mecha10-behavior-runtime 4.2.10

Behavior tree runtime for Mecha10 - unified AI and logic composition system
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
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
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
//! Composition primitives for building behavior trees
//!
//! Includes Sequence, Selector, and Parallel, plus single-child decorators (Inverter,

use crate::{BehaviorNode, BoxedBehavior, NodeStatus, TreeStatusSnapshot};
use async_trait::async_trait;
use mecha10_core::config::{controller_mode, ControllerMode};
use mecha10_core::Context;
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use std::time::{Duration, Instant};
use tracing::{debug, info, warn};

#[derive(Debug)]
pub struct SequenceNode {
    children: Vec<BoxedBehavior>,
    current_index: usize,
    last_status: Option<NodeStatus>,
}

impl SequenceNode {
    /// Create a new sequence node with the given children.
    pub fn new(children: Vec<BoxedBehavior>) -> Self {
        Self {
            children,
            current_index: 0,
            last_status: None,
        }
    }

    /// Add a child behavior to the sequence.
    pub fn add_child(&mut self, child: BoxedBehavior) {
        self.children.push(child);
    }

    /// Get the number of children.
    pub fn len(&self) -> usize {
        self.children.len()
    }

    /// Check if the sequence is empty.
    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

#[async_trait]
impl BehaviorNode for SequenceNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if self.children.is_empty() {
            self.last_status = Some(NodeStatus::Success);
            return Ok(NodeStatus::Success);
        }

        let total_children = self.children.len();
        while self.current_index < total_children {
            debug!(
                "Sequence: ticking child {} of {}",
                self.current_index + 1,
                total_children
            );

            let child = &mut self.children[self.current_index];
            match child.tick(ctx).await? {
                NodeStatus::Success => {
                    self.current_index += 1;
                }
                NodeStatus::Failure => {
                    debug!("Sequence: child {} failed", self.current_index + 1);
                    self.last_status = Some(NodeStatus::Failure);
                    return Ok(NodeStatus::Failure);
                }
                NodeStatus::Running => {
                    self.last_status = Some(NodeStatus::Running);
                    return Ok(NodeStatus::Running);
                }
            }
        }

        debug!("Sequence: all children succeeded");
        self.last_status = Some(NodeStatus::Success);
        Ok(NodeStatus::Success)
    }

    crate::reset_index_field!(current_index);

    fn name(&self) -> &str {
        "sequence"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        crate::boxed_children_mut(self.children.iter_mut())
    }

    fn active_capability(&self) -> Option<&str> {
        self.children
            .get(self.current_index)
            .and_then(|c| c.active_capability())
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: self.children.iter().map(|c| c.status_snapshot()).collect(),
        }
    }
}

#[derive(Debug)]
pub struct SelectOrNode {
    children: Vec<BoxedBehavior>,
    current_index: usize,
    last_status: Option<NodeStatus>,
}

impl SelectOrNode {
    /// Create a new selector node with the given children.
    pub fn new(children: Vec<BoxedBehavior>) -> Self {
        Self {
            children,
            current_index: 0,
            last_status: None,
        }
    }

    /// Add a child behavior to the selector.
    pub fn add_child(&mut self, child: BoxedBehavior) {
        self.children.push(child);
    }

    /// Get the number of children.
    pub fn len(&self) -> usize {
        self.children.len()
    }

    /// Check if the selector is empty.
    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

#[async_trait]
impl BehaviorNode for SelectOrNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if self.children.is_empty() {
            self.last_status = Some(NodeStatus::Failure);
            return Ok(NodeStatus::Failure);
        }

        let total_children = self.children.len();
        while self.current_index < total_children {
            debug!(
                "Selector: ticking child {} of {}",
                self.current_index + 1,
                total_children
            );

            let child = &mut self.children[self.current_index];
            match child.tick(ctx).await? {
                NodeStatus::Success => {
                    debug!("Selector: child {} succeeded", self.current_index + 1);
                    self.last_status = Some(NodeStatus::Success);
                    return Ok(NodeStatus::Success);
                }
                NodeStatus::Failure => {
                    warn!("Selector: child {} failed, trying next", self.current_index + 1);
                    self.current_index += 1;
                }
                NodeStatus::Running => {
                    self.last_status = Some(NodeStatus::Running);
                    return Ok(NodeStatus::Running);
                }
            }
        }

        debug!("Selector: all children failed");
        self.last_status = Some(NodeStatus::Failure);
        Ok(NodeStatus::Failure)
    }

    crate::reset_index_field!(current_index);

    fn name(&self) -> &str {
        "selector"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        crate::boxed_children_mut(self.children.iter_mut())
    }

    fn active_capability(&self) -> Option<&str> {
        self.children
            .get(self.current_index)
            .and_then(|c| c.active_capability())
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: self.children.iter().map(|c| c.status_snapshot()).collect(),
        }
    }
}

/// Like [`SelectOrNode`] (ticks children until one returns non-`Failure`), but instead of always
/// trying children in a fixed index order, each tick-cycle picks the next untried child via a
/// weighted-random draw among children not yet tried THIS resolution cycle. A weight of `0.0` (or
/// negative) means that child is never picked. Once a child is chosen it is "sticky": while it
/// reports `Running`, the next `tick()` re-ticks that same child rather than re-rolling - only
/// once it resolves does the node either return (on `Success`) or roll again among the remaining
/// untried children (on `Failure`), mirroring `SelectOrNode::current_index`'s "resume where we
/// left off" behavior, just with a random rather than fixed starting point each cycle.
#[derive(Debug)]
pub struct WeightedSelectNode {
    children: Vec<BoxedBehavior>,
    weights: Vec<f64>,
    /// Which children have already been tried (and failed) this resolution cycle - cleared
    /// whenever the node resolves (`Success`, or `Failure` once every eligible child is
    /// exhausted).
    tried: Vec<bool>,
    /// The child currently being ticked, if one was chosen and hasn't resolved yet. `None` means
    /// the next `tick()` must roll for a new child.
    current_index: Option<usize>,
    rng: StdRng,
    last_status: Option<NodeStatus>,
}

impl WeightedSelectNode {
    /// Create a new weighted selector from `(weight, child)` pairs, using a freshly OS-seeded
    /// RNG. Negative weights are clamped to `0.0` (never picked).
    pub fn new(weighted_children: Vec<(f64, BoxedBehavior)>) -> Self {
        Self::with_rng(weighted_children, StdRng::from_rng(&mut rand::rng()))
    }

    /// Create a new weighted selector using the given RNG - the injection point tests use for
    /// deterministic behavior (e.g. `StdRng::seed_from_u64(seed)`).
    pub fn with_rng(weighted_children: Vec<(f64, BoxedBehavior)>, rng: StdRng) -> Self {
        let mut weights = Vec::with_capacity(weighted_children.len());
        let mut children = Vec::with_capacity(weighted_children.len());
        for (weight, child) in weighted_children {
            weights.push(weight.max(0.0));
            children.push(child);
        }
        let tried = vec![false; children.len()];

        Self {
            children,
            weights,
            tried,
            current_index: None,
            rng,
            last_status: None,
        }
    }

    /// Get the number of children.
    pub fn len(&self) -> usize {
        self.children.len()
    }

    /// Check if the selector is empty.
    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }

    /// Weighted-random draw among children that are both untried this cycle and have a positive
    /// weight - `None` once no eligible child remains.
    fn pick_next(&mut self) -> Option<usize> {
        let candidates: Vec<usize> = (0..self.children.len())
            .filter(|&i| !self.tried[i] && self.weights[i] > 0.0)
            .collect();

        let total: f64 = candidates.iter().map(|&i| self.weights[i]).sum();
        if candidates.is_empty() || total <= 0.0 {
            return None;
        }

        let mut draw = self.rng.random::<f64>() * total;
        for &i in &candidates {
            draw -= self.weights[i];
            if draw <= 0.0 {
                return Some(i);
            }
        }

        // Floating-point rounding may leave a tiny positive remainder; fall back to the last
        // candidate rather than returning None and spuriously failing the selection.
        candidates.last().copied()
    }
}

