arora-behavior-tree 8.3.0

The Arora behavior tree: Groot-compatible trees ticking Arora modules.
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
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
//! Engine-free tests. Tests that need a real engine moved to `arora-sdk`.
//!
//! The basic control nodes (seq, seq_star, fallback, parallel, succeed, fail,
//! run) are dispatched natively, so their execution can be exercised here with a
//! minimal registry-backed [`CallBridge`] — no wasm module, no engine.
use crate::arora_generated::behavior_tree::status::Status;
use crate::load_behavior_tree_yaml;
use crate::nodes;
use crate::tree_node::TreeNode;
use crate::{run_behavior_tree, BehaviorTree, BehaviorTreeRuntime, ModuleFunction};
use anyhow::Result;
use arora_types::call::{Call, CallBridge, CallError, CallResult, Callable, CallableId};
use arora_types::record::module::frozen::Function;
use arora_types::record::ty::{FrozenTy, PrimitiveKind};
use arora_types::value::Value;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use uuid::Uuid;

#[test]
pub fn load_parse_error() -> Result<()> {
    let tree_yaml = "I'm singing in the rain...";
    assert!(load_behavior_tree_yaml(tree_yaml).is_err());
    Ok(())
}

#[test]
pub fn load_simple_tree() -> Result<()> {
    let tree_yaml = &crate::schema::tests::SIMPLE_TREE_YAML;
    load_behavior_tree_yaml(tree_yaml)?;
    Ok(())
}

/// Two node parameters that reference the **same** variable id must resolve to a
/// single shared cell, so a write through one is visible through the other —
/// that is what makes `{var}` a shared blackboard entry across nodes.
///
/// Regression test for the variable-sharing bug: a freshly-referenced variable
/// was inserted into the variables map under a fresh `Uuid::new_v4()` instead of
/// its own `variable_id`, so the next lookup by `variable_id` missed and a second,
/// independent cell was created.
#[test]
fn shared_variable_id_resolves_to_one_cell() {
    use crate::schema::{Expression, NodeParameterId};
    use crate::variable::VariableCell;

    let var_id = Uuid::new_v4();
    let mut variables: HashMap<Uuid, VariableCell> = HashMap::new();
    let mut node_parameters: HashMap<NodeParameterId, VariableCell> = HashMap::new();

    let param_a = NodeParameterId {
        node: Uuid::new_v4(),
        parameter: Uuid::new_v4(),
    };
    let param_b = NodeParameterId {
        node: Uuid::new_v4(),
        parameter: Uuid::new_v4(),
    };

    let cell_a = crate::setup_node_parameter_variable(
        &param_a,
        &Expression::VariableId(var_id),
        &mut variables,
        &mut node_parameters,
        &|_| None,
        &HashMap::new(),
    )
    .unwrap();
    let cell_b = crate::setup_node_parameter_variable(
        &param_b,
        &Expression::VariableId(var_id),
        &mut variables,
        &mut node_parameters,
        &|_| None,
        &HashMap::new(),
    )
    .unwrap();

    cell_a.set(Value::Boolean(true));
    assert_eq!(
        cell_b.get_or_unit(),
        Value::Boolean(true),
        "two parameters bound to the same variable id must share one cell"
    );
}

/// A `{var}` whose name the resolver knows binds to the data store: the cell and
/// the store key are the same storage, both ways. This is the Direct convention
/// (variable name == store key) the runtime supplies — exercised here against a
/// real [`SimpleDataStore`] so the behavior-tree crate's `Slot` plumbing is
/// covered without an engine.
#[test]
fn resolved_variable_is_store_backed() {
    use crate::schema::{Expression, NodeParameterId};
    use crate::variable::VariableCell;
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::data::{DataStore, Key, StateChange};

    let store = SimpleDataStore::new();
    let resolver = {
        let store = store.clone();
        // `DataStore::slot` already hands back a `Box<dyn Slot>`.
        move |name: &str| Some(store.slot(&Key::from(name)))
    };

    let var_id = Uuid::new_v4();
    let names = HashMap::from([(var_id, "battery.level".to_string())]);

    let mut variables: HashMap<Uuid, VariableCell> = HashMap::new();
    let mut node_parameters: HashMap<NodeParameterId, VariableCell> = HashMap::new();
    let param = NodeParameterId {
        node: Uuid::new_v4(),
        parameter: Uuid::new_v4(),
    };

    let cell = crate::setup_node_parameter_variable(
        &param,
        &Expression::VariableId(var_id),
        &mut variables,
        &mut node_parameters,
        &resolver,
        &names,
    )
    .unwrap();

    // Write through the cell, read through the store.
    cell.set(Value::from(1.0_f64));
    assert_eq!(
        store.read(&[Key::from("battery.level")]),
        vec![Some(Value::from(1.0_f64))],
        "a write through the resolved cell must reach the store key"
    );

    // Write through the store, read through the cell.
    store
        .write(StateChange::set("battery.level", Value::from(2.0_f64)))
        .unwrap();
    assert_eq!(
        cell.get(),
        Some(Value::from(2.0_f64)),
        "a write through the store key must be visible through the resolved cell"
    );
}

// Native execution harness
//================================================================
/// A leaf whose status is supplied by a shared, mutable cell, so a test can
/// change what it returns between ticks. Modeled as a plain (non-control) node
/// so it dispatches through `arora_call` — the path real module leaves use.
type LeafStatuses = Rc<RefCell<HashMap<Uuid, Status>>>;

/// Records how many times each leaf function id was ticked.
type LeafTicks = Rc<RefCell<HashMap<Uuid, u32>>>;

/// A [`CallBridge`] that registers/invokes callables natively and answers
/// `arora_call` for the test's scripted leaf functions. Native behavior trees
/// never call into real modules.
struct TestBridge {
    registered: HashMap<u64, Rc<dyn Callable>>,
    next_id: u64,
    leaf_statuses: LeafStatuses,
    leaf_ticks: LeafTicks,
}

impl TestBridge {
    fn new(leaf_statuses: LeafStatuses, leaf_ticks: LeafTicks) -> Self {
        Self {
            registered: HashMap::new(),
            next_id: 0,
            leaf_statuses,
            leaf_ticks,
        }
    }

    fn empty() -> Self {
        Self::new(
            Rc::new(RefCell::new(HashMap::new())),
            Rc::new(RefCell::new(HashMap::new())),
        )
    }
}

impl CallBridge for TestBridge {
    fn arora_call(&mut self, call: Call) -> Result<CallResult, CallError> {
        *self.leaf_ticks.borrow_mut().entry(call.id).or_insert(0) += 1;
        let status = self
            .leaf_statuses
            .borrow()
            .get(&call.id)
            .cloned()
            .ok_or(CallError::FunctionNotFound { id: call.id })?;
        Ok(CallResult {
            ret: status.into(),
            mutated: Vec::new(),
        })
    }

    fn arora_register_callable(&mut self, callable: Rc<dyn Callable>) -> CallableId {
        let id = self.next_id;
        self.next_id += 1;
        self.registered.insert(id, callable);
        CallableId { id }
    }

    fn arora_unregister_callable(&mut self, callable_id: &CallableId) {
        self.registered.remove(&callable_id.id);
    }

    fn arora_call_indirect(&mut self, callable_id: &CallableId) -> Result<Value, CallError> {
        let callable = self
            .registered
            .get(&callable_id.id)
            .cloned()
            .ok_or(CallError::Generic {
                message: format!("unknown callable {}", callable_id.id),
            })?;
        callable.call(self)
    }
}

