agent86-ui 1.2.2

A2UI 1.0 for Rust: message types, catalogs, and validation of agent-generated UI
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
//! The A2UI specification's shared conformance suites for the runtime, the
//! validator, and the message processor, run against `agent86_ui::runtime`.
//!
//! `tests/fixtures/conformance/core/*.json` are the upstream YAML suites
//! (`conformance/core/` at the commit in `spec/UPSTREAM.md`), converted to JSON
//! unchanged so the tests need no YAML parser. Each case names an `action`; a
//! handler per action drives the runtime and checks the expectation.
//!
//! The upstream harness guide's strict rule applies: an unknown action, step
//! op, or key fails the case. The only escape is `UNSUPPORTED`, which records
//! why a case is skipped; an entry that matches no case fails the run, so the
//! list cannot go stale.

use agent86_ui::runtime::{data, expr, DataModel, EvalError, Evaluator, Scope};
use agent86_ui::Catalog;
use serde_json::{json, Value};
use std::collections::BTreeSet;
use std::path::Path;

fn suite(name: &str) -> Vec<Value> {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/conformance/core")
        .join(format!("{name}.json"));
    let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
    let cases: Vec<Value> = serde_json::from_str(&text).unwrap();
    assert!(!cases.is_empty(), "{name} holds no cases");
    cases
}

/// Fail on any key outside `allowed` (plus the metadata every case may carry).
fn known_keys(object: &Value, allowed: &[&str], at: &str) -> Result<(), String> {
    const META: &[&str] = &["name", "description", "features"];
    for key in object.as_object().into_iter().flat_map(|o| o.keys()) {
        if !allowed.contains(&key.as_str()) && !META.contains(&key.as_str()) {
            return Err(format!("Unknown key '{key}' in {at}"));
        }
    }
    Ok(())
}

fn expect_error(object: &Value) -> Option<&Value> {
    object
        .get("expect_error")
        .or_else(|| object.get("expectError"))
}

/// Check an error against `expect_error`: the category the handler mapped it
/// to, and `message` as a regular expression.
fn check_error(expected: &Value, category: &str, message: &str) -> Result<(), String> {
    let want = expected["category"].as_str().unwrap_or_default();
    if want != category {
        return Err(format!("expected a {want}, got a {category}: {message}"));
    }
    if let Some(pattern) = expected.get("message").and_then(Value::as_str) {
        let re = regex::Regex::new(pattern).unwrap();
        if !re.is_match(message) {
            return Err(format!(
                "error message {message:?} does not match {pattern:?}"
            ));
        }
    }
    Ok(())
}

/// Whether a case declares a protocol version before 1.0 (top level first,
/// then its `catalog` block, as the harness guide says).
fn pre_1_0(case: &Value) -> bool {
    let version = case
        .get("protocolVersion")
        .or_else(|| case.get("catalog").and_then(|c| c.get("protocolVersion")))
        .and_then(Value::as_str);
    version.is_some_and(|v| v.starts_with('v'))
}

fn type_name(value: Option<&Value>) -> &'static str {
    match value {
        None => "absent",
        Some(Value::Object(_)) => "object",
        Some(Value::Array(_)) => "list",
        Some(Value::String(_)) => "string",
        Some(Value::Number(_)) => "number",
        Some(Value::Bool(_)) => "boolean",
        Some(Value::Null) => "null",
    }
}

/// Which cases a suite runs.
#[derive(Clone, Copy, PartialEq)]
enum Versions {
    /// Every case: the behavior does not change between protocol versions
    /// (the data model, paths, the template grammar), whatever a case's label.
    All,
    /// Only cases for 1.0 or with no version: results differ by version, and
    /// this implementation reads 1.0 only.
    From1_0,
    /// Only cases marked 1.0: the version-less ones use 0.9's syntax (a
    /// binding written `{"path": ...}`, which 1.0 reads as a literal).
    Only1_0,
}

/// Run every case of `suite` with an `action` in `actions` through `handle`,
/// collecting failures. `unsupported` lists case names to skip, with reasons.
fn run(
    suite_name: &str,
    versions: Versions,
    actions: &[&str],
    unsupported: &[(&str, &str)],
    handle: impl Fn(&Value) -> Result<(), String>,
) {
    let cases = suite(suite_name);
    let mut failures = Vec::new();
    let mut matched = BTreeSet::new();
    let mut ran = 0;
    for case in &cases {
        let name = case["name"].as_str().unwrap_or("?");
        let action = case["action"].as_str().unwrap_or("?");
        if let Some((skip, _)) = unsupported.iter().find(|(skip, _)| *skip == name) {
            matched.insert(*skip);
            continue;
        }
        let marked_1_0 = case
            .get("protocolVersion")
            .or_else(|| case.get("catalog").and_then(|c| c.get("protocolVersion")))
            .and_then(Value::as_str)
            == Some("1.0");
        if (versions == Versions::From1_0 && pre_1_0(case))
            || (versions == Versions::Only1_0 && !marked_1_0)
        {
            // This implementation reads A2UI 1.0 only.
            continue;
        }
        if !actions.contains(&action) {
            failures.push(format!("{suite_name}#{name}: Unknown action '{action}'"));
            continue;
        }
        ran += 1;
        if let Err(problem) = handle(case) {
            failures.push(format!("{suite_name}#{name}: {problem}"));
        }
    }
    for (skip, _) in unsupported {
        if !matched.contains(skip) {
            failures.push(format!(
                "{suite_name}: UNSUPPORTED entry {skip} matches no case"
            ));
        }
    }
    assert!(ran > 0, "{suite_name}: no case ran");
    assert!(
        failures.is_empty(),
        "{} of {} cases in {suite_name} failed:\n{}",
        failures.len(),
        cases.len(),
        failures.join("\n")
    );
}