#[async_trait]
impl BehaviorNode for WeightedSelectNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if self.children.is_empty() {
            self.last_status = Some(NodeStatus::Failure);
            return Ok(NodeStatus::Failure);
        }

        loop {
            let idx = match self.current_index {
                Some(idx) => idx,
                None => match self.pick_next() {
                    Some(idx) => idx,
                    None => {
                        debug!("WeightedSelect: no eligible child remains, failing");
                        self.tried.iter_mut().for_each(|t| *t = false);
                        self.last_status = Some(NodeStatus::Failure);
                        return Ok(NodeStatus::Failure);
                    }
                },
            };

            self.current_index = Some(idx);
            self.tried[idx] = true;

            let child = &mut self.children[idx];
            match child.tick(ctx).await? {
                NodeStatus::Success => {
                    debug!("WeightedSelect: child {} succeeded", idx);
                    self.current_index = None;
                    self.tried.iter_mut().for_each(|t| *t = false);
                    self.last_status = Some(NodeStatus::Success);
                    return Ok(NodeStatus::Success);
                }
                NodeStatus::Failure => {
                    debug!("WeightedSelect: child {} failed, rolling again", idx);
                    self.current_index = None;
                }
                NodeStatus::Running => {
                    self.last_status = Some(NodeStatus::Running);
                    return Ok(NodeStatus::Running);
                }
            }
        }
    }

    fn reset_self(&mut self) {
        self.current_index = None;
        self.tried.iter_mut().for_each(|t| *t = false);
    }

    fn name(&self) -> &str {
        "weighted_select"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        crate::boxed_children_mut(self.children.iter_mut())
    }

    fn active_capability(&self) -> Option<&str> {
        self.current_index
            .and_then(|i| self.children.get(i))
            .and_then(|c| c.active_capability())
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: self.children.iter().map(|c| c.status_snapshot()).collect(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParallelPolicy {
    RequireAll,

    RequireOne,

    RequireN(usize),
}

#[derive(Debug)]
pub struct ParallelNode {
    children: Vec<BoxedBehavior>,
    policy: ParallelPolicy,
    child_statuses: Vec<NodeStatus>,
    last_status: Option<NodeStatus>,
}

impl ParallelNode {
    /// Create a new parallel node with the given children and policy.
    pub fn new(children: Vec<BoxedBehavior>, policy: ParallelPolicy) -> Self {
        let child_statuses = vec![NodeStatus::Running; children.len()];
        Self {
            children,
            policy,
            child_statuses,
            last_status: None,
        }
    }

    /// Add a child behavior to the parallel node.
    pub fn add_child(&mut self, child: BoxedBehavior) {
        self.children.push(child);
        self.child_statuses.push(NodeStatus::Running);
    }

    /// Get the number of children.
    pub fn len(&self) -> usize {
        self.children.len()
    }

    /// Check if the parallel node is empty.
    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

#[async_trait]
impl BehaviorNode for ParallelNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if self.children.is_empty() {
            self.last_status = Some(NodeStatus::Success);
            return Ok(NodeStatus::Success);
        }

        for (i, child) in self.children.iter_mut().enumerate() {
            if self.child_statuses[i].is_running() {
                let status = child.tick(ctx).await?;
                self.child_statuses[i] = status;
                debug!("Parallel: child {} status: {}", i + 1, status);
            }
        }

        let success_count = self.child_statuses.iter().filter(|s| s.is_success()).count();
        let failure_count = self.child_statuses.iter().filter(|s| s.is_failure()).count();
        let _running_count = self.child_statuses.iter().filter(|s| s.is_running()).count();

        let status = match self.policy {
            ParallelPolicy::RequireAll => {
                if failure_count > 0 {
                    debug!("Parallel (RequireAll): at least one child failed");
                    NodeStatus::Failure
                } else if success_count == self.children.len() {
                    debug!("Parallel (RequireAll): all children succeeded");
                    NodeStatus::Success
                } else {
                    NodeStatus::Running
                }
            }
            ParallelPolicy::RequireOne => {
                if success_count > 0 {
                    debug!("Parallel (RequireOne): at least one child succeeded");
                    NodeStatus::Success
                } else if failure_count == self.children.len() {
                    debug!("Parallel (RequireOne): all children failed");
                    NodeStatus::Failure
                } else {
                    NodeStatus::Running
                }
            }
            ParallelPolicy::RequireN(n) => {
                if success_count >= n {
                    debug!("Parallel (RequireN({})): {} children succeeded", n, success_count);
                    NodeStatus::Success
                } else if (self.children.len() - failure_count) < n {
                    debug!("Parallel (RequireN({})): not enough children can succeed", n);
                    NodeStatus::Failure
                } else {
                    NodeStatus::Running
                }
            }
        };

        self.last_status = Some(status);
        Ok(status)
    }

    crate::reset_child_statuses_field!(child_statuses);

    fn name(&self) -> &str {
        "parallel"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        crate::boxed_children_mut(self.children.iter_mut())
    }

    /// The first still-`Running` child's capability, if any - "first" is an arbitrary but
    /// deterministic tie-break since at most one running child is expected to declare one.
    fn active_capability(&self) -> Option<&str> {
        self.children
            .iter()
            .zip(self.child_statuses.iter())
            .find(|(_, status)| status.is_running())
            .and_then(|(child, _)| child.active_capability())
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: self.children.iter().map(|c| c.status_snapshot()).collect(),
        }
    }
}

/// Like `ParallelNode`, but with no memory of a prior resolution: every child is ticked, every
/// call, unconditionally. Needed for an interrupt-condition layer that must be re-evaluated
/// indefinitely (e.g. the operator clicking/clearing repeatedly over a session).
#[derive(Debug)]
pub struct WatchNode {
    children: Vec<BoxedBehavior>,
    policy: ParallelPolicy,
    last_active: Option<usize>,
    last_status: Option<NodeStatus>,
}

impl WatchNode {
    /// Create a new watch node with the given children and policy.
    pub fn new(children: Vec<BoxedBehavior>, policy: ParallelPolicy) -> Self {
        Self {
            children,
            policy,
            last_active: None,
            last_status: None,
        }
    }

    /// Add a child behavior to the watch node.
    pub fn add_child(&mut self, child: BoxedBehavior) {
        self.children.push(child);
    }

    /// Get the number of children.
    pub fn len(&self) -> usize {
        self.children.len()
    }

    /// Check if the watch node is empty.
    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }
}

#[async_trait]
impl BehaviorNode for WatchNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if self.children.is_empty() {
            self.last_active = None;
            self.last_status = Some(NodeStatus::Failure);
            return Ok(NodeStatus::Failure);
        }

        let mut statuses = Vec::with_capacity(self.children.len());
        for child in &mut self.children {
            statuses.push(child.tick(ctx).await?);
        }

        self.last_active = statuses.iter().position(|s| s.is_running());

        let success_count = statuses.iter().filter(|s| s.is_success()).count();
        let failure_count = statuses.iter().filter(|s| s.is_failure()).count();

        let status = match self.policy {
            ParallelPolicy::RequireAll => {
                if failure_count > 0 {
                    debug!("Watch (RequireAll): at least one child failed");
                    NodeStatus::Failure
                } else if success_count == self.children.len() {
                    debug!("Watch (RequireAll): all children succeeded");
                    NodeStatus::Success
                } else {
                    NodeStatus::Running
                }
            }
            ParallelPolicy::RequireOne => {
                if success_count > 0 {
                    debug!("Watch (RequireOne): at least one child succeeded");
                    NodeStatus::Success
                } else if failure_count == self.children.len() {
                    debug!("Watch (RequireOne): all children failed");
                    NodeStatus::Failure
                } else {
                    NodeStatus::Running
                }
            }
            ParallelPolicy::RequireN(n) => {
                if success_count >= n {
                    debug!("Watch (RequireN({})): {} children succeeded", n, success_count);
                    NodeStatus::Success
                } else if (self.children.len() - failure_count) < n {
                    debug!("Watch (RequireN({})): not enough children can succeed", n);
                    NodeStatus::Failure
                } else {
                    NodeStatus::Running
                }
            }
        };

        self.last_status = Some(status);
        Ok(status)
    }

    fn name(&self) -> &str {
        "watch"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        crate::boxed_children_mut(self.children.iter_mut())
    }

    /// Unlike Sequence/Selector/Parallel, every child here is ticked every time with no persisted
    /// statuses to read after the fact - `tick()` records which child resolved `Running` *this*
    /// call into `last_active`, and this forwards to that child.
    fn active_capability(&self) -> Option<&str> {
        self.last_active
            .and_then(|i| self.children.get(i))
            .and_then(|child| child.active_capability())
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: self.children.iter().map(|c| c.status_snapshot()).collect(),
        }
    }
}