/// A scripted leaf node: a non-control node dispatched through `arora_call`,
/// whose status comes from the bridge's `leaf_statuses`.
fn scripted_leaf(function: Uuid) -> TreeNode {
    TreeNode {
        function,
        children: None,
        parameters: HashMap::new(),
    }
}

/// A minimal `ModuleFunction` for a scripted leaf, so the native tick path can
/// build the (empty) call. The leaf has no parameters and returns a status.
fn scripted_leaf_function(function: Uuid) -> ModuleFunction {
    ModuleFunction {
        module_id: Uuid::nil(),
        function_id: function,
        function_name: "scripted_leaf".to_string(),
        function: Function {
            parameters: HashMap::new(),
            parameter_ordering: Vec::new(),
            return_ty: FrozenTy::from(PrimitiveKind::U8),
        },
    }
}

pub(crate) fn build(node: TreeNode) -> BehaviorTree {
    node.try_into().expect("tree builds")
}

/// Tick a tree (with only native nodes) exactly once.
fn tick_once(tree: &BehaviorTree) -> Status {
    let mut bridge = TestBridge::empty();
    let mut runtime = BehaviorTreeRuntime::setup(tree, Rc::new(HashMap::new()), &mut bridge, false)
        .expect("runtime sets up");
    runtime.tick().expect("tick succeeds")
}

/// Run a tree (with only native nodes) to a terminal status.
fn run(tree: &BehaviorTree) -> Status {
    let mut bridge = TestBridge::empty();
    run_behavior_tree(tree, Rc::new(HashMap::new()), &mut bridge, false).expect("run succeeds")
}

// seq
//----------------------------------------------------------------
#[test]
fn seq_all_success_is_success() {
    let tree = build(nodes::seq(vec![nodes::succeed(), nodes::succeed()]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn seq_first_failure_is_failure() {
    // `fail()` is native, so it short-circuits before the later child can run.
    // Make the later child a leaf that has no scripted status, so reaching it
    // would surface as an error rather than a silent pass.
    let later = Uuid::from_u128(0xA1);
    let tree = build(nodes::seq(vec![nodes::fail(), scripted_leaf(later)]));
    assert_eq!(tick_once(&tree), Status::Failure);
}

#[test]
fn seq_running_child_is_running() {
    let tree = build(nodes::seq(vec![nodes::succeed(), nodes::run()]));
    assert_eq!(tick_once(&tree), Status::Running);
}

// fallback
//----------------------------------------------------------------
#[test]
fn fallback_first_success_is_success() {
    let tree = build(nodes::fallback(vec![nodes::succeed(), nodes::fail()]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn fallback_all_failure_is_failure() {
    let tree = build(nodes::fallback(vec![nodes::fail(), nodes::fail()]));
    assert_eq!(run(&tree), Status::Failure);
}

#[test]
fn fallback_empty_is_success() {
    let tree = build(nodes::fallback(vec![]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn fallback_running_child_is_running() {
    let tree = build(nodes::fallback(vec![nodes::run(), nodes::succeed()]));
    assert_eq!(tick_once(&tree), Status::Running);
}

// parallel
//----------------------------------------------------------------
#[test]
fn parallel_all_success_is_success() {
    let tree = build(nodes::parallel(vec![nodes::succeed(), nodes::succeed()]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn parallel_any_failure_is_failure() {
    let tree = build(nodes::parallel(vec![
        nodes::succeed(),
        nodes::fail(),
        nodes::succeed(),
    ]));
    assert_eq!(run(&tree), Status::Failure);
}

#[test]
fn parallel_mixed_running_is_running() {
    // A running child with no failing child yields Running.
    let tree = build(nodes::parallel(vec![nodes::succeed(), nodes::run()]));
    assert_eq!(tick_once(&tree), Status::Running);
}

/// Poll-on-tick with per-run identity: two long-running leaves run concurrently
/// under `parallel`, each carrying its own status. The tree is re-ticked while
/// either is `Running` (that re-tick *is* the poll-on-tick contract — see
/// docs/async-functions.md), and completing one leaves the other running: each
/// run advances on its own identity, not a shared slot. This is the state model a
/// spawned `say` action needs — here the two runs are distinct scripted leaves,
/// no module and no network. (`polly::say` keys its runs by content only because
/// the module ABI hands it no per-invocation id; a run spawned as a behavior gets
/// that identity from the node, per the reserved-parameter note in the doc.)
#[test]
fn concurrent_runs_advance_independently() {
    let a = Uuid::from_u128(0xA);
    let b = Uuid::from_u128(0xB);

    let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
        (a, Status::Running),
        (b, Status::Running),
    ])));
    let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
    let function_index = Rc::new(HashMap::from([
        (a, scripted_leaf_function(a)),
        (b, scripted_leaf_function(b)),
    ]));
    let tree = build(nodes::parallel(vec![scripted_leaf(a), scripted_leaf(b)]));
    let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());

    // Both runs pending → the tree keeps being re-ticked (Running).
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Running);
    let _ = runtime;

    // Complete run A only. Its status is its own, so B is untouched and the tree
    // is still Running — the two runs never shared a slot.
    statuses.borrow_mut().insert(a, Status::Success);
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Running);
    let _ = runtime;

    // Complete run B. Both terminal → the tree succeeds.
    statuses.borrow_mut().insert(b, Status::Success);
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Success);
}

// seq_star
//----------------------------------------------------------------
#[test]
fn seq_star_resumes_and_resets() {
    // Three scripted leaves; the middle one starts as Running. seq_star should
    // tick the first (Success), hit the second (Running) and stop there,
    // remembering index 1. On the next tick it must resume at the second leaf
    // WITHOUT re-ticking the first. After a terminal result the index resets.
    let first = Uuid::from_u128(0x1);
    let second = Uuid::from_u128(0x2);
    let third = Uuid::from_u128(0x3);

    let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
        (first, Status::Success),
        (second, Status::Running),
        (third, Status::Success),
    ])));
    let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));

    let function_index = Rc::new(HashMap::from([
        (first, scripted_leaf_function(first)),
        (second, scripted_leaf_function(second)),
        (third, scripted_leaf_function(third)),
    ]));

    let tree = build(nodes::seq_star(vec![
        scripted_leaf(first),
        scripted_leaf(second),
        scripted_leaf(third),
    ]));

    let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());

    // First tick: first succeeds, second is Running -> tree Running, index = 1.
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Running);
    let _ = runtime;
    assert_eq!(*ticks.borrow().get(&first).unwrap_or(&0), 1);
    assert_eq!(*ticks.borrow().get(&second).unwrap_or(&0), 1);
    assert_eq!(*ticks.borrow().get(&third).unwrap_or(&0), 0);

    // The second leaf now succeeds.
    statuses.borrow_mut().insert(second, Status::Success);

    // Second tick: resumes at the second leaf (no re-tick of the first), both
    // remaining leaves succeed -> whole seq_star succeeds, index resets to 0.
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Success);
    let _ = runtime;
    assert_eq!(
        *ticks.borrow().get(&first).unwrap_or(&0),
        1,
        "first not re-ticked"
    );
    assert_eq!(*ticks.borrow().get(&second).unwrap_or(&0), 2);
    assert_eq!(*ticks.borrow().get(&third).unwrap_or(&0), 1);

    // Third tick: after the reset, it restarts from the first leaf.
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Success);
    let _ = runtime;
    assert_eq!(
        *ticks.borrow().get(&first).unwrap_or(&0),
        2,
        "first re-ticked after reset"
    );
}