fn data_model_case(case: &Value) -> Result<(), String> {
    known_keys(
        case,
        &["action", "catalog", "initial", "watch", "steps"],
        "case",
    )?;
    let mut model = DataModel::new(case.get("initial").cloned().unwrap_or_else(|| json!({})));
    let mut watched = Vec::new();
    for path in case
        .get("watch")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        let path = path.as_str().unwrap();
        watched.push((model.watch(path).map_err(|e| e.message)?, path.to_string()));
    }
    for (number, step) in case["steps"].as_array().unwrap().iter().enumerate() {
        let at = format!("step {number}");
        known_keys(
            step,
            &[
                "op",
                "path",
                "value",
                "expect",
                "expect_absent",
                "expect_type",
                "expect_notified",
                "expect_values",
                "expect_error",
            ],
            &at,
        )?;
        let path = step.get("path").and_then(Value::as_str).unwrap_or("/");
        let op = step["op"].as_str().unwrap();
        let outcome = match op {
            "get" => model
                .get(path)
                .map(|value| (Vec::new(), Some(value.cloned()))),
            "set" => model
                .set(path, step["value"].clone())
                .map(|ids| (ids, None)),
            "delete" => model.delete(path).map(|ids| (ids, None)),
            "dispose" => {
                model.dispose();
                Ok((Vec::new(), None))
            }
            // Mutating what the caller passed to `set`: Rust moves the value
            // in, so there is nothing to mutate and nothing can change.
            "mutate_input" => Ok((Vec::new(), None)),
            other => return Err(format!("Unknown op '{other}' at {at}")),
        };
        match (outcome, expect_error(step)) {
            (Err(error), Some(expected)) => check_error(expected, "DataError", &error.message)
                .map_err(|e| format!("{at}: {e}"))?,
            (Err(error), None) => return Err(format!("{at}: unexpected error: {}", error.message)),
            (Ok(_), Some(expected)) => {
                return Err(format!("{at}: expected {expected}, got success"))
            }
            (Ok((notified, got)), None) => {
                let got = got.flatten();
                if let Some(expected) = step.get("expect") {
                    if got.as_ref() != Some(expected) {
                        return Err(format!(
                            "{at}: get {path} gave {got:?}, expected {expected}"
                        ));
                    }
                }
                if step.get("expect_absent").and_then(Value::as_bool) == Some(true) && got.is_some()
                {
                    return Err(format!("{at}: get {path} gave {got:?}, expected absent"));
                }
                if let Some(expected) = step.get("expect_type").and_then(Value::as_str) {
                    let found = type_name(got.as_ref());
                    if found != expected {
                        return Err(format!("{at}: {path} is {found}, expected {expected}"));
                    }
                }
                if let Some(expected) = step.get("expect_notified").and_then(Value::as_array) {
                    let mut found: Vec<&str> = watched
                        .iter()
                        .filter(|(id, _)| notified.contains(id))
                        .map(|(_, path)| path.as_str())
                        .collect();
                    let mut expected: Vec<&str> =
                        expected.iter().filter_map(Value::as_str).collect();
                    found.sort_unstable();
                    expected.sort_unstable();
                    if found != expected {
                        return Err(format!("{at}: notified {found:?}, expected {expected:?}"));
                    }
                }
                if let Some(values) = step.get("expect_values").and_then(Value::as_object) {
                    for (watch_path, expected) in values {
                        let value = model.get(watch_path).map_err(|e| e.message)?;
                        if value != Some(expected) {
                            return Err(format!(
                                "{at}: {watch_path} is {value:?}, expected {expected}"
                            ));
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

#[test]
fn data_model() {
    run(
        "data_model",
        Versions::All,
        &["data_model"],
        &[],
        data_model_case,
    );
}

#[test]
fn data_context() {
    run(
        "data_context",
        Versions::All,
        &["resolve_path"],
        &[],
        |case| {
            known_keys(case, &["action", "catalog", "args", "expect"], "case")?;
            let args = &case["args"];
            known_keys(args, &["path", "contextPath"], "args")?;
            let got = data::resolve(
                args["contextPath"].as_str().unwrap_or("/"),
                args["path"].as_str().unwrap(),
            );
            let expected = case["expect"].as_str().unwrap();
            if got != expected {
                return Err(format!("resolved to {got:?}, expected {expected:?}"));
            }
            Ok(())
        },
    );
}

/// Join adjacent text literals and drop empty ones, as the harness guide says
/// to before comparing: a template fixes the values, not how text is split.
fn joined(parts: &[Value]) -> Vec<Value> {
    let mut out: Vec<Value> = Vec::new();
    for part in parts {
        if let Value::String(text) = part {
            if text.is_empty() {
                continue;
            }
            if let Some(Value::String(previous)) = out.last_mut() {
                previous.push_str(text);
                continue;
            }
        }
        out.push(part.clone());
    }
    out
}

#[test]
fn expressions() {
    run(
        "expressions",
        Versions::All,
        &["parse_expression_template", "validate"],
        &[],
        |case| {
            if case["action"] == "validate" {
                return process_case(case);
            }
            known_keys(
                case,
                &["action", "catalog", "input", "expect", "expect_error"],
                "case",
            )?;
            let input = case["input"].as_str().unwrap();
            match (expr::parse(input), expect_error(case)) {
                (Err(error), Some(expected)) => check_error(expected, "ParseError", &error.0),
                (Err(error), None) => Err(format!("unexpected error: {}", error.0)),
                (Ok(parts), Some(expected)) => Err(format!(
                    "expected {expected}, got {:?}",
                    parts.iter().map(expr::Part::to_json).collect::<Vec<_>>()
                )),
                (Ok(parts), None) => {
                    let got: Vec<Value> = parts.iter().map(expr::Part::to_json).collect();
                    let expected = joined(case["expect"].as_array().unwrap());
                    if joined(&got) == expected {
                        Ok(())
                    } else {
                        Err(format!("parsed to {got:?}, expected {expected:?}"))
                    }
                }
            }
        },
    );
}

/// A catalog a case names by its repository path: the basic catalog is the
/// crate's own; a test catalog is read from the fixtures; a catalog for an
/// earlier protocol version is not available to a 1.0 surface, so `None`.
fn catalog_at(path: &str) -> Option<Catalog> {
    match path {
        "catalogs/basic/v1/catalog.json" => Some(Catalog::basic().clone()),
        p if p.starts_with("catalogs/basic/v0_") => None,
        p => {
            let name = p.strip_prefix("conformance/").unwrap_or(p);
            let file = Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/conformance")
                .join(name);
            let text = std::fs::read_to_string(&file)
                .unwrap_or_else(|e| panic!("{}: {e}", file.display()));
            Some(Catalog::from_value(serde_json::from_str(&text).unwrap()).unwrap())
        }
    }
}

fn evaluate_function_case(case: &Value) -> Result<(), String> {
    if case["action"] == "validate" {
        return process_case(case);
    }
    known_keys(
        case,
        &[
            "action",
            "catalog",
            "protocolVersion",
            "function",
            "args",
            "expect",
            "expectError",
            "surface",
            "catalogId",
            "catalogPaths",
            "dataModel",
        ],
        "case",
    )?;
    let function = case["function"].as_str().unwrap();
    let data = DataModel::new(match case.get("dataModel") {
        Some(Value::Object(map)) => Value::Object(map.clone()),
        _ => json!({}),
    });
    let mut call = serde_json::Map::new();
    call.insert("@call".into(), json!(function));
    call.insert(
        "args".into(),
        case.get("args").cloned().unwrap_or_else(|| json!({})),
    );
    let (evaluator, scope) = match case.get("surface") {
        // On a surface: its catalogs, its default, and the call's own catalogId.
        Some(surface) => {
            known_keys(surface, &["catalogId"], "surface")?;
            let catalogs: Vec<Catalog> = case["catalogPaths"]
                .as_array()
                .unwrap()
                .iter()
                .filter_map(|p| catalog_at(p.as_str().unwrap()))
                .collect();
            if let Some(id) = case.get("catalogId").and_then(Value::as_str) {
                call.insert("catalogId".into(), json!(id));
            }
            let scope = Scope::root(&data, surface.get("catalogId").and_then(Value::as_str));
            (Evaluator::new(catalogs), scope)
        }
        // Directly, in the basic catalog, from a gesture (as the reference
        // harnesses call functions directly).
        None => {
            let mut scope = Scope::root(&data, Some(agent86_ui::BASIC_CATALOG_ID));
            scope.activation = true;
            (Evaluator::basic(), scope)
        }
    };
    let outcome: Result<Value, EvalError> = evaluator.call(&call, &scope);
    match (outcome, expect_error(case)) {
        (Err(error), Some(expected)) => check_error(expected, error.category(), &error.to_string()),
        (Err(error), None) => Err(format!("unexpected {}: {error}", error.category())),
        (Ok(value), Some(expected)) => Err(format!("expected {expected}, got {value}")),
        (Ok(value), None) => {
            let expected = &case["expect"];
            let same = match (expected, &value) {
                // A validation result against a boolean: the version-less
                // cases were written for 0.9, where validators returned
                // booleans; in 1.0 they return results, compared by `valid`.
                (Value::Bool(want), Value::Object(got)) => got.get("valid") == Some(&json!(want)),
                // `{"valid": x}` alone checks only `valid`.
                (Value::Object(want), Value::Object(got))
                    if want.len() == 1 && want.contains_key("valid") =>
                {
                    got.get("valid") == want.get("valid")
                }
                _ => *expected == value,
            };
            if same {
                Ok(())
            } else {
                Err(format!("got {value}, expected {expected}"))
            }
        }
    }
}

#[test]
fn functions() {
    run(
        "functions",
        Versions::From1_0,
        &["evaluate_function", "validate"],
        &[(
            "test_function_format_date_tr35_tokens",
            "validate: the surface processor is not built yet",
        )],
        evaluate_function_case,
    );
}

/// The basic catalog under the id `basic`, which the suites' messages use for
/// it.
fn basic_alias() -> Catalog {
    let mut document = Catalog::basic().document().clone();
    document["catalogId"] = json!("basic");
    Catalog::from_value(document).unwrap()
}

/// An inline test catalog, completed into a valid one: each component gets its
/// discriminator, and the catalog its `anyComponent` and `anyFunction` (the
/// harness guide's advice for a stricter runner, in place of relaxing the
/// crate's own catalog checks).
fn inline_catalog(spec: &Value) -> Catalog {
    let id = spec
        .get("catalogId")
        .and_then(Value::as_str)
        .unwrap_or("basic");
    let Some(components) = spec.get("components").and_then(Value::as_object) else {
        let mut document = Catalog::basic().document().clone();
        document["catalogId"] = json!(id);
        return Catalog::from_value(document).unwrap();
    };
    // A fragment is a URI part, so a non-ASCII name is percent-encoded.
    let encode = |name: &str| -> String {
        name.bytes()
            .map(|b| {
                if b.is_ascii() {
                    (b as char).to_string()
                } else {
                    format!("%{b:02X}")
                }
            })
            .collect()
    };
    let mut defs = Vec::new();
    let mut filled = serde_json::Map::new();
    for (name, schema) in components {
        let mut schema = schema.clone();
        schema["type"] = json!("object");
        schema["properties"]["component"] = json!({"const": name});
        let required = schema["required"].as_array().cloned().unwrap_or_default();
        if !required.contains(&json!("component")) {
            let mut required = required;
            required.push(json!("component"));
            schema["required"] = Value::Array(required);
        }
        defs.push(json!({"$ref": format!("#/components/{}", encode(name))}));
        filled.insert(name.clone(), schema);
    }
    // Functions keep their schemas; `anyFunction` lists them.
    let functions = spec
        .get("functions")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let any_function = if functions.is_empty() {
        json!(false)
    } else {
        let refs: Vec<Value> = functions
            .keys()
            .map(|name| json!({"$ref": format!("#/functions/{}", encode(name))}))
            .collect();
        json!({ "oneOf": refs })
    };
    Catalog::from_value(json!({
        "protocolVersion": "1.0",
        "catalogId": id,
        "components": filled,
        "functions": functions,
        "$defs": {"anyComponent": {"oneOf": defs}, "anyFunction": any_function}
    }))
    .unwrap()
}

fn runtime_for(case: &Value) -> agent86_ui::runtime::Runtime {
    let catalog = match case.get("catalog") {
        Some(spec) if spec.get("components").is_some() => inline_catalog(spec),
        _ => basic_alias(),
    };
    agent86_ui::runtime::Runtime::new([catalog]).unwrap()
}

/// The categories a report's errors fall in, as the shared suites name them.
fn categories(report: &agent86_ui::Report) -> Vec<(&'static str, String)> {
    use agent86_ui::Code;
    report
        .errors
        .iter()
        .map(|problem| {
            let category = match problem.code {
                Code::IntegrityError => "IntegrityError",
                Code::DataError => "DataError",
                _ => "ValidationError",
            };
            (category, problem.message.clone())
        })
        .collect()
}

/// Whether a report has an error of the expected category and message. An
/// integrity error is a validation error too, as in the reference SDKs.
fn report_matches(expected: &Value, report: &agent86_ui::Report) -> Result<(), String> {
    let found = categories(report);
    let want = expected["category"].as_str().unwrap_or_default();
    let pattern = expected
        .get("message")
        .and_then(Value::as_str)
        .map(|p| regex::Regex::new(p).unwrap());
    let ok = found.iter().any(|(category, message)| {
        (*category == want || (want == "ValidationError" && *category == "IntegrityError"))
            && pattern.as_ref().is_none_or(|re| re.is_match(message))
    });
    if ok {
        Ok(())
    } else {
        Err(format!(
            "expected a {want} {:?}, got {found:?}",
            expected.get("message")
        ))
    }
}

/// Scalars compare as strings (a suite writes `5` or `'5'`); structured values
/// structurally, as the reference harness does.
fn property_matches(actual: Option<&Value>, expected: &Value) -> bool {
    let structured = |v: &Value| v.is_object() || v.is_array();
    match actual {
        None => expected.is_null(),
        Some(actual) if structured(actual) || structured(expected) => actual == expected,
        Some(actual) => {
            agent86_ui::runtime::format::to_string(actual)
                == agent86_ui::runtime::format::to_string(expected)
                || (actual.is_null() && expected.is_null())
        }
    }
}

/// Every node of a surface by the names the suites use: its id, and
/// `<id>_<n>` for an instance a template made for item `n`.
fn nodes_by_name(
    runtime: &agent86_ui::runtime::Runtime,
    surface: &str,
) -> std::collections::BTreeMap<String, agent86_ui::runtime::Node> {
    let mut map = std::collections::BTreeMap::new();
    if let Some(tree) = runtime.tree(surface) {
        for node in tree.walk() {
            if node.index.is_some() {
                let ordinal = node.data_path.rsplit('/').next().unwrap_or("");
                if ordinal.parse::<usize>().is_ok() {
                    map.insert(format!("{}_{ordinal}", node.id), node.clone());
                }
            }
            map.entry(node.id.clone()).or_insert_with(|| node.clone());
        }
    }
    // Components not reachable from root resolve at the root context.
    for component in runtime.components(surface).into_iter().flatten() {
        let id = component["id"].as_str().unwrap_or_default().to_string();
        if let std::collections::btree_map::Entry::Vacant(slot) = map.entry(id) {
            if let Some(node) = runtime.node(surface, slot.key()) {
                slot.insert(node);
            }
        }
    }
    map
}

fn check_node(
    node: &agent86_ui::runtime::Node,
    raw: Option<&Value>,
    expected: &Value,
    at: &str,
) -> Result<(), String> {
    for (key, want) in expected.as_object().into_iter().flatten() {
        let got = match key.as_str() {
            "id" => Some(json!(node.id)),
            "component" => Some(json!(node.component)),
            // Envelope keys stay on the component as sent.
            "@metadata" => raw.and_then(|r| r.get(key)).cloned(),
            // A property holding only children is in the node's children.
            _ => node.properties.get(key).cloned().or_else(|| {
                let (_, nodes) = node.children.iter().find(|(name, _)| name == key)?;
                let ids: Vec<&str> = nodes.iter().map(|n| n.id.as_str()).collect();
                Some(if want.is_array() {
                    json!(ids)
                } else {
                    json!(ids.first())
                })
            }),
        };
        if !property_matches(got.as_ref(), want) {
            return Err(format!("{at}.{key} is {got:?}, expected {want}"));
        }
    }
    Ok(())
}

fn check_surfaces(runtime: &agent86_ui::runtime::Runtime, expected: &Value) -> Result<(), String> {
    for (surface, want) in expected["surfaces"].as_object().into_iter().flatten() {
        known_keys(
            want,
            &[
                "components",
                "dataModel",
                "exists",
                "isValid",
                "validationErrors",
                "validationResults",
                "validationResult",
            ],
            "expect.surfaces",
        )?;
        let nodes = nodes_by_name(runtime, surface);
        match want.get("components") {
            Some(Value::Object(components)) => {
                for (id, component) in components {
                    let node = nodes
                        .get(id)
                        .ok_or_else(|| format!("{surface}: no component {id}"))?;
                    let raw = runtime
                        .components(surface)
                        .into_iter()
                        .flatten()
                        .find(|c| c["id"] == json!(id));
                    check_node(node, raw, component, &format!("{surface}.{id}"))?;
                }
            }
            Some(Value::Array(components)) => {
                let count = runtime.components(surface).map_or(0, Iterator::count);
                if count != components.len() {
                    return Err(format!(
                        "{surface}: {count} components, expected {}",
                        components.len()
                    ));
                }
                for component in components {
                    let id = component["id"].as_str().unwrap_or_default();
                    let node = nodes
                        .get(id)
                        .ok_or_else(|| format!("{surface}: no component {id}"))?;
                    let raw = runtime
                        .components(surface)
                        .into_iter()
                        .flatten()
                        .find(|c| c["id"] == json!(id));
                    check_node(node, raw, component, &format!("{surface}.{id}"))?;
                }
            }
            _ => {}
        }
        if let Some(model) = want.get("dataModel") {
            let got = runtime.data_model(surface);
            if got != Some(model) {
                return Err(format!("{surface}: data model {got:?}, expected {model}"));
            }
        }
        let per_node = |field: &str,
                        get: &dyn Fn(&agent86_ui::runtime::Node) -> Value|
         -> Result<(), String> {
            for (id, want) in want
                .get(field)
                .and_then(Value::as_object)
                .into_iter()
                .flatten()
            {
                let node = nodes
                    .get(id)
                    .ok_or_else(|| format!("{surface}: no component {id}"))?;
                let got = get(node);
                let same = match (want, &got) {
                    // `validationResult` is a subset match.
                    (Value::Object(w), Value::Object(g)) if field == "validationResult" => {
                        w.iter().all(|(k, v)| g.get(k) == Some(v))
                    }
                    _ => *want == got,
                };
                if !same {
                    return Err(format!("{surface}.{id}.{field} is {got}, expected {want}"));
                }
            }
            Ok(())
        };
        per_node("isValid", &|node| json!(node.is_valid()))?;
        per_node("validationErrors", &|node| json!(node.validation_errors()))?;
        per_node("validationResults", &|node| json!(node.failures))?;
        per_node("validationResult", &|node| node.validation_result())?;
    }
    Ok(())
}

fn messages_of(value: &Value) -> Vec<Value> {
    match value {
        Value::Array(items) => items.clone(),
        Value::Object(map) if map.contains_key("messages") => {
            map["messages"].as_array().cloned().unwrap_or_default()
        }
        Value::Object(_) => vec![value.clone()],
        _ => Vec::new(),
    }
}

fn process_case(case: &Value) -> Result<(), String> {
    known_keys(
        case,
        &[
            "action",
            "catalog",
            "steps",
            "payload",
            "messages",
            "expect",
            "expectError",
            "expect_error",
        ],
        "case",
    )?;
    let mut runtime = runtime_for(case);
    let steps: Vec<Value> = match case.get("steps").and_then(Value::as_array) {
        Some(steps) => steps.clone(),
        None => vec![json!({
            "payload": case.get("payload").or_else(|| case.get("messages")).cloned().unwrap_or(json!([])),
        })],
    };
    let last = steps.len().saturating_sub(1);
    for (number, step) in steps.iter().enumerate() {
        known_keys(
            step,
            &[
                "payload",
                "messages",
                "expect",
                "expectError",
                "expect_error",
            ],
            "step",
        )?;
        let messages = messages_of(
            step.get("payload")
                .or_else(|| step.get("messages"))
                .unwrap_or(&json!([])),
        );
        let report = runtime.apply(&messages);
        // A case-level expectError belongs to the last step.
        let expected = expect_error(step).or(if number == last {
            expect_error(case)
        } else {
            None
        });
        match expected {
            Some(expected) => {
                report_matches(expected, &report).map_err(|e| format!("step {number}: {e}"))?
            }
            None => {
                if !report.is_ok() {
                    return Err(format!(
                        "step {number}: unexpected errors {:?}",
                        categories(&report)
                    ));
                }
                if let Some(expect) = step.get("expect").filter(|e| !e.is_null()) {
                    check_surfaces(&runtime, expect).map_err(|e| format!("step {number}: {e}"))?;
                }
            }
        }
    }
    if let Some(expect) = case.get("expect").filter(|e| !e.is_null()) {
        check_surfaces(&runtime, expect)?;
    }
    Ok(())
}

const PROCESSOR: &[&str] = &["validate", "process_messages"];

#[test]
fn index_function() {
    run(
        "index_function",
        Versions::From1_0,
        PROCESSOR,
        &[],
        process_case,
    );
}

#[test]
fn validation_result() {
    run(
        "validation_result",
        Versions::From1_0,
        PROCESSOR,
        &[],
        process_case,
    );
}

#[test]
fn data_deletion() {
    run(
        "data_deletion",
        Versions::From1_0,
        PROCESSOR,
        &[],
        process_case,
    );
}

#[test]
fn data_model_pointers() {
    run(
        "data_model_pointers",
        Versions::From1_0,
        PROCESSOR,
        &[],
        process_case,
    );
}

#[test]
fn reserved_keys() {
    run(
        "reserved_keys",
        Versions::From1_0,
        PROCESSOR,
        &[],
        process_case,
    );
}

/// The local functions the reference harness registers for the action cases:
/// `incrementCounter` adds `step` (default 1) to the number at `path` (default
/// `/counter`); `failingAction` always fails.
fn action_runtime() -> agent86_ui::runtime::Runtime {
    use agent86_ui::{Callers, FunctionDef};
    let mut runtime = agent86_ui::runtime::Runtime::new([basic_alias()]).unwrap();
    let def = FunctionDef {
        return_type: "void".into(),
        callers: Callers::RendererOnly,
        requires_user_activation: false,
    };
    runtime.register(
        "incrementCounter",
        def.clone(),
        std::sync::Arc::new(|args, scope| {
            let path = args
                .get("path")
                .and_then(Value::as_str)
                .unwrap_or("/counter");
            let step = args.get("step").and_then(Value::as_f64).unwrap_or(1.0);
            let current = scope
                .get(path)
                .as_ref()
                .map_or(0.0, agent86_ui::runtime::format::to_number);
            scope.set(
                path,
                agent86_ui::runtime::expr::number_value(current + step),
            );
            Ok(Value::Null)
        }),
    );
    runtime.register(
        "failingAction",
        def,
        std::sync::Arc::new(|_, _| Err("Action function failed".into())),
    );
    runtime
}

fn dispatch_case(case: &Value) -> Result<(), String> {
    known_keys(
        case,
        &[
            "action",
            "protocolVersion",
            "actionPayload",
            "dataModel",
            "scope",
            "surfaceId",
            "sourceComponentId",
            "userActivation",
            "metadata",
            "expectDispatched",
            "expectDataModel",
            "expectError",
        ],
        "case",
    )?;
    let mut runtime = action_runtime();
    let surface = case
        .get("surfaceId")
        .and_then(Value::as_str)
        .unwrap_or("main");
    let report = runtime.apply(&[json!({
        "version": "1.0",
        "createSurface": {
            "surfaceId": surface,
            "catalogId": "basic",
            "dataModel": case.get("dataModel").cloned().unwrap_or_else(|| json!({}))
        }
    })]);
    assert!(report.is_ok(), "{report:?}");
    let scope = case.get("scope").and_then(Value::as_str).unwrap_or("/");
    let index = scope
        .rsplit('/')
        .next()
        .and_then(|s| s.parse::<usize>().ok());
    let mut gesture = agent86_ui::runtime::Gesture::new(
        surface,
        case.get("sourceComponentId")
            .and_then(Value::as_str)
            .unwrap_or("button"),
    );
    gesture.data_path = scope.into();
    gesture.index = index;
    gesture.activation = case
        .get("userActivation")
        .and_then(Value::as_bool)
        .unwrap_or(true);
    gesture.metadata = case.get("metadata").cloned();
    gesture.timestamp = Some("2026-11-22T10:00:00Z".into());

    let outcome = runtime.dispatch(&case["actionPayload"], &gesture);
    match (outcome, case.get("expectError")) {
        (Err(error), Some(expected)) => {
            known_keys(
                expected,
                &["code", "surfaceId", "message", "category"],
                "expectError",
            )?;
            if let Some(code) = expected.get("code").and_then(Value::as_str) {
                if error.code != code {
                    return Err(format!("error code {}, expected {code}", error.code));
                }
            }
            if let Some(category) = expected.get("category").and_then(Value::as_str) {
                let mapped = if error.code == "VALIDATION_FAILED" {
                    "ValidationError"
                } else {
                    "?"
                };
                if mapped != category {
                    return Err(format!("error {} is not a {category}", error.code));
                }
            }
            if let Some(id) = expected.get("surfaceId").and_then(Value::as_str) {
                if error.surface_id != id {
                    return Err(format!("error on {}, expected {id}", error.surface_id));
                }
            }
            if let Some(message) = expected.get("message").and_then(Value::as_str) {
                if !error.message.contains(message) {
                    return Err(format!(
                        "error {:?} does not mention {message:?}",
                        error.message
                    ));
                }
            }
        }
        (Err(error), None) => return Err(format!("unexpected error {error}")),
        (Ok(dispatch), Some(expected)) => {
            return Err(format!("expected {expected}, got {dispatch:?}"))
        }
        (Ok(dispatch), None) => {
            let sent = dispatch.action.map(|a| serde_json::to_value(a).unwrap());
            match (case.get("expectDispatched"), &sent) {
                (Some(Value::Null), Some(sent)) => {
                    return Err(format!("expected nothing sent, got {sent}"))
                }
                (Some(Value::Object(want)), None) => {
                    return Err(format!("expected {want:?}, nothing sent"))
                }
                (Some(Value::Object(want)), Some(sent)) => {
                    for (key, expected) in want {
                        if key == "timestampIso8601" {
                            let ok = sent["timestamp"]
                                .as_str()
                                .is_some_and(|t| t.parse::<jiff::Timestamp>().is_ok());
                            if !ok {
                                return Err(format!(
                                    "timestamp {} is not ISO 8601",
                                    sent["timestamp"]
                                ));
                            }
                            continue;
                        }
                        let got = sent.get(key).cloned().unwrap_or(Value::Null);
                        if got != *expected {
                            return Err(format!("dispatched {key} is {got}, expected {expected}"));
                        }
                    }
                }
                _ => {}
            }
        }
    }
    if let Some(model) = case.get("expectDataModel") {
        let got = runtime.data_model(surface);
        if got != Some(model) {
            return Err(format!("data model {got:?}, expected {model}"));
        }
    }
    Ok(())
}

#[test]
fn actions() {
    run(
        "actions",
        Versions::Only1_0,
        &["dispatch_action"],
        &[],
        dispatch_case,
    );
}

// ---------------------------------------------------------------------------
// The validator and message processor suites (`validator_v1_0`,
// `message_processor_v1_0`): batches through a strict `Runtime`, as the
// harness guide says (`strictMode: false` relaxes it; a step's
// `validationConfig` replaces the rules for that step, a rule it leaves out
// being strict).
//
// Error messages are matched as the Python reference harness matches them: a
// case writes one SDK's wording, so the expected text is looked for without
// case, with the same few alternations for the other SDKs' phrasing, or as a
// regular expression. `details` lists each SDK's own model errors
// (`messages.0.version`, `missing_field`) and is not compared; the verdict,
// the category, the message, and the renderer error are.

/// The catalogs a case declares, each made a 1.0 catalog this crate loads;
/// a catalog for another protocol version is left out, since a 1.0 renderer
/// cannot use it.
fn declared_catalogs(case: &Value) -> Vec<Catalog> {
    let mut catalogs = Vec::new();
    for path in case
        .get("catalogPaths")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        if let Some(catalog) = catalog_at(path.as_str().unwrap()) {
            catalogs.push(catalog);
        }
    }
    if let Some(spec) = case
        .get("catalog")
        .filter(|s| s.get("components").is_some())
    {
        catalogs.push(inline_catalog(spec));
    }
    for spec in case
        .get("catalogs")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        let version = spec
            .get("protocolVersion")
            .or_else(|| case.get("protocolVersion"))
            .and_then(Value::as_str);
        if version.is_some_and(|v| v != "1.0") {
            continue;
        }
        let catalog = if spec.get("components").is_none() {
            // A stub, the id and version alone: an empty catalog where the
            // case is about capabilities, else (as Python's harness does) the
            // basic catalog under that id.
            let id = spec["catalogId"].as_str().unwrap();
            if case["action"] == "get_renderer_capabilities" {
                Catalog::from_value(json!({
                    "protocolVersion": "1.0",
                    "catalogId": id,
                    "components": {},
                    "$defs": {"anyComponent": false, "anyFunction": false}
                }))
                .unwrap()
            } else {
                let mut document = Catalog::basic().document().clone();
                document["catalogId"] = json!(id);
                Catalog::from_value(document).unwrap()
            }
        } else {
            Catalog::from_value(spec.clone()).unwrap_or_else(|_| inline_catalog(spec))
        };
        catalogs.push(catalog);
    }
    catalogs
}

/// Every `createSurface.catalogId` a case's messages name.
fn surface_catalog_ids(case: &Value) -> BTreeSet<String> {
    let mut ids = BTreeSet::new();
    let mut batches = vec![case.get("messages").or_else(|| case.get("payload"))];
    for step in case
        .get("steps")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        batches.push(step.get("messages").or_else(|| step.get("payload")));
    }
    for batch in batches.into_iter().flatten() {
        for message in messages_of(batch) {
            if let Some(id) = message
                .get("createSurface")
                .and_then(|c| c.get("catalogId"))
                .and_then(Value::as_str)
            {
                ids.insert(id.to_string());
            }
        }
    }
    ids
}

fn expects_catalog_error(case: &Value) -> bool {
    let mut all = vec![expect_error(case)];
    for step in case
        .get("steps")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        all.push(expect_error(step));
    }
    all.into_iter()
        .flatten()
        .any(|e| e.get("category").and_then(Value::as_str) == Some("CatalogError"))
}

/// The case's runtime: its declared catalogs, plus (the harness guide's
/// advice for a stricter runner) the first of them, or the basic catalog, under
/// each surface catalog id the case uses without defining it, unless the case
/// is about a catalog that cannot be found.
fn suite_runtime(case: &Value) -> agent86_ui::runtime::Runtime {
    let mut catalogs = declared_catalogs(case);
    if !expects_catalog_error(case) {
        let excluded: BTreeSet<&str> = case
            .get("catalogs")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(|c| c.get("catalogId").and_then(Value::as_str))
            .collect();
        let base = catalogs
            .first()
            .cloned()
            .unwrap_or_else(|| Catalog::basic().clone());
        for id in surface_catalog_ids(case) {
            if catalogs.iter().any(|c| c.id() == id) || excluded.contains(id.as_str()) {
                continue;
            }
            if id.contains("v0_9") {
                continue;
            }
            let mut document = base.document().clone();
            document["catalogId"] = json!(id);
            catalogs.push(Catalog::from_value(document).unwrap());
        }
    }
    let mut runtime = agent86_ui::runtime::Runtime::new(catalogs).unwrap();
    runtime.set_rules(case_rules(case));
    runtime
}

fn case_rules(case: &Value) -> agent86_ui::Rules {
    if case.get("strictMode") == Some(&json!(false)) {
        agent86_ui::Rules::RELAXED
    } else {
        agent86_ui::Rules::STRICT
    }
}

/// A step's `validationConfig` as rules; a flag left out is strict.
fn step_rules(config: &Value) -> Result<agent86_ui::Rules, String> {
    known_keys(
        config,
        &[
            "allowOrphanComponents",
            "allowDanglingReferences",
            "allowMissingRoot",
        ],
        "validationConfig",
    )?;
    let flag = |name: &str| config.get(name).and_then(Value::as_bool).unwrap_or(false);
    Ok(agent86_ui::Rules::STRICT
        .allowing_orphans(flag("allowOrphanComponents"))
        .allowing_dangling_references(flag("allowDanglingReferences"))
        .allowing_missing_root(flag("allowMissingRoot")))
}

/// The Python reference harness's message match (`_error_message_matches`).
fn message_matches(expected: &str, actual: &str) -> bool {
    let norm = |s: &str| s.to_lowercase().replace('"', "'");
    let (want, got) = (norm(expected), norm(actual));
    if got.contains(&want) {
        return true;
    }
    if (want.contains("orphan") && got.contains("not reachable"))
        || (want.contains("circular")
            && (got.contains("circular") || got.contains("self-reference")))
    {
        return true;
    }
    regex::Regex::new(expected).is_ok_and(|re| re.is_match(actual))
}

fn category_of(problem: &agent86_ui::Problem) -> &'static str {
    match problem.code {
        agent86_ui::Code::IntegrityError => "IntegrityError",
        agent86_ui::Code::DataError => "DataError",
        agent86_ui::Code::RecursionLimitExceeded => "RecursionError",
        agent86_ui::Code::CatalogNotFound => "CatalogError",
        _ => "ValidationError",
    }
}

/// Whether a report holds the error a case expects.
fn suite_error_matches(expected: &Value, report: &agent86_ui::Report) -> Result<(), String> {
    let (category, message) = match expected {
        Value::String(text) => (None, Some(text.as_str())),
        _ => {
            known_keys(
                expected,
                &[
                    "category",
                    "message",
                    "surfaceId",
                    "path",
                    "details",
                    "rendererError",
                ],
                "expectError",
            )?;
            (
                expected.get("category").and_then(Value::as_str),
                expected.get("message").and_then(Value::as_str),
            )
        }
    };
    if report.is_ok() {
        return Err(format!(
            "expected an error {expected}, the batch was accepted"
        ));
    }
    let category_ok = |problem: &agent86_ui::Problem| match category {
        None => true,
        Some(want) => {
            // As the reference harness maps categories: an integrity or
            // recursion error is a validation error too, and a recursion error
            // an integrity error.
            let got = category_of(problem);
            got == want
                || (want == "ValidationError" && matches!(got, "IntegrityError" | "RecursionError"))
                || (want == "IntegrityError" && got == "RecursionError")
        }
    };
    let found = report.errors.iter().any(|problem| {
        category_ok(problem)
            && message.is_none_or(|m| message_matches(m, &problem.message))
            && expected
                .get("surfaceId")
                .and_then(Value::as_str)
                .is_none_or(|s| problem.surface_id.as_deref() == Some(s))
    });
    if !found {
        return Err(format!(
            "expected {expected}, got {:?}",
            report
                .errors
                .iter()
                .map(|p| format!("{} {}: {}", category_of(p), p.code, p.message))
                .collect::<Vec<_>>()
        ));
    }
    if let Some(wire) = expected.get("rendererError") {
        let error = &wire["error"];
        let ok = report.errors.iter().any(|problem| {
            error["code"].as_str() == Some(problem.code.as_str())
                && error
                    .get("message")
                    .and_then(Value::as_str)
                    .is_none_or(|m| message_matches(m, &problem.message))
                && error
                    .get("surfaceId")
                    .and_then(Value::as_str)
                    .is_none_or(|s| problem.surface_id.as_deref() == Some(s))
        });
        if !ok {
            return Err(format!(
                "expected renderer error {error}, got {:?}",
                report
                    .errors
                    .iter()
                    .map(|p| format!("{} at {:?}: {}", p.code, p.path, p.message))
                    .collect::<Vec<_>>()
            ));
        }
    }
    Ok(())
}

fn suite_process_case(case: &Value) -> Result<(), String> {
    known_keys(
        case,
        &[
            "action",
            "protocolVersion",
            "catalog",
            "catalogPaths",
            "catalogs",
            "strictMode",
            "steps",
            "messages",
            "payload",
            "expect",
            "expectError",
            "args",
        ],
        "case",
    )?;
    let mut runtime = suite_runtime(case);
    let steps: Vec<Value> = match case.get("steps").and_then(Value::as_array) {
        Some(steps) => steps.clone(),
        None => vec![json!({
            "messages": case.get("messages").or_else(|| case.get("payload")).cloned().unwrap_or(json!([])),
        })],
    };
    let last = steps.len().saturating_sub(1);
    for (number, step) in steps.iter().enumerate() {
        known_keys(
            step,
            &[
                "messages",
                "payload",
                "expect",
                "expectError",
                "validationConfig",
            ],
            "step",
        )?;
        let messages = messages_of(
            step.get("messages")
                .or_else(|| step.get("payload"))
                .unwrap_or(&json!([])),
        );
        if let Some(config) = step.get("validationConfig") {
            runtime.set_rules(step_rules(config)?);
        }
        let report = runtime.apply(&messages);
        runtime.set_rules(case_rules(case));
        let expected = expect_error(step).or(if number == last {
            expect_error(case)
        } else {
            None
        });
        match expected {
            Some(expected) => {
                suite_error_matches(expected, &report).map_err(|e| format!("step {number}: {e}"))?
            }
            None => {
                if !report.is_ok() {
                    return Err(format!(
                        "step {number}: unexpected errors {:?}",
                        report
                            .errors
                            .iter()
                            .map(|p| format!("{} at {:?}: {}", p.code, p.path, p.message))
                            .collect::<Vec<_>>()
                    ));
                }
                let expect = step.get("expect").or(if number == last {
                    case.get("expect")
                } else {
                    None
                });
                if let Some(expect) = expect.filter(|e| !e.is_null()) {
                    check_suite_surfaces(&runtime, expect)
                        .map_err(|e| format!("step {number}: {e}"))?;
                }
            }
        }
    }
    Ok(())
}

/// `expect.surfaces` for the processor suites: `exists` and `sendDataModel`
/// here, the rest through [`check_surfaces`].
fn check_suite_surfaces(
    runtime: &agent86_ui::runtime::Runtime,
    expect: &Value,
) -> Result<(), String> {
    known_keys(expect, &["surfaces"], "expect")?;
    let mut rest = serde_json::Map::new();
    for (id, want) in expect["surfaces"].as_object().into_iter().flatten() {
        let mut want = want.clone();
        let object = want.as_object_mut().unwrap();
        if let Some(exists) = object.remove("exists") {
            let got = runtime.surface_ids().any(|s| s == id);
            if Some(got) != exists.as_bool() {
                return Err(format!("surface {id} exists is {got}, expected {exists}"));
            }
        }
        if let Some(metadata) = object.remove("metadata") {
            let got = runtime.surface_metadata(id);
            if got != Some(&metadata) {
                return Err(format!(
                    "surface {id} metadata is {got:?}, expected {metadata}"
                ));
            }
        }
        if let Some(send) = object.remove("sendDataModel") {
            let got = runtime.sends_data_model(id);
            if Some(got) != send.as_bool() {
                return Err(format!(
                    "surface {id} sendDataModel is {got}, expected {send}"
                ));
            }
        }
        rest.insert(id.clone(), want);
    }
    check_surfaces(runtime, &json!({ "surfaces": rest }))
}

fn capabilities_case(case: &Value) -> Result<(), String> {
    known_keys(
        case,
        &["action", "protocolVersion", "catalogs", "args", "expect"],
        "case",
    )?;
    known_keys(&case["args"], &["version", "includeInlineCatalogs"], "args")?;
    let runtime = agent86_ui::runtime::Runtime::new(declared_catalogs(case)).unwrap();
    let inline = case["args"]["includeInlineCatalogs"]
        .as_bool()
        .unwrap_or(false);
    let got = runtime.capabilities(inline);
    agent86_ui::check_renderer_capabilities(&got).map_err(|e| format!("{e:?}"))?;
    if got != case["expect"] {
        return Err(format!("capabilities {got}, expected {}", case["expect"]));
    }
    Ok(())
}

fn renderer_data_model_case(case: &Value) -> Result<(), String> {
    known_keys(
        case,
        &[
            "action",
            "protocolVersion",
            "catalogPaths",
            "steps",
            "messages",
            "args",
            "expect",
        ],
        "case",
    )?;
    if let Some(args) = case.get("args") {
        known_keys(args, &["version"], "args")?;
    }
    let mut runtime = suite_runtime(case);
    let steps: Vec<Value> = match case.get("steps").and_then(Value::as_array) {
        Some(steps) => steps.clone(),
        None => vec![json!({"messages": case["messages"]})],
    };
    for step in &steps {
        known_keys(step, &["messages"], "step")?;
        // A message for another version is not this renderer's to apply.
        let messages: Vec<Value> = messages_of(&step["messages"])
            .into_iter()
            .filter(|m| m["version"] == "1.0")
            .collect();
        let report = runtime.apply(&messages);
        if !report.is_ok() {
            return Err(format!("unexpected errors {:?}", report.errors));
        }
    }
    let got = runtime.renderer_data_model().unwrap_or(Value::Null);
    if got != case["expect"] {
        return Err(format!(
            "renderer data model {got}, expected {}",
            case["expect"]
        ));
    }
    Ok(())
}

fn processor_suite_case(case: &Value) -> Result<(), String> {
    match case["action"].as_str().unwrap() {
        "get_renderer_capabilities" => capabilities_case(case),
        "get_renderer_data_model" => renderer_data_model_case(case),
        _ => suite_process_case(case),
    }
}

// Why the cases left out of the processor suites are left out. Each is
// recorded in the plan as work before the crate is first published; an entry
// that stops matching a case fails the run.
const STUB_CATALOGS: &str = "the case's catalogs are stubs (an id alone) holding a component the basic catalog lacks; it needs a permissive stand-in catalog, which this harness does not build";
const CLOSED_SCHEMA: &str = "a catalog component schema with additionalProperties: false rejects the envelope's own keys (id, @catalogId) under the specification's schemas as composed; the reference SDKs check a component's properties apart from its envelope";
const AGENT_FUNCTIONS: &str = "agent functions (schema-only functions, routing an undeclared call to the agent) are left out of agent86UI's first version (ADR 0005)";
const V0_9: &str = "asks for a 0.9 renderer data model; this renderer reads 1.0 only";

#[test]
fn validator_v1_0() {
    run(
        "validator_v1_0",
        Versions::From1_0,
        PROCESSOR,
        &[],
        processor_suite_case,
    );
}

#[test]
fn message_processor_v1_0() {
    run(
        "message_processor_v1_0",
        Versions::From1_0,
        &[
            "validate",
            "process_messages",
            "get_renderer_capabilities",
            "get_renderer_data_model",
        ],
        &[
            (
                "test_v10_strict_function_call_to_schema_only_function_of_surface_catalog",
                AGENT_FUNCTIONS,
            ),
            (
                "test_v10_function_call_naming_catalog_with_valid_args",
                AGENT_FUNCTIONS,
            ),
            (
                "test_v10_nested_call_in_args_naming_its_catalog",
                AGENT_FUNCTIONS,
            ),
            (
                "test_v10_calls_in_lists_naming_their_catalog",
                AGENT_FUNCTIONS,
            ),
            ("test_v10_component_catalog_override", STUB_CATALOGS),
            (
                "test_v10_component_from_named_catalog_with_closed_schema_accepted",
                CLOSED_SCHEMA,
            ),
            (
                "test_v10_call_to_undeclared_function_without_strict_mode_accepted",
                AGENT_FUNCTIONS,
            ),
            (
                "test_v10_get_renderer_data_model_excludes_surface_without_default_from_v09",
                V0_9,
            ),
            (
                "test_v10_get_renderer_data_model_filters_by_surface_protocol_version",
                V0_9,
            ),
        ],
        processor_suite_case,
    );
}