/// A single priority layer in a [`SubsumptionNode`]: a priority (higher wins) plus the behavior
/// that implements it.
#[derive(Debug)]
pub struct SubsumptionLayer {
    pub priority: u8,
    pub behavior: BoxedBehavior,
    pub name: Option<String>,
}

impl SubsumptionLayer {
    mecha10_core::new_with_defaults!(
        /// Create a new subsumption layer.
        pub fn new(priority: u8, behavior: BoxedBehavior) -> Self {
            name: None
        }
    );

    mecha10_core::builder_setter!(into_some, with_name, name, impl Into<String>);
}

/// Priority-based preemption (subsumption architecture): on each tick, tries each layer
/// highest-priority first. The first layer whose `tick()` returns `Running`/`Success` "wins";
/// lower-priority layers aren't ticked that cycle, preserving their internal progress.
#[derive(Debug)]
pub struct SubsumptionNode {
    pub layers: Vec<SubsumptionLayer>,
    last_winning_layer: Option<usize>,
    last_status: Option<NodeStatus>,
}

impl SubsumptionNode {
    /// Create a new empty subsumption node.
    pub fn new() -> Self {
        Self {
            layers: Vec::new(),
            last_winning_layer: None,
            last_status: None,
        }
    }

    /// Add a layer with the given priority and behavior.
    ///
    /// Layers are automatically sorted by priority (highest first).
    pub fn add_layer(mut self, priority: u8, behavior: BoxedBehavior) -> Self {
        self.layers.push(SubsumptionLayer::new(priority, behavior));
        self.layers.sort_by_key(|b| std::cmp::Reverse(b.priority));
        self
    }
}

impl Default for SubsumptionNode {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl BehaviorNode for SubsumptionNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if self.layers.is_empty() {
            self.last_winning_layer = None;
            self.last_status = Some(NodeStatus::Failure);
            return Ok(NodeStatus::Failure);
        }

        for (i, layer) in self.layers.iter_mut().enumerate() {
            let layer_name = layer.name.as_deref().unwrap_or("unnamed");

            debug!(
                "Subsumption: trying layer '{}' (priority {})",
                layer_name, layer.priority
            );

            let status = layer.behavior.tick(ctx).await?;

            match status {
                NodeStatus::Success | NodeStatus::Running => {
                    info!(
                        "Subsumption: layer '{}' (priority {}) taking control with status {}",
                        layer_name, layer.priority, status
                    );
                    self.last_winning_layer = Some(i);
                    self.last_status = Some(status);
                    return Ok(status);
                }
                NodeStatus::Failure => {
                    debug!("Subsumption: layer '{}' failed, trying next layer", layer_name);
                    continue;
                }
            }
        }

        debug!("Subsumption: all layers failed");
        self.last_winning_layer = None;
        self.last_status = Some(NodeStatus::Failure);
        Ok(NodeStatus::Failure)
    }

    fn name(&self) -> &str {
        "subsumption"
    }

    crate::children_mut_via_wrapped_behavior!(layers, layer);

    /// Forwards the winning layer's capability (the highest-priority layer whose `tick()`
    /// returned `Running`/`Success` this call) - `None` if every layer failed. Tracked separately
    /// via `last_winning_layer` since it isn't otherwise recoverable after `tick()` returns.
    fn active_capability(&self) -> Option<&str> {
        self.last_winning_layer
            .and_then(|i| self.layers.get(i))
            .and_then(|layer| layer.behavior.active_capability())
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: self.layers.iter().map(|l| l.behavior.status_snapshot()).collect(),
        }
    }
}

/// Which [`ControllerMode`] variant a [`ConditionKind::ControllerModeIs`] predicate matches - the
/// variant only, since `ControllerMode::Joints`'s joint-name list is irrelevant to the check.
/// Deliberately mirrors [`ControllerMode`]'s own variant names (and
/// [`mecha10_core::node::Capability::Locomotion`]/`Joints`) rather than inventing a parallel
/// vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ControllerModeKind {
    Locomotion,
    Joints,
}

/// A predicate a [`ConditionNode`] evaluates against live project/robot state before deciding
/// whether to tick its child. Deliberately a small, closed enum rather than a general expression
/// language: add a variant here when a genuinely new predicate is needed. Starts with just the
/// two controller-mode checks `patrol` needs today, but is reusable infrastructure - any behavior
/// tree can gate a subtree on one of these without a bespoke composite node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConditionKind {
    /// True when the project's current [`mecha10_core::config::controller_mode`] is the given
    /// variant - the same capability-based dispatch `wander`/`move` leaf nodes already use (see
    /// `actions/movement.rs`'s `resolve_movement_output`), exposed as a composition-level gate so
    /// an entire subtree can be made conditional on the project's actuation surface.
    ControllerModeIs(ControllerModeKind),
}

impl ConditionKind {
    /// Evaluate this predicate against the current process/project state.
    fn evaluate(&self) -> bool {
        match self {
            ConditionKind::ControllerModeIs(kind) => {
                let current = match controller_mode() {
                    ControllerMode::Locomotion => ControllerModeKind::Locomotion,
                    ControllerMode::Joints { .. } => ControllerModeKind::Joints,
                };
                current == *kind
            }
        }
    }
}

/// Single-child decorator that gates its child on a [`ConditionKind`] predicate: it evaluates the
/// predicate FIRST and only ticks the child (forwarding the child's status unchanged) while the
/// predicate holds; when the predicate is false it reports `Failure` WITHOUT ticking the child at
/// all.
///
/// Dropping several of these into a [`SelectOrNode`] gives capability- or state-gated branch
/// selection out of a small, reusable building block: `SelectOrNode` already advances past any
/// child that returns `Failure`, so a false condition naturally falls through to the next option
/// without ever running its subtree. A smaller, more composable primitive than a bespoke
/// branch-on-capability composite node, and it fits the existing decorator pattern
/// ([`InverterNode`]/[`ForceSuccessNode`]/[`ForceFailureNode`]).
#[derive(Debug)]
pub struct ConditionNode {
    condition: ConditionKind,
    child: BoxedBehavior,
    last_status: Option<NodeStatus>,
}