/// A fresh interpreter hosts the runner scaffold from the start: it accepts
/// edits before anything is loaded, and with nothing grafted the runner ticks
/// no children — the interpreter idles, always `Running`.
#[test]
fn a_fresh_interpreter_accepts_edits_and_idles_while_empty() {
    use crate::behavior::BehaviorTreeInterpreter;
    use arora_behavior::graph::GraphDiff;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter, BehaviorStatus};
    use arora_simple_data_store::SimpleDataStore;

    let mut interpreter = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

    // The scaffold is there before anything is loaded: one runner node.
    assert!(interpreter.graph().root.is_some(), "the runner is the root");
    assert_eq!(interpreter.graph().nodes.len(), 1, "just the runner");

    // The empty (no-op) edit is valid.
    interpreter
        .apply(GraphDiff::default())
        .expect("a fresh interpreter accepts a diff");

    // The re-lowering tick sees the bare runner: idle, stay installed.
    let store = SimpleDataStore::new();
    let (statuses, ticks) = (LeafStatuses::default(), LeafTicks::default());
    let mut bridge = TestBridge::new(statuses, ticks);
    let mut ctx = BehaviorContext {
        store: &store,
        call_bridge: &mut bridge,
    };
    let status = interpreter.tick(&mut ctx).expect("the bare scaffold idles");
    assert_eq!(status, BehaviorStatus::Running);
}

/// Task runs: `spawn`/`halt` on the interpreter, and how a run advances
/// alongside the main tree. Each run invokes a scripted leaf (through
/// [`TestBridge`]) whose returned status the test drives between ticks — a
/// stand-in for a real action-behavior whose status decorator publishes its
/// outcome to the run's status key.
mod task_runs {
    use super::{LeafStatuses, LeafTicks, TestBridge};
    use crate::arora_generated::behavior_tree::status::Status;
    use crate::behavior::{graph_type, BehaviorTreeInterpreter};
    use crate::nodes;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter, BehaviorStatus, RunPolicy, TaskId};
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::call::Call;
    use arora_types::data::DataStore;
    use arora_types::value::Value;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;
    use uuid::Uuid;

    /// A [`TestBridge`] whose one scripted leaf `leaf` returns `status`, plus the
    /// shared cells to drive it (`statuses`) and observe invocations (`ticks`).
    fn scripted(leaf: Uuid, status: Status) -> (TestBridge, LeafStatuses, LeafTicks) {
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([(leaf, status)])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        (
            TestBridge::new(statuses.clone(), ticks.clone()),
            statuses,
            ticks,
        )
    }

    /// A [`Call`] a run invokes: `module`/`leaf` identify the scripted leaf.
    fn call_to(module: u128, leaf: Uuid) -> Call {
        Call {
            module_id: Some(Uuid::from_u128(module)),
            id: leaf,
            args: Vec::new(),
        }
    }

    #[test]
    fn a_spawned_run_advances_and_writes_its_status_key() {
        let leaf = Uuid::from_u128(0xA1);
        let (mut bridge, statuses, ticks) = scripted(leaf, Status::Running);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        // The default-reject is overridden: a handle comes back, its keys
        // namespaced under the run id.
        let handle = interp
            .spawn(call_to(0xB0, leaf), RunPolicy::Concurrent)
            .expect("the tree interpreter hosts runs");
        assert!(
            handle.status.path.starts_with("arora/tasks/"),
            "{}",
            handle.status.path
        );
        assert!(
            handle.status.path.ends_with("/status"),
            "{}",
            handle.status.path
        );

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        // Spawn does not tick: nothing is written until the next tick.
        assert_eq!(store.read(std::slice::from_ref(&handle.status)), vec![None]);

        // First tick invokes the run once and publishes Running.
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(running)],
            "the run's status key holds Running"
        );
        assert_eq!(*ticks.borrow().get(&leaf).unwrap(), 1);

        // The run reaches Success: the interpreter publishes it, drops the run,
        // and — no runs, no tree — idles rather than being dropped.
        statuses.borrow_mut().insert(leaf, Status::Success);
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let success: Value = Status::Success.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(success)]
        );

        // A finished run is not ticked again.
        let before = *ticks.borrow().get(&leaf).unwrap();
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            *ticks.borrow().get(&leaf).unwrap(),
            before,
            "a finished run is not re-ticked"
        );
    }

    #[test]
    fn halting_a_run_terminates_it_next_tick() {
        let leaf = Uuid::from_u128(0xC2);
        let (mut bridge, _statuses, ticks) = scripted(leaf, Status::Running);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let handle = interp
            .spawn(call_to(0xB0, leaf), RunPolicy::Concurrent)
            .unwrap();
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };

        // Runs indefinitely: after a tick it is still Running.
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(running)]
        );

        // Halt: the next tick ends the run (Failure) without invoking it again.
        interp.halt(handle.id).unwrap();
        let ticks_before = *ticks.borrow().get(&leaf).unwrap();
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let failure: Value = Status::Failure.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(failure)],
            "a halted run ends Failure"
        );
        assert_eq!(
            *ticks.borrow().get(&leaf).unwrap(),
            ticks_before,
            "a halted run is not invoked"
        );

        // Idempotent: halting the finished run, or an unknown run, is a clean
        // no-op.
        interp
            .halt(handle.id)
            .expect("halting a finished run is a no-op");
        interp
            .halt(TaskId(Uuid::from_u128(0xDEAD)))
            .expect("halting an unknown run is a no-op");
    }

    /// A loaded behavior and a spawned run coexist under the runner and both
    /// advance each tick — the main behavior reactively re-evaluated, the run
    /// invoked once per tick — and the interpreter is a standing policy: it
    /// reports `Running` every tick, never `Done`.
    #[test]
    fn a_loaded_behavior_and_a_run_tick_together() {
        use arora_behavior::graph::{Graph, Node as GraphNode};

        let main_leaf = Uuid::from_u128(0xE3);
        let run_leaf = Uuid::from_u128(0xE4);
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
            (main_leaf, Status::Success),
            (run_leaf, Status::Running),
        ])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        // The main behavior: a single run-call leaf graph invoking the
        // scripted main_leaf (dispatched through arora_call, like a module
        // action node would be).
        let main_node = Uuid::from_u128(0x111);
        let mut main = Graph::empty();
        main.root = Some(main_node);
        main.nodes.insert(
            main_node,
            GraphNode {
                id: main_node,
                function: crate::nodes::RUN_CALL_FUNCTION_ID,
                inputs: vec![arora_behavior::graph::Io::new(
                    crate::nodes::RUN_CALL_PARAM_ID,
                )],
                ..GraphNode::default()
            },
        );
        main.links.push(arora_behavior::graph::Link::new(
            arora_behavior::graph::Port::new(main_node, crate::nodes::RUN_CALL_PARAM_ID),
            arora_behavior::graph::LinkSource::Literal(
                arora_types::value_serde::to_value(&call_to(0xB0, main_leaf)).unwrap(),
            ),
        ));
        interp.load(main).expect("the behavior loads");
        interp
            .spawn(call_to(0xB0, run_leaf), RunPolicy::Concurrent)
            .unwrap();

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        for round in 1..=3u32 {
            assert_eq!(
                interp.tick(&mut ctx).unwrap(),
                BehaviorStatus::Running,
                "the interpreter is a standing policy (never Done)"
            );
            assert_eq!(
                *ticks.borrow().get(&main_leaf).unwrap(),
                round,
                "the main behavior re-evaluates every tick"
            );
            assert_eq!(
                *ticks.borrow().get(&run_leaf).unwrap(),
                round,
                "the run advances every tick"
            );
        }
    }

    /// The scaffold is introspectable the behavior tree's way: a spawned run is
    /// two graph nodes under the runner (a run-status decorator, its status key
    /// predetermined, over a run-call leaf carrying the call as literal data) —
    /// and a halted run's fragment is pruned again.
    #[test]
    fn a_spawned_run_is_visible_in_the_graph_until_halted() {
        let leaf = Uuid::from_u128(0xE5);
        let (mut bridge, _statuses, _ticks) = scripted(leaf, Status::Running);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let handle = interp
            .spawn(call_to(0xB0, leaf), RunPolicy::Concurrent)
            .unwrap();
        let graph = interp.graph();
        let decorator = graph
            .nodes
            .values()
            .find(|n| n.function == crate::nodes::RUN_STATUS_FUNCTION_ID)
            .expect("the run's status decorator is in the graph");
        assert_eq!(
            decorator.outputs[0].predetermined_key.as_deref(),
            Some(handle.status.path.as_str()),
            "the decorator's status output is predetermined to the run's key"
        );
        let call_node = decorator.children.as_ref().unwrap()[0];
        assert_eq!(
            graph.nodes[&call_node].function,
            crate::nodes::RUN_CALL_FUNCTION_ID,
            "the decorator wraps the run-call leaf"
        );
        let root = graph.root.expect("the runner roots the scaffold");
        assert!(
            graph.nodes[&root]
                .children
                .as_ref()
                .unwrap()
                .contains(&decorator.id),
            "the fragment hangs off the runner"
        );

        // Halt: the next tick prunes the fragment from the graph.
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        interp.halt(handle.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            interp.graph().nodes.len(),
            1,
            "only the runner remains after the halt pruned the fragment"
        );
    }

    #[test]
    fn concurrent_runs_get_independent_status_keys() {
        let a = Uuid::from_u128(0xAA);
        let b = Uuid::from_u128(0xBB);
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
            (a, Status::Running),
            (b, Status::Running),
        ])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let ha = interp
            .spawn(call_to(0xB0, a), RunPolicy::Concurrent)
            .unwrap();
        let hb = interp
            .spawn(call_to(0xB0, b), RunPolicy::Concurrent)
            .unwrap();
        assert_ne!(
            ha.status.path, hb.status.path,
            "each run gets its own status key"
        );

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(std::slice::from_ref(&ha.status)),
            vec![Some(running.clone())]
        );
        assert_eq!(
            store.read(std::slice::from_ref(&hb.status)),
            vec![Some(running.clone())]
        );

        // Halt A only; B keeps running independently.
        interp.halt(ha.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        let failure: Value = Status::Failure.into();
        assert_eq!(
            store.read(std::slice::from_ref(&ha.status)),
            vec![Some(failure)],
            "the halted run ended"
        );
        assert_eq!(
            store.read(std::slice::from_ref(&hb.status)),
            vec![Some(running)],
            "the other run is unaffected"
        );
    }

    /// A graph that ticks every step and never ends: a parallel of a run-call
    /// leaf invoking `leaf` and a `Run`. Its nodes are `ids` (parallel, call
    /// node, run node).
    fn stepping_graph(ids: [u128; 3], leaf: Uuid) -> arora_behavior::graph::Graph {
        use arora_behavior::graph::{Graph, Io, Link, LinkSource, Node as GraphNode, Port};
        let [parallel, call_node, run] = ids.map(Uuid::from_u128);
        let mut graph = Graph::empty();
        graph.root = Some(parallel);
        graph.nodes.insert(
            parallel,
            GraphNode {
                id: parallel,
                function: nodes::PARALLEL_FUNCTION_ID,
                children: Some(vec![call_node, run]),
                ..GraphNode::default()
            },
        );
        graph.nodes.insert(
            call_node,
            GraphNode {
                id: call_node,
                function: nodes::RUN_CALL_FUNCTION_ID,
                inputs: vec![Io::new(nodes::RUN_CALL_PARAM_ID)],
                ..GraphNode::default()
            },
        );
        graph.nodes.insert(
            run,
            GraphNode {
                id: run,
                function: nodes::RUN_FUNCTION_ID,
                ..GraphNode::default()
            },
        );
        graph.links.push(Link::new(
            Port::new(call_node, nodes::RUN_CALL_PARAM_ID),
            LinkSource::Literal(arora_types::value_serde::to_value(&call_to(0xB0, leaf)).unwrap()),
        ));
        graph
    }

    /// A core string node is native: a graph calling one spawns on a device
    /// with no module, and the run ticks it.
    #[test]
    fn a_spawned_graph_may_call_a_core_string_node() {
        use arora_behavior::graph::{Graph, Io, Link, LinkSource, Node as GraphNode, Port};
        let node = Uuid::from_u128(0x30);
        let mut graph = Graph::empty();
        graph.root = Some(node);
        graph.nodes.insert(
            node,
            GraphNode {
                id: node,
                function: nodes::IS_STR_SET_FUNCTION_ID,
                inputs: vec![Io::new(nodes::IS_STR_SET_VALUE_PARAM_ID)],
                ..GraphNode::default()
            },
        );
        graph.links.push(Link::new(
            Port::new(node, nodes::IS_STR_SET_VALUE_PARAM_ID),
            LinkSource::Literal(Value::String("set".to_string())),
        ));
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let handle = interp
            .spawn_graph(&graph_type(), graph, RunPolicy::Concurrent)
            .expect("a core node needs no module");

        let store = SimpleDataStore::new();
        let mut bridge = TestBridge::new(LeafStatuses::default(), LeafTicks::default());
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        let success: Value = Status::Success.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(success)],
            "the run ticked the core node"
        );
    }

    /// A spawned graph is a run: its tree ticks on every step beside the main
    /// behavior, its status key reads Running, and a halt ends it Failure and
    /// prunes every one of its nodes.
    #[test]
    fn a_spawned_behavior_ticks_every_step_until_halted() {
        let leaf = Uuid::from_u128(0xF1);
        let (mut bridge, _statuses, ticks) = scripted(leaf, Status::Success);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let handle = interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x10, 0x11, 0x12], leaf),
                RunPolicy::Concurrent,
            )
            .expect("the tree interpreter hosts a graph as a run");
        assert_eq!(
            handle.status.path,
            format!(
                "arora/tasks/{}/{}/{}/status",
                arora_behavior::interpreter_module::ID,
                arora_behavior::interpreter_module::SPAWN_GRAPH,
                handle.id.0
            ),
            "the run's keys are under the interpreter module's spawn_graph"
        );

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        let running: Value = Status::Running.into();
        for round in 1..=3u32 {
            assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
            assert_eq!(
                *ticks.borrow().get(&leaf).unwrap(),
                round,
                "the run's leaf ticks once per step"
            );
            assert_eq!(
                store.read(std::slice::from_ref(&handle.status)),
                vec![Some(running.clone())]
            );
        }

        interp.halt(handle.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        let failure: Value = Status::Failure.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(failure)],
            "a halted run ends Failure"
        );
        assert_eq!(
            *ticks.borrow().get(&leaf).unwrap(),
            3,
            "a halted run is not ticked"
        );
        assert_eq!(
            interp.graph().nodes.len(),
            1,
            "only the runner remains after the halt pruned the run's nodes"
        );
    }

    /// An edit reaches a spawned graph's nodes: it relinks a literal and adds a
    /// node under the run, which then belongs to it. Loading a main behavior
    /// leaves the run in place, and halting prunes the node the edit added.
    #[test]
    fn an_edit_reaches_a_spawned_behavior_and_a_load_keeps_it() {
        use arora_behavior::graph::{Graph, GraphDiff, Link, LinkSource, Node as GraphNode, Port};

        let a = Uuid::from_u128(0xA1);
        let b = Uuid::from_u128(0xB1);
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
            (a, Status::Success),
            (b, Status::Success),
        ])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        let mut bridge = TestBridge::new(statuses, ticks.clone());
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let [parallel, call_node, run] = [0x20, 0x21, 0x22].map(Uuid::from_u128);
        let handle = interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x20, 0x21, 0x22], a),
                RunPolicy::Concurrent,
            )
            .unwrap();
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        assert_eq!(ticks.borrow().get(&a), Some(&1));

        // Relink the run-call leaf's literal: the run now calls `b`.
        interp
            .apply(GraphDiff {
                add_links: vec![Link::new(
                    Port::new(call_node, nodes::RUN_CALL_PARAM_ID),
                    LinkSource::Literal(
                        arora_types::value_serde::to_value(&call_to(0xB0, b)).unwrap(),
                    ),
                )],
                ..GraphDiff::default()
            })
            .expect("the edit applies");
        interp.tick(&mut ctx).unwrap();
        assert_eq!(ticks.borrow().get(&a), Some(&1), "the old call is gone");
        assert_eq!(ticks.borrow().get(&b), Some(&1), "the relinked call runs");

        // Add a node under the run: a second `Run` child of its parallel.
        let added = Uuid::from_u128(0x23);
        interp
            .apply(GraphDiff {
                add_nodes: vec![
                    GraphNode {
                        id: parallel,
                        function: nodes::PARALLEL_FUNCTION_ID,
                        children: Some(vec![call_node, run, added]),
                        ..GraphNode::default()
                    },
                    GraphNode {
                        id: added,
                        function: nodes::RUN_FUNCTION_ID,
                        ..GraphNode::default()
                    },
                ],
                ..GraphDiff::default()
            })
            .expect("the edit applies");

        // Load a main behavior: the run stays and keeps ticking.
        let main_node = Uuid::from_u128(0x30);
        let mut main = Graph::empty();
        main.root = Some(main_node);
        main.nodes.insert(
            main_node,
            GraphNode {
                id: main_node,
                function: nodes::SUCCEED_FUNCTION_ID,
                ..GraphNode::default()
            },
        );
        interp.load(main).expect("the main behavior loads");
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            ticks.borrow().get(&b),
            Some(&2),
            "the run survived the load"
        );
        for id in [parallel, call_node, run, added, main_node] {
            assert!(
                interp.graph().nodes.contains_key(&id),
                "{id} is in the graph"
            );
        }

        // A second load replaces the main behavior only.
        interp
            .load(Graph::empty())
            .expect("an empty main behavior loads");
        assert!(!interp.graph().nodes.contains_key(&main_node));
        assert!(
            interp.graph().nodes.contains_key(&added),
            "the run's nodes stay"
        );

        // Halt: every node of the run leaves, the one the edit added included.
        interp.halt(handle.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            interp.graph().nodes.len(),
            1,
            "only the runner remains: {:?}",
            interp.graph().nodes.keys().collect::<Vec<_>>()
        );
    }

    /// Runs hang from the runner after the main behavior, in spawn order, and an
    /// edit cannot change a run's decorator or remove a run's root: halting is
    /// how a run leaves.
    #[test]
    fn runs_tick_in_spawn_order_and_keep_their_decorators() {
        use arora_behavior::graph::{GraphDiff, Link, LinkSource, Node as GraphNode, Port};

        let leaf = Uuid::from_u128(0xC1);
        let (mut bridge, _statuses, _ticks) = scripted(leaf, Status::Success);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let mut decorators = Vec::new();
        for (n, ids) in [[0x40, 0x41, 0x42], [0x50, 0x51, 0x52], [0x60, 0x61, 0x62]]
            .into_iter()
            .enumerate()
        {
            let handle = interp
                .spawn_graph(
                    &graph_type(),
                    stepping_graph(ids, leaf),
                    RunPolicy::Concurrent,
                )
                .unwrap();
            let decorator = interp
                .graph()
                .nodes
                .values()
                .find(|node| {
                    node.outputs
                        .first()
                        .and_then(|io| io.predetermined_key.as_deref())
                        == Some(handle.status.path.as_str())
                })
                .expect("the run's decorator")
                .id;
            decorators.push(decorator);
            let root = interp.graph().root.unwrap();
            assert_eq!(
                interp.graph().nodes[&root].children.as_deref(),
                Some(decorators.as_slice()),
                "after {} spawns the runner holds the runs in spawn order",
                n + 1
            );
        }

        let refused = [
            GraphDiff {
                remove_nodes: vec![decorators[1]],
                ..GraphDiff::default()
            },
            GraphDiff {
                add_nodes: vec![GraphNode {
                    id: decorators[1],
                    function: nodes::SUCCEED_FUNCTION_ID,
                    ..GraphNode::default()
                }],
                ..GraphDiff::default()
            },
            GraphDiff {
                add_links: vec![Link::new(
                    Port::new(decorators[1], nodes::RUN_STATUS_LATCH_PARAM_ID),
                    LinkSource::Literal(Status::Success.into()),
                )],
                ..GraphDiff::default()
            },
            GraphDiff {
                remove_nodes: vec![Uuid::from_u128(0x50)],
                ..GraphDiff::default()
            },
        ];
        for diff in refused {
            assert!(interp.apply(diff.clone()).is_err(), "{diff:?} is refused");
        }
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).expect("the scaffold still lowers");
        assert!(interp.graph().nodes.contains_key(&decorators[1]));
    }

    /// A run is the subtree under its decorator, whatever order the edits came
    /// in: a node added loose and then placed under a run belongs to the run, so
    /// a load keeps it and a halt prunes it.
    #[test]
    fn a_node_placed_under_a_run_by_a_later_edit_belongs_to_it() {
        use arora_behavior::graph::{Graph, GraphDiff, Node as GraphNode};

        let leaf = Uuid::from_u128(0xC2);
        let (mut bridge, _statuses, _ticks) = scripted(leaf, Status::Success);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let [parallel, call_node, run] = [0x90, 0x91, 0x92].map(Uuid::from_u128);
        let handle = interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x90, 0x91, 0x92], leaf),
                RunPolicy::Concurrent,
            )
            .unwrap();

        let loose = Uuid::from_u128(0x93);
        interp
            .apply(GraphDiff {
                add_nodes: vec![GraphNode {
                    id: loose,
                    function: nodes::RUN_FUNCTION_ID,
                    ..GraphNode::default()
                }],
                ..GraphDiff::default()
            })
            .unwrap();
        interp
            .apply(GraphDiff {
                add_nodes: vec![GraphNode {
                    id: parallel,
                    function: nodes::PARALLEL_FUNCTION_ID,
                    children: Some(vec![call_node, run, loose]),
                    ..GraphNode::default()
                }],
                ..GraphDiff::default()
            })
            .unwrap();
        interp.load(Graph::empty()).unwrap();
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp
            .tick(&mut ctx)
            .expect("the run still lowers after the load");
        assert!(
            interp.graph().nodes.contains_key(&loose),
            "the load kept it"
        );

        interp.halt(handle.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            interp.graph().nodes.len(),
            1,
            "the halt pruned it with the run"
        );
    }

    /// A graph that reads `variable`, declared under `name`: a sequence whose
    /// one child takes the variable as an argument.
    fn reading(root: u128, variable: Uuid, name: &str) -> arora_behavior::graph::Graph {
        use arora_behavior::graph::{Graph, Link, LinkSource, Node as GraphNode, Port};
        let root = Uuid::from_u128(root);
        let mut graph = Graph::empty();
        graph.root = Some(root);
        graph.nodes.insert(
            root,
            GraphNode {
                id: root,
                function: nodes::SUCCEED_FUNCTION_ID,
                ..GraphNode::default()
            },
        );
        graph.links.push(Link::new(
            Port::new(root, Uuid::from_u128(0x1)),
            LinkSource::Variable(variable),
        ));
        graph.variables.insert(variable, name.to_string());
        graph
    }

    /// A spawned graph is a region of its own: a graph type the interpreter
    /// reads, one tree of new nodes under its root, links among its own nodes,
    /// and no renaming of a variable the device's behavior reads. A load cannot
    /// take over a run's nodes either.
    #[test]
    fn a_spawned_graph_that_overlaps_the_device_s_is_refused() {
        use arora_behavior::graph::{Graph, GraphType, Link, LinkSource, Node as GraphNode, Port};

        let leaf = Uuid::from_u128(0xD1);
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x70, 0x71, 0x72], leaf),
                RunPolicy::Concurrent,
            )
            .unwrap();
        let variable = Uuid::from_u128(0x5);
        interp.load(reading(0xA0, variable, "face/x")).unwrap();
        let nodes_before = interp.graph().nodes.len();

        let fresh = || stepping_graph([0x80, 0x81, 0x82], leaf);
        let [parallel, call_node, run] = [0x80, 0x81, 0x82].map(Uuid::from_u128);
        let mut rootless = fresh();
        rootless.root = None;
        let mut stray_root = fresh();
        stray_root.root = Some(Uuid::from_u128(0x99));
        let reused = stepping_graph([0x80, 0x71, 0x82], leaf);
        let mut reaching_out = fresh();
        reaching_out.links.push(Link::new(
            Port::new(Uuid::from_u128(0x71), nodes::RUN_CALL_PARAM_ID),
            LinkSource::Literal(Value::Unit),
        ));
        let mut renaming = fresh();
        renaming.variables.insert(variable, "face/y".to_string());
        let mut dangling_child = fresh();
        dangling_child.nodes.get_mut(&parallel).unwrap().children =
            Some(vec![call_node, run, Uuid::from_u128(0x99)]);
        let mut cycle = fresh();
        cycle.nodes.get_mut(&run).unwrap().children = Some(vec![run]);
        let mut two_parents = fresh();
        two_parents.nodes.get_mut(&run).unwrap().children = Some(vec![call_node]);
        let mut stray_node = fresh();
        stray_node.nodes.insert(
            Uuid::from_u128(0x83),
            GraphNode {
                id: Uuid::from_u128(0x83),
                function: nodes::RUN_FUNCTION_ID,
                ..GraphNode::default()
            },
        );
        let mut child_outside = fresh();
        child_outside.nodes.get_mut(&run).unwrap().children = Some(vec![Uuid::from_u128(0xA0)]);

        let tree = graph_type();
        let ty = |name: &str, major, minor| GraphType {
            name: name.to_string(),
            version: semver::Version::new(major, minor, 0),
        };
        for (what, graph_type, graph) in [
            ("no root", tree.clone(), rootless),
            ("a root that is not a node", tree.clone(), stray_root),
            ("a node id the device uses", tree.clone(), reused),
            ("a link onto another node", tree.clone(), reaching_out),
            ("a variable in use renamed", tree.clone(), renaming),
            ("a child that is not a node", tree.clone(), dangling_child),
            ("a cycle", tree.clone(), cycle),
            ("a node with two parents", tree.clone(), two_parents),
            ("a node outside the tree", tree.clone(), stray_node),
            ("a child of the main behavior", tree.clone(), child_outside),
            ("another language", ty("node-graph", 1, 0), fresh()),
            ("another major", ty("behavior-tree", 2, 0), fresh()),
            ("a newer minor", ty("behavior-tree", 1, 99), fresh()),
        ] {
            let refused = interp.spawn_graph(&graph_type, graph, RunPolicy::Concurrent);
            assert!(refused.is_err(), "a graph with {what} is refused");
        }
        assert_eq!(
            interp.graph().nodes.len(),
            nodes_before,
            "a refused spawn leaves the graph as it was"
        );

        let mut over_a_run = Graph::empty();
        let run_node = Uuid::from_u128(0x72);
        over_a_run.root = Some(run_node);
        over_a_run.nodes.insert(
            run_node,
            GraphNode {
                id: run_node,
                function: nodes::SUCCEED_FUNCTION_ID,
                ..GraphNode::default()
            },
        );
        assert!(
            interp.load(over_a_run).is_err(),
            "a load cannot replace a run's node"
        );
    }

    /// A run's variables leave with it: once halted, a graph may declare the
    /// same variable under another name. While it runs, a load cannot rename a
    /// variable the run reads.
    #[test]
    fn a_run_s_variables_leave_with_it() {
        let leaf = Uuid::from_u128(0xE1);
        let (mut bridge, _statuses, _ticks) = scripted(leaf, Status::Success);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let variable = Uuid::from_u128(0x6);
        let handle = interp
            .spawn_graph(
                &graph_type(),
                reading(0xB0, variable, "a"),
                RunPolicy::Concurrent,
            )
            .unwrap();
        assert!(
            interp.load(reading(0xB1, variable, "b")).is_err(),
            "a load cannot rename a variable a run reads"
        );

        interp.halt(handle.id).unwrap();
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        assert!(!interp.graph().variables.contains_key(&variable));
        interp
            .spawn_graph(
                &graph_type(),
                reading(0xB2, variable, "b"),
                RunPolicy::Concurrent,
            )
            .expect("the halted run's declaration is gone");
    }

    /// A run whose program errors ends `Failure`: the error is reported once,
    /// and the other runs tick on.
    #[test]
    fn a_run_that_errors_ends_failure_and_the_others_tick_on() {
        let good = Uuid::from_u128(0xF5);
        let missing = Uuid::from_u128(0xF6);
        let (mut bridge, _statuses, ticks) = scripted(good, Status::Success);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let failing = interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x10, 0x11, 0x12], missing),
                RunPolicy::Concurrent,
            )
            .unwrap();
        interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x20, 0x21, 0x22], good),
                RunPolicy::Concurrent,
            )
            .unwrap();
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        assert!(interp.tick(&mut ctx).is_err(), "the error is reported");
        let failure: Value = Status::Failure.into();
        assert_eq!(
            store.read(std::slice::from_ref(&failing.status)),
            vec![Some(failure)]
        );
        for _ in 0..2 {
            interp
                .tick(&mut ctx)
                .expect("the failed run no longer errors");
        }
        assert_eq!(
            ticks.borrow().get(&good),
            Some(&2),
            "the other run ticks on"
        );
    }

    /// A finished or halted run's node ids are free again at once, so a client
    /// replaces a program by halting it and spawning the new one before the
    /// next step.
    #[test]
    fn a_halted_or_finished_run_s_ids_can_be_spawned_again() {
        let leaf = Uuid::from_u128(0xF7);
        let (mut bridge, _statuses, _ticks) = scripted(leaf, Status::Success);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        let ids = [0x30, 0x31, 0x32];
        let first = interp
            .spawn_graph(
                &graph_type(),
                stepping_graph(ids, leaf),
                RunPolicy::Concurrent,
            )
            .unwrap();
        interp.halt(first.id).unwrap();
        let second = interp
            .spawn_graph(
                &graph_type(),
                stepping_graph(ids, leaf),
                RunPolicy::Concurrent,
            )
            .expect("the halted run's ids are free");
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        let failure: Value = Status::Failure.into();
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(&[first.status.clone(), second.status.clone()]),
            vec![Some(failure), Some(running)]
        );

        // A run that ends by itself: a sequence of one succeeding leaf.
        use arora_behavior::graph::{Graph, Node as GraphNode};
        let one = Uuid::from_u128(0x40);
        let mut once = Graph::empty();
        once.root = Some(one);
        once.nodes.insert(
            one,
            GraphNode {
                id: one,
                function: nodes::SUCCEED_FUNCTION_ID,
                ..GraphNode::default()
            },
        );
        interp
            .spawn_graph(&graph_type(), once.clone(), RunPolicy::Concurrent)
            .unwrap();
        interp.tick(&mut ctx).unwrap();
        interp
            .spawn_graph(&graph_type(), once, RunPolicy::Concurrent)
            .expect("the finished run's ids are free");
    }

    /// An edit cannot place the runner or a decorator elsewhere, call a node
    /// that is not there, or close a cycle; a refused edit changes nothing.
    #[test]
    fn an_edit_that_would_break_the_tree_is_refused() {
        use arora_behavior::graph::{GraphDiff, Node as GraphNode};

        let leaf = Uuid::from_u128(0xF8);
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        interp
            .spawn_graph(
                &graph_type(),
                stepping_graph([0x50, 0x51, 0x52], leaf),
                RunPolicy::Concurrent,
            )
            .unwrap();
        let runner = interp.graph().root.unwrap();
        let decorator = interp.graph().nodes[&runner].children.as_ref().unwrap()[0];
        let [parallel, _, run] = [0x50, 0x51, 0x52].map(Uuid::from_u128);
        let before = interp.graph().clone();
        let node = |id, children| GraphNode {
            id,
            function: nodes::SEQ_FUNCTION_ID,
            children: Some(children),
            ..GraphNode::default()
        };
        for (what, diff) in [
            (
                "the main root set to a decorator",
                GraphDiff {
                    set_root: Some(decorator),
                    ..GraphDiff::default()
                },
            ),
            (
                "a decorator as a child",
                GraphDiff {
                    add_nodes: vec![node(Uuid::from_u128(0x60), vec![decorator])],
                    ..GraphDiff::default()
                },
            ),
            (
                "the runner as a child",
                GraphDiff {
                    add_nodes: vec![node(Uuid::from_u128(0x60), vec![runner])],
                    ..GraphDiff::default()
                },
            ),
            (
                "a run's node removed under its parent",
                GraphDiff {
                    remove_nodes: vec![run],
                    ..GraphDiff::default()
                },
            ),
            (
                "a cycle",
                GraphDiff {
                    add_nodes: vec![node(run, vec![parallel])],
                    ..GraphDiff::default()
                },
            ),
        ] {
            assert!(interp.apply(diff).is_err(), "{what} is refused");
            assert_eq!(interp.graph(), &before, "{what} changed nothing");
        }
    }
}