impl ConditionNode {
    /// Create a new condition node gating `child` on `condition`.
    pub fn new(condition: ConditionKind, child: BoxedBehavior) -> Self {
        Self {
            condition,
            child,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for ConditionNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        let status = if self.condition.evaluate() {
            self.child.tick(ctx).await?
        } else {
            debug!(
                "Condition: predicate {:?} is false, returning Failure without ticking child",
                self.condition
            );
            NodeStatus::Failure
        };

        self.last_status = Some(status);
        Ok(status)
    }

    fn name(&self) -> &str {
        "condition"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Negates a `Success`/`Failure` result from its single child; `Running` passes through
/// unchanged. The canonical decorator for turning a "condition" leaf/subtree into its opposite
/// (e.g. "target NOT in range") without duplicating the underlying check.
#[derive(Debug)]
pub struct InverterNode {
    child: BoxedBehavior,
    last_status: Option<NodeStatus>,
}

impl InverterNode {
    /// Create a new inverter node wrapping `child`.
    pub fn new(child: BoxedBehavior) -> Self {
        Self {
            child,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for InverterNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        let status = match self.child.tick(ctx).await? {
            NodeStatus::Success => NodeStatus::Failure,
            NodeStatus::Failure => NodeStatus::Success,
            NodeStatus::Running => NodeStatus::Running,
        };
        self.last_status = Some(status);
        Ok(status)
    }

    fn name(&self) -> &str {
        "inverter"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Always reports `Success` once its child resolves, regardless of whether the child actually
/// succeeded or failed; `Running` passes through unchanged. Useful for an optional step whose
/// failure shouldn't abort the rest of a `Sequence`.
#[derive(Debug)]
pub struct ForceSuccessNode {
    child: BoxedBehavior,
    last_status: Option<NodeStatus>,
}

impl ForceSuccessNode {
    /// Create a new force-success node wrapping `child`.
    pub fn new(child: BoxedBehavior) -> Self {
        Self {
            child,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for ForceSuccessNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        let status = match self.child.tick(ctx).await? {
            NodeStatus::Running => NodeStatus::Running,
            NodeStatus::Success | NodeStatus::Failure => NodeStatus::Success,
        };
        self.last_status = Some(status);
        Ok(status)
    }

    fn name(&self) -> &str {
        "force_success"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Always reports `Failure` once its child resolves, regardless of whether the child actually
/// succeeded or failed; `Running` passes through unchanged. The mirror of `ForceSuccessNode`,
/// useful inside a `Selector` to force a fallback to the next option.
#[derive(Debug)]
pub struct ForceFailureNode {
    child: BoxedBehavior,
    last_status: Option<NodeStatus>,
}

impl ForceFailureNode {
    /// Create a new force-failure node wrapping `child`.
    pub fn new(child: BoxedBehavior) -> Self {
        Self {
            child,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for ForceFailureNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        let status = match self.child.tick(ctx).await? {
            NodeStatus::Running => NodeStatus::Running,
            NodeStatus::Success | NodeStatus::Failure => NodeStatus::Failure,
        };
        self.last_status = Some(status);
        Ok(status)
    }

    fn name(&self) -> &str {
        "force_failure"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Re-runs its child every time it succeeds, up to an optional fixed count; a `Failure` from the
/// child always ends the loop immediately with `Failure`. `count: None` repeats indefinitely
/// (e.g. a patrol leg re-run forever until something fails it).
#[derive(Debug)]
pub struct RepeatNode {
    child: BoxedBehavior,
    count: Option<u32>,
    completed: u32,
    last_status: Option<NodeStatus>,
}

impl RepeatNode {
    /// Create a new repeat node wrapping `child`. `count: None` repeats indefinitely.
    pub fn new(child: BoxedBehavior, count: Option<u32>) -> Self {
        Self {
            child,
            count,
            completed: 0,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for RepeatNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if let Some(count) = self.count {
            if self.completed >= count {
                self.last_status = Some(NodeStatus::Success);
                return Ok(NodeStatus::Success);
            }
        }

        let status = match self.child.tick(ctx).await? {
            NodeStatus::Success => {
                self.completed += 1;
                self.child.reset().await?;

                match self.count {
                    Some(count) if self.completed >= count => NodeStatus::Success,
                    _ => NodeStatus::Running,
                }
            }
            NodeStatus::Failure => NodeStatus::Failure,
            NodeStatus::Running => NodeStatus::Running,
        };

        self.last_status = Some(status);
        Ok(status)
    }

    fn reset_self(&mut self) {
        self.completed = 0;
    }

    fn name(&self) -> &str {
        "repeat"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Re-runs its child up to `max_attempts` times whenever it fails, succeeding as soon as one
/// attempt succeeds; only reports `Failure` once every attempt has been exhausted. The
/// complement of `RepeatNode` (which loops on success).
#[derive(Debug)]
pub struct RetryNode {
    child: BoxedBehavior,
    max_attempts: u32,
    attempts: u32,
    last_status: Option<NodeStatus>,
}

impl RetryNode {
    /// Create a new retry node wrapping `child`, allowing up to `max_attempts` tries (must be at
    /// least 1).
    pub fn new(child: BoxedBehavior, max_attempts: u32) -> Self {
        Self {
            child,
            max_attempts: max_attempts.max(1),
            attempts: 0,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for RetryNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        let status = match self.child.tick(ctx).await? {
            NodeStatus::Success => NodeStatus::Success,
            NodeStatus::Running => NodeStatus::Running,
            NodeStatus::Failure => {
                self.attempts += 1;
                if self.attempts >= self.max_attempts {
                    debug!("Retry: child failed after {} attempt(s), giving up", self.attempts);
                    NodeStatus::Failure
                } else {
                    debug!(
                        "Retry: child failed on attempt {} of {}, retrying",
                        self.attempts, self.max_attempts
                    );
                    self.child.reset().await?;
                    NodeStatus::Running
                }
            }
        };

        self.last_status = Some(status);
        Ok(status)
    }

    fn reset_self(&mut self) {
        self.attempts = 0;
    }

    fn name(&self) -> &str {
        "retry"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Bounds how long its child may stay `Running`: once `duration` elapses without the child
/// resolving, immediately reports `Failure` (resetting the child's state). A child that resolves
/// before the deadline passes its status straight through.
#[derive(Debug)]
pub struct TimeoutNode {
    child: BoxedBehavior,
    duration: Duration,
    start_time: Option<Instant>,
    last_status: Option<NodeStatus>,
}

impl TimeoutNode {
    /// Create a new timeout node wrapping `child`, bounding it to `duration`.
    pub fn new(child: BoxedBehavior, duration: Duration) -> Self {
        Self {
            child,
            duration,
            start_time: None,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for TimeoutNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        let now = Instant::now();
        let start = *self.start_time.get_or_insert(now);

        if now.duration_since(start) >= self.duration {
            warn!("Timeout: child did not resolve within {:?}, failing", self.duration);
            self.start_time = None;
            self.child.reset().await?;
            self.last_status = Some(NodeStatus::Failure);
            return Ok(NodeStatus::Failure);
        }

        let status = self.child.tick(ctx).await?;
        if status.is_complete() {
            self.start_time = None;
        }
        self.last_status = Some(status);
        Ok(status)
    }

    fn reset_self(&mut self) {
        self.start_time = None;
    }

    fn name(&self) -> &str {
        "timeout"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

/// Bounds the GAP between runs of its child, the complement of [`TimeoutNode`] (which bounds how
/// long a single run may stay `Running`). Once the child returns a terminal result (`Success` or
/// `Failure`), this node refuses to re-tick it for `cooldown`: during that window `tick()`
/// returns `Failure` immediately WITHOUT ticking the child at all. Once the window elapses,
/// ticking resumes normally. A child that returns `Running` doesn't start the cooldown clock -
/// only a terminal result does.
#[derive(Debug)]
pub struct CooldownNode {
    child: BoxedBehavior,
    cooldown: Duration,
    /// Set to the instant the cooldown window ends whenever the child resolves; `None` means no
    /// cooldown is in effect (either the child has never resolved, or the window already elapsed
    /// and was cleared).
    cooldown_until: Option<Instant>,
    last_status: Option<NodeStatus>,
}

impl CooldownNode {
    /// Create a new cooldown node wrapping `child`, refusing to re-tick it for `cooldown` after
    /// it last resolved.
    pub fn new(child: BoxedBehavior, cooldown: Duration) -> Self {
        Self {
            child,
            cooldown,
            cooldown_until: None,
            last_status: None,
        }
    }
}

#[async_trait]
impl BehaviorNode for CooldownNode {
    async fn tick(&mut self, ctx: &Context) -> anyhow::Result<NodeStatus> {
        if let Some(until) = self.cooldown_until {
            if Instant::now() < until {
                debug!("Cooldown: still cooling down, returning Failure without ticking child");
                self.last_status = Some(NodeStatus::Failure);
                return Ok(NodeStatus::Failure);
            }
            self.cooldown_until = None;
        }

        let status = self.child.tick(ctx).await?;
        if status.is_complete() {
            self.cooldown_until = Some(Instant::now() + self.cooldown);
        }
        self.last_status = Some(status);
        Ok(status)
    }

    fn reset_self(&mut self) {
        self.cooldown_until = None;
    }

    fn name(&self) -> &str {
        "cooldown"
    }

    fn children_mut(&mut self) -> Vec<&mut dyn BehaviorNode> {
        vec![self.child.as_mut()]
    }

    fn active_capability(&self) -> Option<&str> {
        self.child.active_capability()
    }

    fn status_snapshot(&self) -> TreeStatusSnapshot {
        TreeStatusSnapshot {
            name: self.name().to_string(),
            status: self.last_status,
            active_capability: self.active_capability().map(String::from),
            children: vec![self.child.status_snapshot()],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Default)]
    struct DummyBehavior;

    #[async_trait]
    impl BehaviorNode for DummyBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            unimplemented!("not exercised by these tests")
        }
    }

    #[derive(Debug)]
    struct CapabilityBehavior(&'static str);

    #[async_trait]
    impl BehaviorNode for CapabilityBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            unimplemented!("not exercised by these tests")
        }

        fn active_capability(&self) -> Option<&str> {
            Some(self.0)
        }
    }

    #[test]
    fn sequence_children_mut_exposes_every_child() {
        let mut node = SequenceNode::new(vec![Box::new(DummyBehavior), Box::new(DummyBehavior)]);
        assert_eq!(node.children_mut().len(), 2);
    }

    #[tokio::test]
    async fn sequence_reset_rewinds_current_index() {
        let mut node = SequenceNode::new(vec![Box::new(DummyBehavior)]);
        node.current_index = 1;

        node.reset().await.unwrap();

        assert_eq!(node.current_index, 0);
    }

    #[test]
    fn selector_children_mut_exposes_every_child() {
        let mut node = SelectOrNode::new(vec![Box::new(DummyBehavior), Box::new(DummyBehavior)]);
        assert_eq!(node.children_mut().len(), 2);
    }

    #[tokio::test]
    async fn selector_reset_rewinds_current_index() {
        let mut node = SelectOrNode::new(vec![Box::new(DummyBehavior)]);
        node.current_index = 1;

        node.reset().await.unwrap();

        assert_eq!(node.current_index, 0);
    }

    #[test]
    fn parallel_children_mut_exposes_every_child() {
        let mut node = ParallelNode::new(
            vec![Box::new(DummyBehavior), Box::new(DummyBehavior)],
            ParallelPolicy::RequireAll,
        );
        assert_eq!(node.children_mut().len(), 2);
    }

    #[tokio::test]
    async fn parallel_reset_clears_child_statuses_back_to_running() {
        let mut node = ParallelNode::new(vec![Box::new(DummyBehavior)], ParallelPolicy::RequireAll);
        node.child_statuses[0] = NodeStatus::Success;

        node.reset().await.unwrap();

        assert_eq!(node.child_statuses[0], NodeStatus::Running);
    }

    #[test]
    fn sequence_forwards_the_current_childs_active_capability() {
        let node = SequenceNode::new(vec![Box::new(CapabilityBehavior("rl")), Box::new(DummyBehavior)]);
        assert_eq!(node.active_capability(), Some("rl"));
    }

    #[test]
    fn sequence_has_no_active_capability_once_past_the_declaring_child() {
        let mut node = SequenceNode::new(vec![Box::new(CapabilityBehavior("rl")), Box::new(DummyBehavior)]);
        node.current_index = 1;
        assert_eq!(node.active_capability(), None);
    }

    #[test]
    fn sequence_status_snapshot_is_none_before_any_tick() {
        let node = SequenceNode::new(vec![Box::new(DummyBehavior)]);
        let snapshot = node.status_snapshot();
        assert_eq!(snapshot.status, None);
        assert_eq!(snapshot.name, "sequence");
        assert_eq!(
            snapshot.children.len(),
            1,
            "children must still be recursed into pre-tick"
        );
    }

    /// The core `status_snapshot()` contract for a composite node: the reported `status` must
    /// match exactly what `tick()` itself returned, and `children` must recursively include each
    /// child's own snapshot (here, `StatusAndCapabilityBehavior` - defined below for the
    /// `SubsumptionNode` tests - doubling as a simple fixed-status child).
    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn sequence_status_snapshot_matches_the_last_tick_result_and_recurses_into_children() {
        let ctx = crate::test_helpers::create_test_context("sequence_status_snapshot").await;
        let mut node = SequenceNode::new(vec![Box::new(StatusAndCapabilityBehavior {
            status: NodeStatus::Success,
            capability: "rl",
        })]);

        let status = node.tick(&ctx).await.unwrap();
        assert_eq!(status, NodeStatus::Success);

        let snapshot = node.status_snapshot();
        assert_eq!(snapshot.status, Some(status));
        assert_eq!(snapshot.name, "sequence");
        assert_eq!(
            snapshot.active_capability, None,
            "the only child already succeeded and was advanced past, so no capability is active"
        );
        assert_eq!(snapshot.children.len(), 1);
    }

    #[test]
    fn selector_forwards_the_current_childs_active_capability() {
        let node = SelectOrNode::new(vec![Box::new(CapabilityBehavior("rl")), Box::new(DummyBehavior)]);
        assert_eq!(node.active_capability(), Some("rl"));
    }

    #[test]
    fn parallel_forwards_the_first_running_childs_active_capability() {
        let mut node = ParallelNode::new(
            vec![Box::new(CapabilityBehavior("rl")), Box::new(DummyBehavior)],
            ParallelPolicy::RequireAll,
        );
        node.child_statuses[0] = NodeStatus::Success;
        assert_eq!(
            node.active_capability(),
            None,
            "a non-running child's capability must not be reported"
        );
    }

    /// A child whose status changes from tick to tick (e.g. a target that comes and goes), used
    /// to prove `WatchNode` re-evaluates every call instead of freezing like `ParallelNode`.
    #[derive(Debug)]
    struct SequencedStatusBehavior {
        statuses: Vec<NodeStatus>,
        index: usize,
        tick_count: usize,
        capability: Option<&'static str>,
    }

    impl SequencedStatusBehavior {
        fn new(statuses: Vec<NodeStatus>) -> Self {
            Self {
                statuses,
                index: 0,
                tick_count: 0,
                capability: None,
            }
        }

        fn with_capability(statuses: Vec<NodeStatus>, capability: &'static str) -> Self {
            Self {
                capability: Some(capability),
                ..Self::new(statuses)
            }
        }
    }

    #[async_trait]
    impl BehaviorNode for SequencedStatusBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            self.tick_count += 1;
            let status = self.statuses[self.index.min(self.statuses.len() - 1)];
            if self.index + 1 < self.statuses.len() {
                self.index += 1;
            }
            Ok(status)
        }

        fn active_capability(&self) -> Option<&str> {
            self.capability
        }
    }

    #[test]
    fn watch_children_mut_exposes_every_child() {
        let mut node = WatchNode::new(
            vec![Box::new(DummyBehavior), Box::new(DummyBehavior)],
            ParallelPolicy::RequireOne,
        );
        assert_eq!(node.children_mut().len(), 2);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn watch_is_empty_returns_failure() {
        let ctx = crate::test_helpers::create_test_context("watch_empty").await;
        let mut node = WatchNode::new(vec![], ParallelPolicy::RequireOne);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);
    }

    /// Regression test: unlike `ParallelNode`, `WatchNode` has no `child_statuses` memory, so a
    /// child that flips from `Failure` to `Running` across ticks must be re-ticked every call and
    /// the aggregate status must reflect *that* tick's actual child statuses, not a stale one.
    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn watch_re_ticks_every_child_every_call_and_reflects_the_latest_statuses() {
        let ctx = crate::test_helpers::create_test_context("watch_re_ticks").await;
        let mut node = WatchNode::new(
            vec![Box::new(SequencedStatusBehavior::new(vec![
                NodeStatus::Failure,
                NodeStatus::Running,
                NodeStatus::Failure,
            ]))],
            ParallelPolicy::RequireOne,
        );

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(
            node.tick(&ctx).await.unwrap(),
            NodeStatus::Failure,
            "a ParallelNode would have frozen on the first Failure and never re-ticked the child"
        );
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn watch_forwards_the_currently_running_childs_active_capability() {
        let ctx = crate::test_helpers::create_test_context("watch_capability").await;
        let mut node = WatchNode::new(
            vec![Box::new(SequencedStatusBehavior::with_capability(
                vec![NodeStatus::Running, NodeStatus::Failure],
                "instance_track",
            ))],
            ParallelPolicy::RequireOne,
        );

        node.tick(&ctx).await.unwrap();
        assert_eq!(node.active_capability(), Some("instance_track"));

        node.tick(&ctx).await.unwrap();
        assert_eq!(
            node.active_capability(),
            None,
            "a child that was running last tick and is not running this tick must not keep reporting its capability"
        );
    }

    #[test]
    fn subsumption_children_mut_exposes_every_layer_behavior() {
        let mut node = SubsumptionNode::new()
            .add_layer(10, Box::new(DummyBehavior))
            .add_layer(5, Box::new(DummyBehavior));
        assert_eq!(node.children_mut().len(), 2);
    }

    /// A double that both returns a fixed `NodeStatus` from `tick()` and declares a capability -
    /// `CapabilityBehavior` above only does the latter, so it can't exercise
    /// `SubsumptionNode::active_capability()` end-to-end through an actual `tick()` call.
    #[derive(Debug)]
    struct StatusAndCapabilityBehavior {
        status: NodeStatus,
        capability: &'static str,
    }

    #[async_trait]
    impl BehaviorNode for StatusAndCapabilityBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            Ok(self.status)
        }

        fn active_capability(&self) -> Option<&str> {
            Some(self.capability)
        }
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn subsumption_active_capability_forwards_the_winning_layers_capability() {
        let ctx = crate::test_helpers::create_test_context("subsumption_capability").await;
        let mut node = SubsumptionNode::new()
            .add_layer(
                10,
                Box::new(StatusAndCapabilityBehavior {
                    status: NodeStatus::Failure,
                    capability: "instance_track",
                }),
            )
            .add_layer(
                0,
                Box::new(StatusAndCapabilityBehavior {
                    status: NodeStatus::Running,
                    capability: "patrol",
                }),
            );

        assert_eq!(node.active_capability(), None, "no tick has happened yet");

        let status = node.tick(&ctx).await.unwrap();
        assert_eq!(
            status,
            NodeStatus::Running,
            "the high-priority layer fails, so the low layer wins"
        );
        assert_eq!(
            node.active_capability(),
            Some("patrol"),
            "active_capability must forward the winning (low-priority) layer's capability, not the failed high-priority one"
        );
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn subsumption_active_capability_none_when_all_layers_fail() {
        let ctx = crate::test_helpers::create_test_context("subsumption_capability_all_fail").await;
        let mut node =
            SubsumptionNode::new().add_layer(10, Box::new(SequencedStatusBehavior::new(vec![NodeStatus::Failure])));

        node.tick(&ctx).await.unwrap();
        assert_eq!(node.active_capability(), None);
    }

    /// A stub mimicking `CapabilityTaskNode`/`SetCapabilityTargetNode`'s (instance-track
    /// configuration) Failure-when-idle/Running-when-engaged convergence, controllable via a
    /// shared flag - zero `Context`/messaging dependency, same style as `DummyBehavior` above.
    #[derive(Debug)]
    struct ToggleableBehavior {
        engaged: std::sync::Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait]
    impl BehaviorNode for ToggleableBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            Ok(if self.engaged.load(std::sync::atomic::Ordering::SeqCst) {
                NodeStatus::Running
            } else {
                NodeStatus::Failure
            })
        }
    }

    /// Simulates one leg of `patrol`'s timed-move sequence: `Running` for a fixed number
    /// of ticks, then `Success`. Records how many times it was ticked, so the test can observe
    /// whether a frozen `SequenceNode` child is skipped while a higher-priority layer is engaged.
    #[derive(Debug)]
    struct CountedLegBehavior {
        running_ticks_remaining: usize,
        tick_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    }

    #[async_trait]
    impl BehaviorNode for CountedLegBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            self.tick_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if self.running_ticks_remaining == 0 {
                Ok(NodeStatus::Success)
            } else {
                self.running_ticks_remaining -= 1;
                Ok(NodeStatus::Running)
            }
        }
    }

    /// The property that matters most: a `Subsumption` tree with a `Watch`-wrapped interrupt layer
    /// must let the interrupt freeze the main layer mid-sequence, then hand control back on the
    /// *same* tick it disengages, resuming exactly where it was.
    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn subsumption_preserves_lower_layer_progress_across_an_interrupt() {
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
        use std::sync::Arc;

        let ctx = crate::test_helpers::create_test_context("subsumption_resume").await;

        let engaged = Arc::new(AtomicBool::new(false));
        let leg1_ticks = Arc::new(AtomicUsize::new(0));
        let leg2_ticks = Arc::new(AtomicUsize::new(0));

        let watch = WatchNode::new(
            vec![Box::new(ToggleableBehavior {
                engaged: engaged.clone(),
            })],
            ParallelPolicy::RequireOne,
        );

        let sequence = SequenceNode::new(vec![
            Box::new(CountedLegBehavior {
                running_ticks_remaining: 2,
                tick_count: leg1_ticks.clone(),
            }),
            Box::new(CountedLegBehavior {
                running_ticks_remaining: 2,
                tick_count: leg2_ticks.clone(),
            }),
        ]);

        let mut subsumption = SubsumptionNode::new()
            .add_layer(100, Box::new(watch))
            .add_layer(0, Box::new(sequence));

        assert_eq!(subsumption.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(leg1_ticks.load(Ordering::SeqCst), 1);
        assert_eq!(subsumption.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(leg1_ticks.load(Ordering::SeqCst), 2);

        assert_eq!(subsumption.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(leg1_ticks.load(Ordering::SeqCst), 3);
        assert_eq!(leg2_ticks.load(Ordering::SeqCst), 1);

        engaged.store(true, Ordering::SeqCst);
        for _ in 0..3 {
            assert_eq!(
                subsumption.tick(&ctx).await.unwrap(),
                NodeStatus::Running,
                "the instance_track layer wins while engaged"
            );
        }
        assert_eq!(
            leg2_ticks.load(Ordering::SeqCst),
            1,
            "the main layer must be frozen (not reset, not advanced) while the interrupt layer is engaged"
        );

        engaged.store(false, Ordering::SeqCst);
        let status = subsumption.tick(&ctx).await.unwrap();
        assert_eq!(
            status,
            NodeStatus::Running,
            "handback must surface the Sequence's own status, not Success/Failure from the ceding interrupt layer"
        );
        assert_eq!(
            leg1_ticks.load(Ordering::SeqCst),
            3,
            "leg1 must not be re-ticked - the sequence was not reset"
        );
        assert_eq!(
            leg2_ticks.load(Ordering::SeqCst),
            2,
            "the Sequence resumes ticking leg2 (not leg1) - progress was preserved, not reset"
        );
    }

    /// The full 3-layer safety stack `find_target`/`patrol` wire up: a priority-255
    /// `emergency-stop-interrupt` layer above a priority-100 `instance-track-interrupt` layer
    /// above the priority-0 main layer. Proves the e-stop layer wins over BOTH lower layers
    /// (even while instance_track is itself engaged), freezes the main layer's progress while
    /// active, and on clearing hands control back exactly where it left off - the same
    /// resume-exactly-where-it-was property `subsumption_preserves_lower_layer_progress_across_an_interrupt`
    /// proves for a single interrupt layer, extended to prove the higher-priority layer also
    /// preempts an already-engaged lower-priority interrupt layer, not just the main layer.
    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn emergency_stop_layer_preempts_both_instance_track_and_the_main_layer_and_resumes_on_clear() {
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
        use std::sync::Arc;

        let ctx = crate::test_helpers::create_test_context("subsumption_estop_resume").await;

        let estop_active = Arc::new(AtomicBool::new(false));
        let instance_track_engaged = Arc::new(AtomicBool::new(false));
        let leg1_ticks = Arc::new(AtomicUsize::new(0));
        let leg2_ticks = Arc::new(AtomicUsize::new(0));

        let estop_watch = WatchNode::new(
            vec![Box::new(ToggleableBehavior {
                engaged: estop_active.clone(),
            })],
            ParallelPolicy::RequireOne,
        );

        let instance_track_watch = WatchNode::new(
            vec![Box::new(ToggleableBehavior {
                engaged: instance_track_engaged.clone(),
            })],
            ParallelPolicy::RequireOne,
        );

        let main_sequence = SequenceNode::new(vec![
            Box::new(CountedLegBehavior {
                running_ticks_remaining: 2,
                tick_count: leg1_ticks.clone(),
            }),
            Box::new(CountedLegBehavior {
                running_ticks_remaining: 2,
                tick_count: leg2_ticks.clone(),
            }),
        ]);

        let mut subsumption = SubsumptionNode::new()
            .add_layer(255, Box::new(estop_watch))
            .add_layer(100, Box::new(instance_track_watch))
            .add_layer(0, Box::new(main_sequence));

        // Main layer makes progress while nothing is interrupting.
        assert_eq!(subsumption.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(leg1_ticks.load(Ordering::SeqCst), 1);

        // instance_track engages and wins over the main layer, as in the 2-layer case.
        instance_track_engaged.store(true, Ordering::SeqCst);
        assert_eq!(subsumption.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(
            leg1_ticks.load(Ordering::SeqCst),
            1,
            "main layer frozen while instance_track is engaged"
        );

        // Now e-stop fires WHILE instance_track is still engaged - priority 255 must win over
        // BOTH lower layers, not just the main one.
        estop_active.store(true, Ordering::SeqCst);
        for _ in 0..3 {
            assert_eq!(
                subsumption.tick(&ctx).await.unwrap(),
                NodeStatus::Running,
                "the emergency-stop layer must win even over an already-engaged instance_track layer"
            );
        }
        assert_eq!(
            leg1_ticks.load(Ordering::SeqCst),
            1,
            "main layer must stay frozen while e-stop is active"
        );

        // instance_track clears while e-stop is still active - e-stop must keep winning.
        instance_track_engaged.store(false, Ordering::SeqCst);
        assert_eq!(
            subsumption.tick(&ctx).await.unwrap(),
            NodeStatus::Running,
            "e-stop still active, so it keeps control even after instance_track clears"
        );
        assert_eq!(leg1_ticks.load(Ordering::SeqCst), 1, "main layer still frozen");

        // e-stop clears - control hands back to the main layer, resuming (not restarting) leg1.
        estop_active.store(false, Ordering::SeqCst);
        let status = subsumption.tick(&ctx).await.unwrap();
        assert_eq!(
            status,
            NodeStatus::Running,
            "handback surfaces the Sequence's own status once e-stop clears"
        );
        assert_eq!(
            leg1_ticks.load(Ordering::SeqCst),
            2,
            "leg1 resumes from where it left off (1 prior tick), not reset to 0"
        );
        assert_eq!(leg2_ticks.load(Ordering::SeqCst), 0, "leg2 not yet reached");
    }

    #[derive(Debug)]
    struct FixedStatusBehavior(NodeStatus);

    #[async_trait]
    impl BehaviorNode for FixedStatusBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            Ok(self.0)
        }
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn inverter_flips_success_and_failure_but_passes_running_through() {
        let ctx = crate::test_helpers::create_test_context("inverter").await;

        let mut success = InverterNode::new(Box::new(FixedStatusBehavior(NodeStatus::Success)));
        assert_eq!(success.tick(&ctx).await.unwrap(), NodeStatus::Failure);

        let mut failure = InverterNode::new(Box::new(FixedStatusBehavior(NodeStatus::Failure)));
        assert_eq!(failure.tick(&ctx).await.unwrap(), NodeStatus::Success);

        let mut running = InverterNode::new(Box::new(FixedStatusBehavior(NodeStatus::Running)));
        assert_eq!(running.tick(&ctx).await.unwrap(), NodeStatus::Running);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn force_success_reports_success_even_when_child_fails() {
        let ctx = crate::test_helpers::create_test_context("force_success").await;

        let mut node = ForceSuccessNode::new(Box::new(FixedStatusBehavior(NodeStatus::Failure)));
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);

        let mut running = ForceSuccessNode::new(Box::new(FixedStatusBehavior(NodeStatus::Running)));
        assert_eq!(running.tick(&ctx).await.unwrap(), NodeStatus::Running);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn force_failure_reports_failure_even_when_child_succeeds() {
        let ctx = crate::test_helpers::create_test_context("force_failure").await;

        let mut node = ForceFailureNode::new(Box::new(FixedStatusBehavior(NodeStatus::Success)));
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);

        let mut running = ForceFailureNode::new(Box::new(FixedStatusBehavior(NodeStatus::Running)));
        assert_eq!(running.tick(&ctx).await.unwrap(), NodeStatus::Running);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn repeat_with_count_succeeds_after_n_successful_runs() {
        let ctx = crate::test_helpers::create_test_context("repeat_count").await;

        let mut node = RepeatNode::new(Box::new(FixedStatusBehavior(NodeStatus::Success)), Some(3));
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn repeat_stops_immediately_on_child_failure() {
        let ctx = crate::test_helpers::create_test_context("repeat_failure").await;

        let mut node = RepeatNode::new(Box::new(FixedStatusBehavior(NodeStatus::Failure)), None);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn retry_succeeds_once_an_attempt_within_the_budget_succeeds() {
        let ctx = crate::test_helpers::create_test_context("retry_succeeds").await;

        let mut node = RetryNode::new(
            Box::new(SequencedStatusBehavior::new(vec![
                NodeStatus::Failure,
                NodeStatus::Failure,
                NodeStatus::Success,
            ])),
            3,
        );
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn retry_fails_once_every_attempt_is_exhausted() {
        let ctx = crate::test_helpers::create_test_context("retry_exhausted").await;

        let mut node = RetryNode::new(Box::new(FixedStatusBehavior(NodeStatus::Failure)), 2);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn timeout_passes_through_a_child_that_resolves_before_the_deadline() {
        let ctx = crate::test_helpers::create_test_context("timeout_resolves").await;

        let mut node = TimeoutNode::new(
            Box::new(FixedStatusBehavior(NodeStatus::Success)),
            Duration::from_secs(60),
        );
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn timeout_fails_once_the_child_has_been_running_too_long() {
        let ctx = crate::test_helpers::create_test_context("timeout_expires").await;

        let mut node = TimeoutNode::new(Box::new(FixedStatusBehavior(NodeStatus::Running)), Duration::ZERO);
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);
    }

    // `controller_mode()` reads process-global env vars; serialize tests that touch them so they
    // can't observe each other's in-flight state - mirrors `actions/movement.rs`'s own
    // `CONTROLLER_ENV_LOCK` convention (a separate lock, since statics aren't shared across
    // modules, but guarding the same underlying env vars).
    //
    // This needs to be a `tokio::sync::Mutex`, not `std::sync::Mutex`: the async tests below
    // hold the guard across `.await` points (by design - other tests' env var mutations must
    // stay locked out for the whole test body, not just up to the first await), and holding a
    // non-async-aware guard across an await is a hard compile error (`clippy::await_holding_lock`
    // promoted to deny under this workspace's lint config).
    static CONTROLLER_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

    fn clear_controller_env() {
        std::env::remove_var(mecha10_core::config::CAPABILITIES_ENV_VAR);
        std::env::remove_var(mecha10_core::config::ACTUATION_JOINT_NAMES_ENV_VAR);
    }

    #[test]
    fn controller_mode_is_evaluates_against_the_current_controller_mode() {
        let _guard = CONTROLLER_ENV_LOCK.blocking_lock();
        clear_controller_env();

        // No capability env set => the project falls back to Locomotion (see
        // `mecha10_core::config::controller_mode`).
        assert!(ConditionKind::ControllerModeIs(ControllerModeKind::Locomotion).evaluate());
        assert!(!ConditionKind::ControllerModeIs(ControllerModeKind::Joints).evaluate());

        std::env::set_var(mecha10_core::config::CAPABILITIES_ENV_VAR, r#"["joints"]"#);
        assert!(ConditionKind::ControllerModeIs(ControllerModeKind::Joints).evaluate());
        assert!(!ConditionKind::ControllerModeIs(ControllerModeKind::Locomotion).evaluate());

        clear_controller_env();
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn condition_ticks_child_and_forwards_its_status_when_the_predicate_holds() {
        let _guard = CONTROLLER_ENV_LOCK.lock().await;
        clear_controller_env(); // => Locomotion

        let ctx = crate::test_helpers::create_test_context("condition_true").await;
        let mut node = ConditionNode::new(
            ConditionKind::ControllerModeIs(ControllerModeKind::Locomotion),
            Box::new(FixedStatusBehavior(NodeStatus::Running)),
        );

        assert_eq!(
            node.tick(&ctx).await.unwrap(),
            NodeStatus::Running,
            "a true predicate must tick the child and forward its status unchanged"
        );

        clear_controller_env();
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn condition_returns_failure_without_ticking_child_when_the_predicate_is_false() {
        let _guard = CONTROLLER_ENV_LOCK.lock().await;
        clear_controller_env();
        std::env::set_var(mecha10_core::config::CAPABILITIES_ENV_VAR, r#"["joints"]"#);

        let ctx = crate::test_helpers::create_test_context("condition_false").await;
        // `DummyBehavior::tick` is `unimplemented!()`, so the test would panic if the child were
        // ticked - proving a false predicate short-circuits to Failure without touching it.
        let mut node = ConditionNode::new(
            ConditionKind::ControllerModeIs(ControllerModeKind::Locomotion),
            Box::new(DummyBehavior),
        );

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Failure);

        clear_controller_env();
    }

    #[test]
    fn condition_children_mut_exposes_the_child() {
        let mut node = ConditionNode::new(
            ConditionKind::ControllerModeIs(ControllerModeKind::Joints),
            Box::new(DummyBehavior),
        );
        assert_eq!(node.children_mut().len(), 1);
    }

    #[test]
    fn condition_forwards_its_childs_active_capability() {
        let node = ConditionNode::new(
            ConditionKind::ControllerModeIs(ControllerModeKind::Locomotion),
            Box::new(CapabilityBehavior("sweep")),
        );
        assert_eq!(node.active_capability(), Some("sweep"));
    }

    #[test]
    fn weighted_select_children_mut_exposes_every_child() {
        let mut node = WeightedSelectNode::new(vec![
            (1.0, Box::new(DummyBehavior) as BoxedBehavior),
            (1.0, Box::new(DummyBehavior) as BoxedBehavior),
        ]);
        assert_eq!(node.children_mut().len(), 2);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn weighted_select_never_picks_a_zero_weight_child() {
        let ctx = crate::test_helpers::create_test_context("weighted_select_zero_weight").await;

        // `DummyBehavior::tick` is `unimplemented!()`, so the test would panic if the zero-weight
        // child were ever ticked - proving it's never picked, over a resolution cycle that visits
        // every *eligible* child.
        let mut node = WeightedSelectNode::with_rng(
            vec![
                (1.0, Box::new(FixedStatusBehavior(NodeStatus::Failure)) as BoxedBehavior),
                (0.0, Box::new(DummyBehavior) as BoxedBehavior),
            ],
            StdRng::seed_from_u64(42),
        );

        assert_eq!(
            node.tick(&ctx).await.unwrap(),
            NodeStatus::Failure,
            "the only eligible (positive-weight) child fails, and the zero-weight one must not be tried"
        );
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn weighted_select_does_not_reroll_away_from_a_running_child() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let ctx = crate::test_helpers::create_test_context("weighted_select_sticky").await;

        let leg_a_ticks = Arc::new(AtomicUsize::new(0));
        let leg_b_ticks = Arc::new(AtomicUsize::new(0));

        let mut node = WeightedSelectNode::with_rng(
            vec![
                (
                    1.0,
                    Box::new(CountedLegBehavior {
                        running_ticks_remaining: 1,
                        tick_count: leg_a_ticks.clone(),
                    }) as BoxedBehavior,
                ),
                (
                    1.0,
                    Box::new(CountedLegBehavior {
                        running_ticks_remaining: 1,
                        tick_count: leg_b_ticks.clone(),
                    }) as BoxedBehavior,
                ),
            ],
            StdRng::seed_from_u64(7),
        );

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        let a_after_first = leg_a_ticks.load(Ordering::SeqCst);
        let b_after_first = leg_b_ticks.load(Ordering::SeqCst);
        assert_eq!(
            a_after_first + b_after_first,
            1,
            "exactly one child should have been ticked"
        );

        // Whichever child was chosen (and is now Running) must be re-ticked next call, not
        // re-rolled to the other one.
        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);
        assert_eq!(
            leg_a_ticks.load(Ordering::SeqCst) + leg_b_ticks.load(Ordering::SeqCst),
            2,
            "the same child that was Running must be re-ticked (reaching 2 ticks), not the other \
             one (which must remain untouched at 0)"
        );
        assert!(
            leg_a_ticks.load(Ordering::SeqCst) == 0 || leg_b_ticks.load(Ordering::SeqCst) == 0,
            "the child that was never chosen must never be ticked at all"
        );
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn weighted_select_forwards_the_current_childs_active_capability() {
        let ctx = crate::test_helpers::create_test_context("weighted_select_capability").await;

        let mut node = WeightedSelectNode::with_rng(
            vec![(
                1.0,
                Box::new(StatusAndCapabilityBehavior {
                    status: NodeStatus::Running,
                    capability: "patrol",
                }) as BoxedBehavior,
            )],
            StdRng::seed_from_u64(1),
        );

        assert_eq!(node.active_capability(), None, "no tick has happened yet");

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(node.active_capability(), Some("patrol"));
    }

    #[tokio::test]
    async fn weighted_select_reset_clears_current_index_and_tried() {
        let mut node = WeightedSelectNode::with_rng(
            vec![
                (1.0, Box::new(DummyBehavior) as BoxedBehavior),
                (1.0, Box::new(DummyBehavior) as BoxedBehavior),
            ],
            StdRng::seed_from_u64(3),
        );
        node.current_index = Some(1);
        node.tried[0] = true;

        node.reset().await.unwrap();

        assert_eq!(node.current_index, None);
        assert!(node.tried.iter().all(|t| !t));
    }

    #[derive(Debug)]
    struct CountingFixedStatusBehavior {
        status: NodeStatus,
        tick_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    }

    #[async_trait]
    impl BehaviorNode for CountingFixedStatusBehavior {
        async fn tick(&mut self, _ctx: &Context) -> anyhow::Result<NodeStatus> {
            self.tick_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(self.status)
        }
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn cooldown_blocks_reentry_immediately_after_a_terminal_result() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let ctx = crate::test_helpers::create_test_context("cooldown_blocks").await;

        let tick_count = Arc::new(AtomicUsize::new(0));
        let mut node = CooldownNode::new(
            Box::new(CountingFixedStatusBehavior {
                status: NodeStatus::Success,
                tick_count: tick_count.clone(),
            }),
            Duration::from_secs(60),
        );

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);
        assert_eq!(tick_count.load(Ordering::SeqCst), 1);

        assert_eq!(
            node.tick(&ctx).await.unwrap(),
            NodeStatus::Failure,
            "within the cooldown window, the node must fail without ticking the child"
        );
        assert_eq!(
            tick_count.load(Ordering::SeqCst),
            1,
            "the child must not have been ticked again while cooling down"
        );
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn cooldown_expires_and_ticking_resumes() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let ctx = crate::test_helpers::create_test_context("cooldown_expires").await;

        let tick_count = Arc::new(AtomicUsize::new(0));
        let mut node = CooldownNode::new(
            Box::new(CountingFixedStatusBehavior {
                status: NodeStatus::Success,
                tick_count: tick_count.clone(),
            }),
            Duration::ZERO,
        );

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Success);
        assert_eq!(tick_count.load(Ordering::SeqCst), 1);

        // A zero-length cooldown has already elapsed by the time the next tick() call checks it.
        assert_eq!(
            node.tick(&ctx).await.unwrap(),
            NodeStatus::Success,
            "once the cooldown window elapses, ticking must resume normally"
        );
        assert_eq!(tick_count.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    #[ignore = "Requires Redis infrastructure"]
    async fn cooldown_does_not_start_while_the_child_is_running() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let ctx = crate::test_helpers::create_test_context("cooldown_running").await;

        let tick_count = Arc::new(AtomicUsize::new(0));
        let mut node = CooldownNode::new(
            Box::new(CountingFixedStatusBehavior {
                status: NodeStatus::Running,
                tick_count: tick_count.clone(),
            }),
            Duration::from_secs(60),
        );

        assert_eq!(node.tick(&ctx).await.unwrap(), NodeStatus::Running);
        assert_eq!(tick_count.load(Ordering::SeqCst), 1);

        assert_eq!(
            node.tick(&ctx).await.unwrap(),
            NodeStatus::Running,
            "Running must not start the cooldown clock, so the child must be ticked again"
        );
        assert_eq!(tick_count.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn cooldown_children_mut_exposes_the_child() {
        let mut node = CooldownNode::new(Box::new(DummyBehavior), Duration::from_secs(1));
        assert_eq!(node.children_mut().len(), 1);
    }

    #[test]
    fn cooldown_forwards_its_childs_active_capability() {
        let node = CooldownNode::new(Box::new(CapabilityBehavior("sweep")), Duration::from_secs(1));
        assert_eq!(node.active_capability(), Some("sweep"));
    }

    #[test]
    fn cooldown_reset_clears_cooldown_until() {
        let mut node = CooldownNode::new(Box::new(DummyBehavior), Duration::from_secs(1));
        node.cooldown_until = Some(Instant::now() + Duration::from_secs(60));

        node.reset_self();

        assert_eq!(node.cooldown_until, None);
    }
}