/// The core string nodes run natively in a Groot tree over a data store, with
/// no module loaded: their ports bind to store keys that need not exist yet.
mod core_string_nodes {
    use super::{LeafStatuses, LeafTicks, TestBridge};
    use crate::arora_generated::behavior_tree::status::Status;
    use crate::behavior::BehaviorTreeInterpreter;
    use crate::nodes;
    use crate::schema::Expression;
    use crate::variable::VariableCell;
    use crate::BehaviorTreeRuntime;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter};
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::data::{DataStore, Key, StateChange};
    use arora_types::value::Value;
    use std::collections::HashMap;
    use std::rc::Rc;

    fn groot(body: &str) -> String {
        format!(
            r#"<root main_tree_to_execute="MainTree"><BehaviorTree ID="MainTree">{body}</BehaviorTree></root>"#
        )
    }

    /// An interpreter with no module (an empty function index) running `body`.
    fn interpreter(body: &str) -> BehaviorTreeInterpreter {
        let mut interpreter = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        interpreter
            .load_groot(&groot(body))
            .expect("the core nodes need no module");
        interpreter
    }

    /// A loaded tree and the bridge its node ticks are registered on.
    struct Device {
        tree: BehaviorTreeInterpreter,
        bridge: TestBridge,
    }

    fn device(body: &str) -> Device {
        Device {
            tree: interpreter(body),
            bridge: TestBridge::new(LeafStatuses::default(), LeafTicks::default()),
        }
    }

    fn tick(device: &mut Device, store: &SimpleDataStore) {
        let mut ctx = BehaviorContext {
            store,
            call_bridge: &mut device.bridge,
        };
        device.tree.tick(&mut ctx).expect("the tree ticks");
    }

    fn read(store: &SimpleDataStore, key: &str) -> Option<Value> {
        store.read(&[Key::from(key)]).remove(0)
    }

    fn string(value: &str) -> Option<Value> {
        Some(Value::String(value.to_string()))
    }

    fn unset(key: &str) -> StateChange {
        StateChange {
            set: HashMap::new(),
            unset: std::collections::HashSet::from([Key::from(key)]),
        }
    }

    /// `IsStringSet → SetString → UnsetString` on a key written from outside
    /// the tree runs its branch once per write: the key is absent at first
    /// (the condition fails, nothing errors), each write runs the branch once,
    /// and the branch consuming the key keeps it from running again.
    #[test]
    fn a_branch_runs_once_per_write_of_a_key() {
        let store = SimpleDataStore::new();
        let mut tree = device(
            r#"<Sequence>
                 <IsStringSet value="{message}"/>
                 <SetString variable="{heard}" value="{message}"/>
                 <UnsetString variable="{message}"/>
               </Sequence>"#,
        );

        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), None, "no message yet: no branch");

        store
            .write(StateChange::set("message", Value::String("hi".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), string("hi"), "the branch ran");
        assert_eq!(read(&store, "message"), None, "and consumed the message");

        // Clear the trace: a tick without a new write does not run the branch.
        store.write(unset("heard")).unwrap();
        tick(&mut tree, &store);
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), None, "no write, no run");

        store
            .write(StateChange::set("message", Value::String("again".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), string("again"));
        assert_eq!(read(&store, "message"), None);

        // An empty string is not set.
        store.write(unset("heard")).unwrap();
        store
            .write(StateChange::set("message", Value::String(String::new())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), None, "an empty string is not set");
    }

    /// `SetString` creates a key that does not exist yet, from a literal.
    #[test]
    fn set_string_creates_a_missing_key() {
        let store = SimpleDataStore::new();
        let mut tree = device(r#"<SetString variable="{greeting}" value="hello"/>"#);
        assert_eq!(read(&store, "greeting"), None);
        tick(&mut tree, &store);
        assert_eq!(read(&store, "greeting"), string("hello"));
    }

    /// `WaitStringSet` holds its sequence `Running` while its key is absent,
    /// then lets it through once the key is written.
    #[test]
    fn wait_string_set_waits_for_its_key() {
        let store = SimpleDataStore::new();
        let mut tree = device(
            r#"<Sequence>
                 <WaitStringSet value="{reply}"/>
                 <SetString variable="{done}" value="yes"/>
               </Sequence>"#,
        );
        tick(&mut tree, &store);
        tick(&mut tree, &store);
        assert_eq!(read(&store, "done"), None, "waiting for the reply");
        store
            .write(StateChange::set("reply", Value::String("ok".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "done"), string("yes"));
    }

    /// `WaitStringSet`'s own status: `Running` on an absent value, `Success`
    /// once set.
    #[test]
    fn wait_string_set_is_running_then_success() {
        let reply = VariableCell::local();
        let tree = crate::tests::build(nodes::wait_str_set(Expression::Variable(reply.clone())));
        let mut bridge = TestBridge::empty();
        let mut runtime =
            BehaviorTreeRuntime::setup(&tree, Rc::new(HashMap::new()), &mut bridge, false)
                .expect("runtime sets up");
        assert_eq!(runtime.tick().unwrap(), Status::Running);
        assert_eq!(runtime.tick().unwrap(), Status::Running);
        reply.set(Value::String("ok".into()));
        assert_eq!(runtime.tick().unwrap(), Status::Success);
    }

    /// `RegexMatch` writes the matched text to its output key, creating it,
    /// and fails — leaving the output alone — when nothing matches or the
    /// input is absent.
    #[test]
    fn regex_match_writes_the_match() {
        let store = SimpleDataStore::new();
        let mut tree = device(
            r#"<RegexMatch value="{input}" matcher="(Ross|Brad|Victor)" first_match="{name}"/>"#,
        );
        tick(&mut tree, &store);
        assert_eq!(read(&store, "name"), None, "no input: no match");
        store
            .write(StateChange::set(
                "input",
                Value::String("I am Victor".into()),
            ))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "name"), string("Victor"));
        store
            .write(StateChange::set("input", Value::String("nobody".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "name"), string("Victor"), "a miss leaves it");
    }

    /// A port bound to a value that is not a string fails the tick, as the
    /// module's argument decoding did, rather than reading as unset.
    #[test]
    fn a_non_string_value_fails_the_tick() {
        let value = VariableCell::local_with(Value::F32(1.0));
        let tree = crate::tests::build(nodes::is_str_set(Expression::Variable(value)));
        let mut bridge = TestBridge::empty();
        let mut runtime =
            BehaviorTreeRuntime::setup(&tree, Rc::new(HashMap::new()), &mut bridge, false)
                .expect("runtime sets up");
        assert!(runtime.tick().is_err());
    }
}

/// Module functions with optional parameters, bound to store keys that may be
/// absent: an absent key passes `None`, an optional out-parameter writes
/// `Some` as the key's value and `None` as unsetting it.
mod optional_parameters {
    use crate::behavior::BehaviorTreeInterpreter;
    use crate::ModuleFunction;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter};
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::call::{Call, CallBridge, CallError, CallResult, Callable, CallableId};
    use arora_types::data::{DataStore, Key, StateChange};
    use arora_types::record::module::frozen::{Function, Parameter};
    use arora_types::record::ty::{FrozenOption, FrozenTy, PrimitiveKind};
    use arora_types::value::{StructureField, Value};
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;
    use uuid::Uuid;

    const ECHO: Uuid = Uuid::from_u128(0xEC40);
    const INPUT: Uuid = Uuid::from_u128(0xEC41);
    const OUTPUT: Uuid = Uuid::from_u128(0xEC42);

    fn unset(key: &str) -> StateChange {
        StateChange {
            set: HashMap::new(),
            unset: std::collections::HashSet::from([Key::from(key)]),
        }
    }

    fn optional_string() -> FrozenTy {
        FrozenTy::FrozenOption(FrozenOption {
            element: Box::new(FrozenTy::from(PrimitiveKind::String)),
        })
    }

    /// `echo(input: Option<String>, output: &mut Option<String>)`.
    fn echo_index() -> HashMap<Uuid, ModuleFunction> {
        HashMap::from([(
            ECHO,
            ModuleFunction {
                module_id: Uuid::from_u128(0xEC00),
                function_id: ECHO,
                function_name: "echo".to_string(),
                function: Function {
                    parameters: HashMap::from([
                        (
                            INPUT,
                            Parameter {
                                name: "input".to_string(),
                                ty: optional_string(),
                                mutable: false,
                            },
                        ),
                        (
                            OUTPUT,
                            Parameter {
                                name: "output".to_string(),
                                ty: optional_string(),
                                mutable: true,
                            },
                        ),
                    ]),
                    parameter_ordering: vec![INPUT, OUTPUT],
                    return_ty: FrozenTy::from(PrimitiveKind::U8),
                },
            },
        )])
    }

    /// Serves `echo` the way a module decoding `Option<String>` would: it
    /// refuses `()` for its optional input, and returns its output framed as
    /// an optional. Records the inputs it received.
    #[derive(Default)]
    struct EchoBridge {
        registered: HashMap<u64, Rc<dyn Callable>>,
        next_id: u64,
        inputs: Rc<RefCell<Vec<Value>>>,
    }

    impl CallBridge for EchoBridge {
        fn arora_call(&mut self, call: Call) -> Result<CallResult, CallError> {
            let input = call
                .args
                .iter()
                .find(|arg| arg.id == INPUT)
                .map(|arg| (*arg.value).clone())
                .ok_or(CallError::Generic {
                    message: "no input".into(),
                })?;
            self.inputs.borrow_mut().push(input.clone());
            let output = match input {
                Value::Option(None) => Value::Option(None),
                Value::Option(Some(s)) if matches!(*s, Value::String(_)) => Value::Option(Some(s)),
                other => {
                    return Err(CallError::Generic {
                        message: format!("input: unexpected value {other}"),
                    })
                }
            };
            Ok(CallResult {
                ret: Value::Unit,
                mutated: vec![StructureField {
                    id: OUTPUT,
                    value: Box::new(output),
                }],
            })
        }
        fn arora_register_callable(&mut self, callable: Rc<dyn Callable>) -> CallableId {
            let id = self.next_id;
            self.next_id += 1;
            self.registered.insert(id, callable);
            CallableId { id }
        }
        fn arora_unregister_callable(&mut self, callable_id: &CallableId) {
            self.registered.remove(&callable_id.id);
        }
        fn arora_call_indirect(&mut self, callable_id: &CallableId) -> Result<Value, CallError> {
            let callable = self.registered[&callable_id.id].clone();
            callable.call(self)
        }
    }

    #[test]
    fn an_absent_key_binds_none_and_an_optional_output_maps_to_the_key() {
        let store = SimpleDataStore::new();
        let mut tree = BehaviorTreeInterpreter::new(Rc::new(echo_index()));
        tree.load_groot(
            r#"<root main_tree_to_execute="MainTree"><BehaviorTree ID="MainTree">
                 <Echo input="{in}" output="{out}"/>
               </BehaviorTree></root>"#,
        )
        .expect("echo resolves by its PascalCase name");
        let mut bridge = EchoBridge::default();
        let inputs = bridge.inputs.clone();
        let read = |key: &str| store.read(&[Key::from(key)]).remove(0);
        let mut tick = |bridge: &mut EchoBridge| {
            let mut ctx = BehaviorContext {
                store: &store,
                call_bridge: bridge,
            };
            tree.tick(&mut ctx).expect("the tree ticks");
        };

        // `in` is not set: the module receives `None`, not `()`, and writes
        // `None`, which leaves `out` absent.
        tick(&mut bridge);
        assert_eq!(inputs.borrow().last(), Some(&Value::Option(None)));
        assert_eq!(read("out"), None);

        // `in` is set: the module receives `Some("x")`, and its `Some`
        // creates `out`, holding the bare string.
        store
            .write(StateChange::set("in", Value::String("x".into())))
            .unwrap();
        tick(&mut bridge);
        assert_eq!(
            inputs.borrow().last(),
            Some(&Value::Option(Some(Box::new(Value::String("x".into())))))
        );
        assert_eq!(read("out"), Some(Value::String("x".into())));

        // `in` is unset again: `None` unsets `out`.
        store.write(unset("in")).unwrap();
        tick(&mut bridge);
        assert_eq!(inputs.borrow().last(), Some(&Value::Option(None)));
        assert_eq!(read("out"), None);
    }
}