leviath-cli 0.3.8

Command-line interface for Leviath agent framework
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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
//! `lev test` - Run agent tests

use clap::Args;
use leviath_providers::InferenceRequest;
use leviath_runtime::{ContextWindow, ProviderRegistry, context_setup};
use serde::Deserialize;
use std::fs;
use std::path::Path;
use std::sync::Arc;

use crate::config::Config;
use leviath_core::manifest::parse_manifest;
use leviath_core::truncate_at_boundary;

/// Arguments for `lev test`.
#[derive(Args)]
pub struct TestArgs {
    /// Path to agent project
    #[arg(value_name = "PATH")]
    pub path: Option<String>,

    /// Test filter pattern
    #[arg(short, long)]
    pub filter: Option<String>,

    /// Validate test structure without running agents (no API calls)
    #[arg(long)]
    pub dry_run: bool,
}

/// A test case loaded from a TOML test file.
#[derive(Debug, Deserialize)]
struct TestCase {
    name: String,
    input: String,
    #[serde(default)]
    expect_contains: Option<String>,
    #[serde(default)]
    expect_tool_call: Option<String>,
    #[serde(default)]
    max_tokens: Option<usize>,
}

#[derive(Debug, Deserialize)]
struct TestFile {
    test: Vec<TestCase>,
}

/// Run `lev test`: drive a blueprint's declared test cases.
pub async fn execute(args: TestArgs) -> anyhow::Result<()> {
    execute_with_registry(args, Box::new(build_registry_from_config)).await
}

/// Builds the real provider registry from a loaded [`Config`] - the
/// production `build_registry` passed to [`execute_with_registry`] by
/// [`execute`].
fn build_registry_from_config(
    config: &Config,
) -> Result<ProviderRegistry, leviath_providers::ProviderError> {
    build_registry_from_config_with(config, &leviath_providers::provider::build_http_client)
}

/// [`build_registry_from_config`], with client construction injected so the
/// failure path is reachable from a test.
fn build_registry_from_config_with(
    config: &Config,
    build_client: leviath_providers::provider::HttpClientFactory<'_>,
) -> Result<ProviderRegistry, leviath_providers::ProviderError> {
    let mut reg = ProviderRegistry::new();
    // `lev test` uses one client for every provider it registers: the command
    // has no per-provider timeout to honour, so there is nothing to key on.
    let client = build_client(None)
        .map_err(|e| leviath_providers::ProviderError::ClientBuild(e.to_string()))?;

    if let Some(ref key) = config.providers.anthropic_api_key {
        reg.register(
            "anthropic".to_string(),
            Arc::new(leviath_providers::AnthropicProvider::new(
                client.clone(),
                key.clone(),
            )),
        );
    }
    if let Some(ref key) = config.providers.openai_api_key {
        reg.register(
            "openai".to_string(),
            Arc::new(leviath_providers::OpenAIProvider::new(
                client.clone(),
                key.clone(),
            )),
        );
    }
    if let Some(ref key) = config.providers.google_api_key {
        reg.register(
            "google".to_string(),
            Arc::new(leviath_providers::GeminiProvider::new(
                client.clone(),
                key.clone(),
            )),
        );
    }
    if let Some(ref key) = config.openrouter_api_key {
        reg.register(
            "openrouter".to_string(),
            Arc::new(leviath_providers::OpenRouterProvider::new(
                client.clone(),
                key.clone(),
            )),
        );
    }
    let ollama_url = config
        .ollama_base_url
        .as_deref()
        .unwrap_or("http://localhost:11434");
    reg.register(
        "ollama".to_string(),
        Arc::new(leviath_providers::OllamaProvider::with_base_url(
            client.clone(),
            ollama_url.to_string(),
        )),
    );

    Ok(reg)
}

/// How `lev test` gets its provider registry.
///
/// Fallible because constructing a provider's outbound HTTPS client reads the
/// machine's root certificate store and can fail; boxed for the
/// monomorphization reason spelled out on [`execute_with_registry`].
type RegistryBuilder =
    Box<dyn FnOnce(&Config) -> Result<ProviderRegistry, leviath_providers::ProviderError>>;

/// Core of [`execute`], with provider-registry construction injected so
/// tests can drive the non-dry-run path with a mock [`Provider`] instead of
/// either skipping it (dry-run only) or making a real, billed network call
/// through whatever the developer's real `~/.leviath/config.toml` happens to
/// contain.
///
/// `build_registry` is a boxed trait object ([`RegistryBuilder`]) rather than an
/// `impl FnOnce` bound so every caller - production's `build_registry_from_config` and every
/// test's distinct `mock_registry_builder(...)` closure - shares exactly
/// ONE monomorphization of this (large, many-branch) function instead of
/// one per closure type. This was a confirmed generic-monomorphization
/// coverage-attribution artifact: every source position had a covered
/// instantiation (confirmed via HTML/JSON segment inspection showing no
/// red/uncovered regions anywhere in this function), but the summary table
/// still reported 32 regions / 21 lines missed - the largest such residual
/// in this crate.
async fn execute_with_registry(
    args: TestArgs,
    build_registry: RegistryBuilder,
) -> anyhow::Result<()> {
    let path = args.path.unwrap_or_else(|| ".".to_string());
    tracing::info!(path = %path, "Running agent tests");

    let project_path = Path::new(&path);

    // Verify agent.leviath exists
    let manifest_path = project_path.join("agent.leviath");
    if !manifest_path.exists() {
        anyhow::bail!(
            "No agent.leviath found in '{}'. Not an agent project.",
            project_path.display()
        );
    }

    let tests_dir = project_path.join("tests");
    if !tests_dir.exists() {
        println!("No tests directory found. Create tests/ with .toml or .rhai files.");
        println!("\nExample test file (tests/basic.toml):");
        println!("  [[test]]");
        println!("  name = \"basic_response\"");
        println!("  input = \"Hello\"");
        println!("  expect_contains = \"hello\"");
        // The other two keys are deliberately not spelled out here: a second
        // partial example is a second thing to drift. `expect_tool_call` and
        // `max_tokens` were each parsed and ignored for months, which is what
        // an undocumented format buys.
        println!("\nAlso available: expect_tool_call, max_tokens.");
        println!("See https://leviath.dev/docs/cli#lev-test-path for what each does.");
        return Ok(());
    }

    if args.dry_run {
        println!("Dry run mode: validating test structure only (no API calls)\n");
    }

    // Parse blueprint and set up providers (only if not dry_run)
    let manifest_content = fs::read_to_string(&manifest_path)?;
    let blueprint = parse_manifest(&manifest_content)?;

    // Custom regions' Rhai scripts, resolved exactly as a real spawn would
    // (blueprint-dir-relative, compile-checked, hard error) - `lev test` is
    // precisely the preview loop where a hook author wants the hook to run.
    let region_scripts =
        crate::daemon::spawn::resolve_region_scripts(&blueprint, &manifest_path.to_string_lossy())
            .map_err(|e| anyhow::anyhow!(e))?;

    let registry = if !args.dry_run {
        let config = Config::load()?;
        Some(build_registry(&config)?)
    } else {
        None
    };

    let mut total = 0;
    let mut passed = 0;
    let mut failed = 0;
    let mut failures: Vec<String> = Vec::new();

    // Run .toml test files and .rhai test scripts (single directory scan)
    for entry in fs::read_dir(&tests_dir)?.flatten() {
        let test_path = entry.path();

        if test_path.extension().and_then(|e| e.to_str()) == Some("toml") {
            let file_name = test_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("unknown");

            println!("Running test file: {}", file_name);

            let content = fs::read_to_string(&test_path)?;
            let test_file: TestFile = toml::from_str(&content)
                .map_err(|e| anyhow::anyhow!("Failed to parse test file '{}': {}", file_name, e))?;

            for test_case in &test_file.test {
                // Apply filter if provided
                if let Some(ref filter) = args.filter
                    && !test_case.name.contains(filter.as_str())
                {
                    continue;
                }

                total += 1;

                if args.dry_run {
                    // Dry-run: validate structure only
                    let test_valid = validate_test_case(test_case);
                    if test_valid {
                        passed += 1;
                        println!("  PASS (dry-run): {}", test_case.name);
                    } else {
                        failed += 1;
                        let msg = format!("{}: test case validation failed", test_case.name);
                        println!("  FAIL (dry-run): {}", msg);
                        failures.push(msg);
                    }
                } else {
                    // Real run: execute inference and check assertions
                    let registry = registry
                        .as_ref()
                        .expect("registry should exist in non-dry-run");
                    match run_test_case(&blueprint, registry, test_case, &region_scripts).await {
                        Ok(true) => {
                            passed += 1;
                            println!("  PASS: {}", test_case.name);
                        }
                        Ok(false) => {
                            failed += 1;
                            let msg = format!("{}: assertions failed", test_case.name);
                            println!("  FAIL: {}", msg);
                            failures.push(msg);
                        }
                        Err(e) => {
                            failed += 1;
                            let msg = format!("{}: {}", test_case.name, e);
                            println!("  FAIL: {}", msg);
                            failures.push(msg);
                        }
                    }
                }
            }
        } else if test_path.extension().and_then(|e| e.to_str()) == Some("rhai") {
            let file_name = test_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("unknown");

            // Apply filter if provided
            if let Some(ref filter) = args.filter
                && !file_name.contains(filter.as_str())
            {
                continue;
            }

            total += 1;
            println!("Running script: {}", file_name);

            let script = fs::read_to_string(&test_path)?;
            let engine = leviath_scripting::ScriptEngine::new();
            let mut scope = rhai::Scope::new();

            match engine.execute(&script, &mut scope) {
                Ok(result) => {
                    if let Ok(success) = result.as_bool() {
                        if success {
                            passed += 1;
                            println!("  PASS: {}", file_name);
                        } else {
                            failed += 1;
                            let msg = format!("{}: script returned false", file_name);
                            println!("  FAIL: {}", msg);
                            failures.push(msg);
                        }
                    } else {
                        passed += 1;
                        println!("  PASS: {} (returned: {})", file_name, result);
                    }
                }
                Err(e) => {
                    failed += 1;
                    let msg = format!("{}: {}", file_name, e);
                    println!("  FAIL: {}", msg);
                    failures.push(msg);
                }
            }
        }
    }

    // Report results
    println!("\n--- Results ---");
    println!("{} passed, {} failed, {} total", passed, failed, total);

    if !failures.is_empty() {
        println!("\nFailures:");
        for f in &failures {
            println!("  - {}", f);
        }
        anyhow::bail!("{} test(s) failed", failed);
    }

    if total == 0 {
        println!("No test files found in tests/ directory.");
    }

    Ok(())
}

/// How many output tokens one case may ask for.
///
/// A case's `max_tokens` narrows `ceiling` and never widens it: it is there to
/// keep one test cheap, not to let a test ask for more than the context window
/// or the model allows. A free function rather than an inline `map_or` so the
/// rule is exercised without reaching a provider.
fn resolved_max_tokens(case_cap: Option<usize>, ceiling: usize) -> usize {
    match case_cap {
        Some(cap) => cap.min(ceiling),
        None => ceiling,
    }
}

/// The tools a stage advertises, as the provider wants them.
///
/// `lev test` drives one inference, so this is the same set the first turn of a
/// real run would see - which is what makes `expect_tool_call` mean the same
/// thing here as it does in production.
fn stage_tools(stage: &leviath_core::Stage) -> Vec<leviath_providers::Tool> {
    // Built over a throwaway workdir: `lev test` never executes a tool, it only
    // needs the definitions so the model can choose to call one.
    let builtins =
        leviath_tools::BuiltinTools::new(leviath_tools::ToolContext::new(std::env::temp_dir()));
    let mut defs = builtins.tool_defs();
    defs.extend(leviath_tools::BuiltinTools::subagent_tool_defs());
    stage
        .available_tools
        .iter()
        .filter_map(|name| defs.iter().find(|d| d.name == *name).cloned())
        .collect()
}

/// Run a single test case: build a one-off context window from the blueprint,
/// run one inference against the resolved provider, and check the assertions.
async fn run_test_case(
    blueprint: &leviath_core::Blueprint,
    registry: &ProviderRegistry,
    test: &TestCase,
    region_scripts: &std::collections::HashMap<
        String,
        std::sync::Arc<leviath_scripting::region_hook::RegionScript>,
    >,
) -> anyhow::Result<bool> {
    // Model config comes from the first stage.
    let stage = blueprint
        .stages
        .first()
        .ok_or(anyhow::anyhow!("Blueprint has no stages"))?;
    let provider_name = stage.model.provider();
    let model_name = stage.model.model();

    let provider = registry.get(provider_name).ok_or_else(|| {
        anyhow::anyhow!(
            "Provider '{}' is not configured. Set API key in ~/.leviath/config.toml",
            provider_name
        )
    })?;

    // Build a standalone context window from the blueprint's layout, seeding the
    // test input as the task, then assemble a single inference request. This
    // mirrors what the ECS pipeline's spawner does, without the shared world:
    // `lev test` only needs one inference to validate a stage's first response.
    let mut window = ContextWindow::new(blueprint.context_layout.total_budget_tokens);
    window.region_scripts = region_scripts.clone();
    context_setup::init_window(&mut window, blueprint, &test.input);

    // Assemble with real stage metadata so custom-region render hooks see
    // what a live run's first inference would (iteration 0).
    let assembled = window.assemble_with_meta(&leviath_runtime::custom_region::AssembleMeta {
        stage_name: stage.name.clone(),
        stage_iterations: 0,
        model: model_name.to_string(),
    });
    let caps = provider.capabilities(model_name);
    let remaining = window.max_tokens.saturating_sub(window.current_tokens);
    // A case's `max_tokens` narrows the ceiling and never widens it: it is there
    // to keep one test cheap, not to let a test ask for more than the window or
    // the model allows.
    let max_tokens = resolved_max_tokens(test.max_tokens, remaining.min(caps.max_output_tokens));
    let temperature = if caps.supports_temperature { 0.7 } else { 0.0 };
    let request = InferenceRequest {
        system: assembled.system_blocks,
        messages: assembled.messages,
        model: model_name.to_string(),
        max_tokens,
        temperature,
        // The stage's own tools, so a case can assert on a tool call at all.
        // Advertising none was the prior behaviour and made `expect_tool_call`
        // unsatisfiable: the model cannot call a tool it was never offered, so
        // every such assertion failed whatever the agent did.
        tools: stage_tools(stage),
        extra: serde_json::Value::Null,
        request_timeout_secs: None,
    };

    let response = provider
        .infer(&request)
        .await
        .map_err(|e| anyhow::anyhow!("Inference failed: {}", e))?;

    // Check assertions
    let mut all_passed = true;

    if let Some(ref expected) = test.expect_contains {
        let content_lower = response.content.to_lowercase();
        let expected_lower = expected.to_lowercase();
        if !content_lower.contains(&expected_lower) {
            println!(
                "    expect_contains failed: response does not contain '{}'",
                expected
            );
            println!("    response: {}", truncate_str(&response.content, 200));
            all_passed = false;
        }
    }

    if let Some(ref expected_tool) = test.expect_tool_call {
        let has_tool = response
            .tool_calls
            .iter()
            .any(|tc| tc.name == *expected_tool);
        if !has_tool {
            println!(
                "    expect_tool_call failed: no tool call to '{}'",
                expected_tool
            );
            let tool_names: Vec<&str> = response
                .tool_calls
                .iter()
                .map(|tc| tc.name.as_str())
                .collect();
            println!("    actual tool calls: {:?}", tool_names);
            all_passed = false;
        }
    }

    Ok(all_passed)
}

/// Validate a test case structure (checks that it's well-formed).
fn validate_test_case(test: &TestCase) -> bool {
    if test.name.is_empty() {
        return false;
    }
    if test.input.is_empty() {
        return false;
    }
    // Must have at least one assertion
    if test.expect_contains.is_none() && test.expect_tool_call.is_none() {
        return false;
    }
    true
}

/// Shorten a model response for the assertion-failure preview.
///
/// Cuts on a char boundary: this runs on raw model output, and a byte cut-off
/// through an emoji once panicked `lev test` outright.
fn truncate_str(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("{}...", truncate_at_boundary(s, max))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{with_tracing, write_test_agent};

    // ─── validate_test_case ────────────────────────────────────────────────

    #[test]
    fn validate_test_case_valid_with_expect_contains() {
        let tc = TestCase {
            name: "basic".to_string(),
            input: "hello".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(validate_test_case(&tc));
    }

    #[test]
    fn validate_test_case_valid_with_expect_tool_call() {
        let tc = TestCase {
            name: "tool_test".to_string(),
            input: "do something".to_string(),
            expect_contains: None,
            expect_tool_call: Some("bash".to_string()),
            max_tokens: None,
        };
        assert!(validate_test_case(&tc));
    }

    #[test]
    fn validate_test_case_valid_with_both_assertions() {
        let tc = TestCase {
            name: "both".to_string(),
            input: "test".to_string(),
            expect_contains: Some("output".to_string()),
            expect_tool_call: Some("read_file".to_string()),
            max_tokens: Some(100),
        };
        assert!(validate_test_case(&tc));
    }

    #[test]
    fn validate_test_case_empty_name_fails() {
        let tc = TestCase {
            name: String::new(),
            input: "hello".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(!validate_test_case(&tc));
    }

    #[test]
    fn validate_test_case_empty_input_fails() {
        let tc = TestCase {
            name: "test".to_string(),
            input: String::new(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(!validate_test_case(&tc));
    }

    #[test]
    fn validate_test_case_no_assertions_fails() {
        let tc = TestCase {
            name: "test".to_string(),
            input: "hello".to_string(),
            expect_contains: None,
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(!validate_test_case(&tc));
    }

    // ─── truncate_str ──────────────────────────────────────────────────────

    #[test]
    fn truncate_str_short() {
        assert_eq!(truncate_str("hello", 10), "hello");
    }

    #[test]
    fn truncate_str_exact() {
        assert_eq!(truncate_str("hello", 5), "hello");
    }

    #[test]
    fn truncate_str_long() {
        assert_eq!(truncate_str("hello world", 5), "hello...");
    }

    #[test]
    fn truncate_str_empty() {
        assert_eq!(truncate_str("", 5), "");
    }

    // ─── TestFile TOML parsing ─────────────────────────────────────────────

    #[test]
    fn parse_test_file_toml() {
        let toml_content = r#"
[[test]]
name = "greeting"
input = "Say hello"
expect_contains = "hello"

[[test]]
name = "tool_use"
input = "Read file.txt"
expect_tool_call = "read_file"
max_tokens = 500
"#;
        let test_file: TestFile = toml::from_str(toml_content).unwrap();
        assert_eq!(test_file.test.len(), 2);
        assert_eq!(test_file.test[0].name, "greeting");
        assert_eq!(test_file.test[0].input, "Say hello");
        assert_eq!(test_file.test[0].expect_contains.as_deref(), Some("hello"));
        assert!(test_file.test[0].expect_tool_call.is_none());
        assert!(test_file.test[0].max_tokens.is_none());

        assert_eq!(test_file.test[1].name, "tool_use");
        assert_eq!(
            test_file.test[1].expect_tool_call.as_deref(),
            Some("read_file")
        );
        assert_eq!(test_file.test[1].max_tokens, Some(500));
    }

    /// A minimal model config, since `Stage::new` needs one and these tests
    /// never reach a provider.
    fn test_model() -> leviath_core::blueprint::ModelConfig {
        leviath_core::blueprint::ModelConfig::new("anthropic".to_string(), "m".to_string())
    }

    /// The bug these two fixes closed, pinned so it cannot reopen: both keys
    /// were parsed, asserted on *as parsed values*, and then ignored. A test
    /// that only checks deserialisation certifies nothing about behaviour.
    #[test]
    fn a_case_max_tokens_narrows_the_ceiling_and_never_widens_it() {
        let ceiling = 4_000;
        assert_eq!(
            resolved_max_tokens(Some(500), ceiling),
            500,
            "a smaller case cap wins"
        );
        assert_eq!(
            resolved_max_tokens(Some(99_000), ceiling),
            ceiling,
            "a case may not ask for more than the model allows"
        );
        assert_eq!(
            resolved_max_tokens(None, ceiling),
            ceiling,
            "no cap means the full ceiling"
        );
    }

    /// `expect_tool_call` was unsatisfiable: the request advertised no tools, so
    /// the model could never call one and every such assertion failed whatever
    /// the agent did.
    #[test]
    fn a_stage_advertises_its_tools_so_a_tool_call_is_possible() {
        let mut stage = leviath_core::Stage::new("s".to_string(), test_model());
        stage.available_tools = vec!["read_file".to_string(), "write_file".to_string()];
        let tools = stage_tools(&stage);
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
        assert!(names.contains(&"read_file"), "got {names:?}");
        assert!(names.contains(&"write_file"), "got {names:?}");
    }

    /// A stage that advertises nothing still sends nothing, so a plain
    /// text-assertion case is unchanged.
    #[test]
    fn a_stage_with_no_tools_advertises_none() {
        let stage = leviath_core::Stage::new("s".to_string(), test_model());
        assert!(stage_tools(&stage).is_empty());
    }

    /// A name the builtins do not know is dropped rather than sent as a tool the
    /// provider would reject.
    #[test]
    fn an_unknown_tool_name_is_not_advertised() {
        let mut stage = leviath_core::Stage::new("s".to_string(), test_model());
        stage.available_tools = vec!["definitely_not_a_tool".to_string()];
        assert!(stage_tools(&stage).is_empty());
    }

    #[test]
    fn parse_test_file_minimal() {
        let toml_content = r#"
[[test]]
name = "min"
input = "test"
expect_contains = "ok"
"#;
        let test_file: TestFile = toml::from_str(toml_content).unwrap();
        assert_eq!(test_file.test.len(), 1);
    }

    #[test]
    fn parse_test_file_invalid_toml_errors() {
        let result: Result<TestFile, _> = toml::from_str("not valid toml {{{{");
        assert!(result.is_err());
    }

    // ─── dry_run flag ──────────────────────────────────────────────────────

    #[tokio::test]
    async fn dry_run_with_temp_project() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();

        // Create minimal agent.leviath
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);

        // Create tests directory with a test file
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        let test_toml = r#"
[[test]]
name = "valid_test"
input = "hello"
expect_contains = "world"
"#;
        std::fs::write(tests_dir.join("basic.toml"), test_toml).unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };

        let result = execute(args).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn dry_run_no_tests_dir() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();

        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };

        // Should succeed but report no tests found
        let result = execute(args).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn execute_no_manifest_errors() {
        let dir = tempfile::tempdir().unwrap();
        let args = TestArgs {
            path: Some(dir.path().to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("agent.leviath"));
    }

    // ─── TestCase struct construction ──────────────────────────────────────

    #[test]
    fn test_case_all_fields_from_toml() {
        let toml_content = r#"
[[test]]
name = "full_test"
input = "full input"
expect_contains = "expected"
expect_tool_call = "bash"
max_tokens = 1000
"#;
        let test_file: TestFile = toml::from_str(toml_content).unwrap();
        let tc = &test_file.test[0];
        assert_eq!(tc.name, "full_test");
        assert_eq!(tc.input, "full input");
        assert_eq!(tc.expect_contains.as_deref(), Some("expected"));
        assert_eq!(tc.expect_tool_call.as_deref(), Some("bash"));
        assert_eq!(tc.max_tokens, Some(1000));
    }

    #[test]
    fn test_case_minimal_from_toml() {
        let toml_content = r#"
[[test]]
name = "min"
input = "hello"
expect_contains = "world"
"#;
        let test_file: TestFile = toml::from_str(toml_content).unwrap();
        let tc = &test_file.test[0];
        assert!(tc.expect_tool_call.is_none());
        assert!(tc.max_tokens.is_none());
    }

    #[test]
    fn test_file_multiple_cases() {
        let toml_content = r#"
[[test]]
name = "case1"
input = "a"
expect_contains = "b"

[[test]]
name = "case2"
input = "c"
expect_tool_call = "read_file"

[[test]]
name = "case3"
input = "d"
expect_contains = "e"
expect_tool_call = "bash"
max_tokens = 500
"#;
        let test_file: TestFile = toml::from_str(toml_content).unwrap();
        assert_eq!(test_file.test.len(), 3);
    }

    // ─── validate_test_case edge cases ────────────────────────────────────

    #[test]
    fn validate_test_case_whitespace_name_passes() {
        // A whitespace-only name is technically non-empty
        let tc = TestCase {
            name: " ".to_string(),
            input: "hello".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(validate_test_case(&tc));
    }

    // ─── truncate_str edge cases ──────────────────────────────────────────

    #[test]
    fn truncate_str_one_char_max() {
        assert_eq!(truncate_str("hello", 1), "h...");
    }

    #[test]
    fn truncate_str_unicode() {
        assert_eq!(truncate_str("abcde", 3), "abc...");
        // Issue #115: the cut lands inside a multi-byte character. This used to
        // panic ("byte index N is not a char boundary") on the assertion-failure
        // path, which prints raw model output. '🎉' occupies bytes 3..7.
        assert_eq!(truncate_str("abc🎉def", 4), "abc...");
        assert_eq!(truncate_str("abc🎉def", 6), "abc...");
        // A boundary-aligned cut is unaffected.
        assert_eq!(truncate_str("abc🎉def", 7), "abc🎉...");
        // Every character straddles the cut - the preview degrades to the marker
        // rather than panicking.
        assert_eq!(truncate_str("🎉🎉", 2), "...");
    }

    // ─── dry_run with filter ──────────────────────────────────────────────

    #[tokio::test]
    async fn dry_run_with_filter_matches() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        let test_toml = r#"
[[test]]
name = "alpha_test"
input = "hello"
expect_contains = "world"

[[test]]
name = "beta_test"
input = "hello"
expect_contains = "world"
"#;
        std::fs::write(tests_dir.join("basic.toml"), test_toml).unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: Some("alpha".to_string()),
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn dry_run_failing_test_case() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        // No assertions = fails validation
        let test_toml = r#"
[[test]]
name = "bad_test"
input = "hello"
"#;
        std::fs::write(tests_dir.join("fail.toml"), test_toml).unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_err()); // Should report failures
    }

    // ─── validate_test_case more cases ───────────────────────────────────

    #[test]
    fn validate_test_case_with_max_tokens_only_and_no_assertion_fails() {
        let tc = TestCase {
            name: "has-max-tokens".to_string(),
            input: "test".to_string(),
            expect_contains: None,
            expect_tool_call: None,
            max_tokens: Some(500),
        };
        assert!(!validate_test_case(&tc));
    }

    #[test]
    fn validate_test_case_with_only_tool_call_assertion() {
        let tc = TestCase {
            name: "tool-only".to_string(),
            input: "do it".to_string(),
            expect_contains: None,
            expect_tool_call: Some("write_file".to_string()),
            max_tokens: None,
        };
        assert!(validate_test_case(&tc));
    }

    // ─── truncate_str additional ─────────────────────────────────────────

    #[test]
    fn truncate_str_zero_max() {
        assert_eq!(truncate_str("hello", 0), "...");
    }

    #[test]
    fn truncate_str_large_max() {
        let s = "short";
        assert_eq!(truncate_str(s, 1000), "short");
    }

    // ─── TestFile TOML parsing edge cases ────────────────────────────────

    #[test]
    fn parse_test_file_empty_tests_array() {
        let toml_content = r#"
test = []
"#;
        let test_file: TestFile = toml::from_str(toml_content).unwrap();
        assert!(test_file.test.is_empty());
    }

    #[test]
    fn parse_test_file_missing_test_key_errors() {
        let result: Result<TestFile, _> = toml::from_str("something_else = 42");
        assert!(result.is_err());
    }

    // ─── dry_run with no matching filter ─────────────────────────────────

    #[tokio::test]
    async fn dry_run_with_filter_no_match() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        let test_toml = r#"
[[test]]
name = "alpha_test"
input = "hello"
expect_contains = "world"
"#;
        std::fs::write(tests_dir.join("basic.toml"), test_toml).unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: Some("nonexistent_filter".to_string()),
            dry_run: true,
        };
        // All tests filtered out = 0 total, no failures
        let result = execute(args).await;
        assert!(result.is_ok());
    }

    // ─── Rhai script tests ────────────────────────────────────────────────

    #[tokio::test]
    async fn dry_run_with_rhai_script_passing() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        // Write a Rhai script that returns true (passes)
        std::fs::write(tests_dir.join("pass_test.rhai"), "true").unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn dry_run_with_rhai_script_returning_false() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        // Write a Rhai script that returns false (fails)
        std::fs::write(tests_dir.join("fail_test.rhai"), "false").unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_err()); // Should report test failure
    }

    #[tokio::test]
    async fn dry_run_with_rhai_script_error() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        // Write a Rhai script that throws an error
        std::fs::write(
            tests_dir.join("error_test.rhai"),
            "throw \"intentional error\"",
        )
        .unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_err()); // Should report script error as failure
    }

    #[tokio::test]
    async fn dry_run_with_rhai_non_bool_result_passes() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        // Write a Rhai script that returns a non-bool (treated as pass)
        std::fs::write(tests_dir.join("nonbool_test.rhai"), "42").unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_ok()); // Non-bool return treated as pass
    }

    #[tokio::test]
    async fn dry_run_with_rhai_filter_matches() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        // A rhai script whose name won't match the filter
        std::fs::write(tests_dir.join("fail_test.rhai"), "false").unwrap();
        // A rhai script that passes and matches the filter
        std::fs::write(tests_dir.join("good_test.rhai"), "true").unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: Some("good".to_string()),
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_ok()); // Only "good_test.rhai" runs, which passes
    }

    // ─── dry_run with multiple test files ────────────────────────────────

    #[tokio::test]
    async fn dry_run_with_multiple_test_files() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        let test1 = r#"
[[test]]
name = "test_a"
input = "hello"
expect_contains = "world"
"#;
        let test2 = r#"
[[test]]
name = "test_b"
input = "foo"
expect_tool_call = "bar"
"#;
        std::fs::write(tests_dir.join("file1.toml"), test1).unwrap();
        std::fs::write(tests_dir.join("file2.toml"), test2).unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_ok());
    }

    // ─── dry_run with invalid TOML file ──────────────────────────────────

    #[tokio::test]
    async fn dry_run_with_invalid_toml_file() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("bad.toml"), "not valid {{{ toml").unwrap();

        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute(args).await;
        assert!(result.is_err());
    }

    // ─── run_test_case: mock provider (no real network calls) ────────────
    //
    // `execute()`'s non-dry-run path calls `Config::load()`, which reads the
    // developer's real `~/.leviath/config.toml` (and env var fallbacks) --
    // there's no path-injection seam for it from this file, and adding one
    // would require touching `config.rs`, which is out of scope. Driving
    // `execute(dry_run: false)` in a test would risk registering a real
    // provider with a real API key and making a live network call, which is
    // exactly the kind of flakiness/cost we must not introduce. Instead, we
    // exercise `run_test_case` directly with an in-memory mock `Provider`,
    // which covers the same assertion/response-handling logic without any
    // I/O.

    use leviath_providers::{
        FinishReason, InferenceRequest, InferenceResponse, Provider, TokenUsage, ToolCall,
    };

    /// A mock provider that returns a fixed canned response, entirely in
    /// memory - no network calls, no subprocess spawning.
    struct MockProvider {
        content: String,
        tool_calls: Vec<ToolCall>,
    }

    #[async_trait::async_trait]
    impl Provider for MockProvider {
        async fn infer(
            &self,
            _request: &InferenceRequest,
        ) -> leviath_providers::Result<InferenceResponse> {
            Ok(InferenceResponse {
                content: self.content.clone(),
                tool_calls: self.tool_calls.clone(),
                tokens_used: TokenUsage {
                    prompt_tokens: 1,
                    completion_tokens: 1,
                    total_tokens: 2,
                    cached_tokens: 0,
                    cache_write_tokens: 0,
                },
                finish_reason: FinishReason::Complete,
            })
        }

        async fn count_tokens(&self, text: &str, _model: &str) -> usize {
            text.len()
        }

        fn max_context_tokens(&self, _model: &str) -> usize {
            8192
        }

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

        fn capabilities(&self, _model: &str) -> leviath_providers::ModelCapabilities {
            leviath_providers::ModelCapabilities::default()
        }
    }

    /// A mock provider that does NOT support temperature (the default caps have
    /// it `true`), so the `else { 0.0 }` branch of the temperature choice runs.
    struct NoTemperatureProvider;

    #[async_trait::async_trait]
    impl Provider for NoTemperatureProvider {
        async fn infer(
            &self,
            _request: &InferenceRequest,
        ) -> leviath_providers::Result<InferenceResponse> {
            Ok(InferenceResponse {
                content: "cold hello".to_string(),
                tool_calls: vec![],
                tokens_used: TokenUsage {
                    prompt_tokens: 1,
                    completion_tokens: 1,
                    total_tokens: 2,
                    cached_tokens: 0,
                    cache_write_tokens: 0,
                },
                finish_reason: FinishReason::Complete,
            })
        }

        async fn count_tokens(&self, text: &str, _model: &str) -> usize {
            text.len()
        }

        fn max_context_tokens(&self, _model: &str) -> usize {
            8192
        }

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

        fn capabilities(&self, _model: &str) -> leviath_providers::ModelCapabilities {
            leviath_providers::ModelCapabilities {
                supports_temperature: false,
                ..Default::default()
            }
        }
    }

    /// A mock provider that always returns an error.
    struct ErrorProvider;

    #[async_trait::async_trait]
    impl Provider for ErrorProvider {
        async fn infer(
            &self,
            _request: &InferenceRequest,
        ) -> leviath_providers::Result<InferenceResponse> {
            Err(leviath_providers::ProviderError::ApiError(
                "simulated inference error".to_string(),
            ))
        }

        async fn count_tokens(&self, text: &str, _model: &str) -> usize {
            text.len()
        }

        fn max_context_tokens(&self, _model: &str) -> usize {
            8192
        }

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

        fn capabilities(&self, _model: &str) -> leviath_providers::ModelCapabilities {
            leviath_providers::ModelCapabilities::default()
        }
    }

    fn basic_blueprint() -> leviath_core::Blueprint {
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        parse_manifest(manifest).unwrap()
    }

    /// Blueprint with an explicit `tool_results` region, so the
    /// `if window.get_region("tool_results").is_none()` branch is NOT taken.
    fn blueprint_with_tool_results_region() -> leviath_core::Blueprint {
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }

[context.regions.tool_results]
kind = "temporary"
max_tokens = 5000
"#;
        parse_manifest(manifest).unwrap()
    }

    /// A provider that records the request it receives, so a test can assert
    /// what `lev test` actually assembled (e.g. a custom region's rendered
    /// output).
    struct RecordingProvider {
        seen: std::sync::Arc<std::sync::Mutex<Option<InferenceRequest>>>,
    }

    #[async_trait::async_trait]
    impl Provider for RecordingProvider {
        async fn infer(
            &self,
            request: &InferenceRequest,
        ) -> leviath_providers::Result<InferenceResponse> {
            *self.seen.lock().unwrap() = Some(request.clone());
            Ok(InferenceResponse {
                content: "recorded".to_string(),
                tool_calls: vec![],
                tokens_used: TokenUsage {
                    prompt_tokens: 1,
                    completion_tokens: 1,
                    total_tokens: 2,
                    cached_tokens: 0,
                    cache_write_tokens: 0,
                },
                finish_reason: FinishReason::Complete,
            })
        }

        async fn count_tokens(&self, text: &str, _model: &str) -> usize {
            text.len()
        }

        fn max_context_tokens(&self, _model: &str) -> usize {
            8192
        }

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

        fn capabilities(&self, _model: &str) -> leviath_providers::ModelCapabilities {
            leviath_providers::ModelCapabilities::default()
        }
    }

    /// `lev test` runs custom-region render hooks with the entry stage's real
    /// metadata - the preview a hook author iterates against.
    #[tokio::test]
    async fn run_test_case_renders_custom_region_through_its_script() {
        let manifest = r#"
[agent]
name = "custom-test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }

[context.regions.task]
kind = "pinned"
max_tokens = 4000

[context.regions.brain]
kind = "custom"
script = "hooks/brain.rhai"
max_tokens = 4000
"#;
        let blueprint = parse_manifest(manifest).unwrap();
        let scripts = std::collections::HashMap::from([(
            "hooks/brain.rhai".to_string(),
            std::sync::Arc::new(
                leviath_scripting::region_hook::compile(
                    "hooks/brain.rhai",
                    "fn render(ctx) { `<brain stage=${ctx.stage_name} model=${ctx.model}>` }",
                )
                .unwrap(),
            ),
        )]);
        let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(RecordingProvider { seen: seen.clone() }),
        );
        let tc = TestCase {
            name: "custom_render".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("recorded".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        let passed = run_test_case(&blueprint, &registry, &tc, &scripts)
            .await
            .unwrap();
        assert!(passed);
        let request = seen.lock().unwrap().take().expect("provider saw a request");
        // Precompute the texts so the assert message costs no extra branch.
        let system_texts: Vec<&String> = request.system.iter().map(|b| &b.text).collect();
        let rendered = system_texts
            .iter()
            .any(|t| t.as_str() == "<brain stage=main model=claude-sonnet-4-6>");
        assert!(
            rendered,
            "custom region rendered with stage metadata; system blocks: {system_texts:?}"
        );

        // Exercise the recording provider's remaining trait surface directly.
        let provider = registry.get("anthropic").unwrap();
        assert_eq!(provider.count_tokens("abcd", "m").await, 4);
        assert_eq!(provider.max_context_tokens("m"), 8192);
        assert_eq!(provider.name(), "recording");
    }

    /// The custom-region resolve error path in `execute` (a declared script
    /// that doesn't exist fails before any provider setup, dry-run or not).
    #[tokio::test]
    async fn execute_fails_fast_on_a_broken_custom_region_script() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        std::fs::write(
            project.join("agent.leviath"),
            r#"
[agent]
name = "broken-custom"
version = "0.1.0"
description = "d"

[stages.main]
model = { provider = "anthropic", model = "m" }

[context.regions.brain]
kind = "custom"
script = "hooks/missing.rhai"
max_tokens = 4000
"#,
        )
        .unwrap();
        std::fs::create_dir(project.join("tests")).unwrap();
        std::fs::write(
            project.join("tests/basic.toml"),
            "[[test]]\nname = \"t\"\ninput = \"hi\"\n",
        )
        .unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let err = execute(args).await.unwrap_err().to_string();
        assert!(err.contains("region 'brain'"), "{err}");
        assert!(err.contains("hooks/missing.rhai"), "{err}");
    }

    // ── new coverage tests ────────────────────────────────────────────────────

    /// Covers the `map_err(|e| anyhow!("Inference failed: {}", e))` closure
    /// path at the `provider.infer(...)` call-site.
    #[tokio::test]
    async fn run_test_case_inference_error_propagates() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register("anthropic".to_string(), Arc::new(ErrorProvider));
        let tc = TestCase {
            name: "inference_error".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("x".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Inference failed"));
    }

    /// Covers the `ok_or(anyhow!("Blueprint has no stages"))` path.
    #[tokio::test]
    async fn run_test_case_blueprint_with_no_stages_errors() {
        use leviath_core::{Blueprint, layout::ContextLayout};
        let blueprint = Blueprint::new(
            "no-stages".to_string(),
            "test".to_string(),
            vec![],
            ContextLayout::new(vec![], 4096),
        );
        let registry = ProviderRegistry::new();
        let tc = TestCase {
            name: "no_stages".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("x".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Blueprint has no stages"));
    }

    /// A blueprint that already declares a `tool_results` region runs fine (the
    /// window builder leaves the existing region in place).
    #[tokio::test]
    async fn run_test_case_with_preexisting_tool_results_region() {
        let blueprint = blueprint_with_tool_results_region();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "hello world".to_string(),
                tool_calls: vec![],
            }),
        );
        let tc = TestCase {
            name: "has_tool_results_region".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(result.unwrap());
    }

    /// Covers `fs::read_to_string(&manifest_path)?` failing by making
    /// `agent.leviath` a *directory*: `exists()` passes the guard but the read
    /// fails on every platform.
    #[tokio::test]
    async fn execute_with_registry_manifest_unreadable_errors() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        std::fs::create_dir_all(project.join("agent.leviath")).unwrap();
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute_with_registry(args, Box::new(build_registry_from_config)).await;
        assert!(result.is_err());
    }

    /// Covers `Config::load()?` (line 139) failing when the config file exists
    /// but contains invalid TOML.  Uses `isolate_config_path_for_test` so that
    /// we redirect `LEVIATH_CONFIG_PATH` to a temp file we control, avoiding
    /// any mutation of the user's real `~/.leviath/config.toml`.
    #[tokio::test]
    async fn execute_with_registry_config_load_fails_errors() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();

        // Redirect Config::load() to a file with invalid TOML.
        crate::config::with_isolated_config_path_async(
            "test-cmd-config-fail",
            |fake_dir| async move {
                let bad_config = fake_dir.join("config.toml");
                std::fs::write(&bad_config, "not valid toml {{{").unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false, // triggers Config::load()
                };
                let result =
                    execute_with_registry(args, Box::new(build_registry_from_config)).await;
                assert!(result.is_err());
            },
        )
        .await;
    }

    /// Covers the `parse_manifest(&manifest_content)?` error path
    /// in `execute_with_registry` (invalid TOML in agent.leviath).
    #[tokio::test]
    async fn execute_with_registry_manifest_invalid_toml_errors() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        std::fs::write(project.join("agent.leviath"), "not valid toml {{{").unwrap();
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: false,
        };
        let result =
            execute_with_registry(args, Box::new(mock_registry_builder("irrelevant", vec![])))
                .await;
        assert!(result.is_err());
    }

    /// Covers `fs::read_dir(&tests_dir)?` failing by making `tests` a *file*:
    /// `exists()` passes the guard but `read_dir` fails on every platform.
    #[tokio::test]
    async fn execute_with_registry_tests_dir_unreadable_errors() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        // `tests` is a file, not a directory.
        std::fs::write(project.join("tests"), "not a dir").unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute_with_registry(args, Box::new(build_registry_from_config)).await;
        assert!(result.is_err());
    }

    /// Covers `fs::read_to_string(&test_path)?` for a `.toml` entry by making
    /// it a *directory* (extension is still `toml`): `read_dir` yields it but
    /// the read fails on every platform.
    #[tokio::test]
    async fn execute_with_registry_toml_unreadable_errors() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::create_dir_all(tests_dir.join("unreadable.toml")).unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute_with_registry(args, Box::new(build_registry_from_config)).await;
        assert!(result.is_err());
    }

    /// Covers `fs::read_to_string(&test_path)?` for a `.rhai` entry by making
    /// it a *directory* (extension is still `rhai`): `read_dir` yields it but
    /// the read fails on every platform.
    #[tokio::test]
    async fn execute_with_registry_rhai_unreadable_errors() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::create_dir_all(tests_dir.join("unreadable.rhai")).unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute_with_registry(args, Box::new(build_registry_from_config)).await;
        assert!(result.is_err());
    }

    /// A blueprint with no Pinned region still runs: `init_window` simply skips
    /// seeding the task, and the inference proceeds.
    #[tokio::test]
    async fn run_test_case_with_no_pinned_region_still_runs() {
        use leviath_core::Blueprint;
        use leviath_core::layout::ContextLayout;
        let blueprint = Blueprint::new(
            "no-regions".to_string(),
            "test".to_string(),
            vec![leviath_core::Stage::new(
                "main".to_string(),
                leviath_core::blueprint::ModelConfig::new(
                    "anthropic".to_string(),
                    "claude-sonnet-4-6".to_string(),
                ),
            )],
            ContextLayout::new(vec![], 4096),
        );
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "hello world".to_string(),
                tool_calls: vec![],
            }),
        );
        let tc = TestCase {
            name: "no_pinned".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(
            run_test_case(&blueprint, &registry, &tc, &Default::default())
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn run_test_case_passes_with_expect_contains() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "Hello, world!".to_string(),
                tool_calls: vec![],
            }),
        );

        let tc = TestCase {
            name: "greeting".to_string(),
            input: "say hello".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn run_test_case_fails_expect_contains_mismatch() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "Goodbye".to_string(),
                tool_calls: vec![],
            }),
        );

        let tc = TestCase {
            name: "greeting".to_string(),
            input: "say hello".to_string(),
            expect_contains: Some("world".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn run_test_case_passes_with_expect_tool_call() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: String::new(),
                tool_calls: vec![ToolCall {
                    id: "call_1".to_string(),
                    name: "bash".to_string(),
                    arguments: serde_json::json!({}),
                    thought_signature: None,
                }],
            }),
        );

        let tc = TestCase {
            name: "tool_test".to_string(),
            input: "run a command".to_string(),
            expect_contains: None,
            expect_tool_call: Some("bash".to_string()),
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn run_test_case_fails_expect_tool_call_missing() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "no tools here".to_string(),
                // A non-matching (rather than empty) tool call list still
                // fails the "has_tool" check but also exercises the
                // subsequent `tool_names` diagnostic's `.map()` closure,
                // which an empty Vec's `.iter().map(...)` never invokes at
                // all.
                tool_calls: vec![ToolCall {
                    id: "call_1".to_string(),
                    name: "write_file".to_string(),
                    arguments: serde_json::json!({}),
                    thought_signature: None,
                }],
            }),
        );

        let tc = TestCase {
            name: "tool_test".to_string(),
            input: "run a command".to_string(),
            expect_contains: None,
            expect_tool_call: Some("bash".to_string()),
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn run_test_case_fails_both_assertions() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "unrelated content".to_string(),
                tool_calls: vec![],
            }),
        );

        let tc = TestCase {
            name: "both".to_string(),
            input: "do stuff".to_string(),
            expect_contains: Some("expected".to_string()),
            expect_tool_call: Some("write_file".to_string()),
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn run_test_case_no_assertions_always_passes() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "anything".to_string(),
                tool_calls: vec![],
            }),
        );

        let tc = TestCase {
            name: "no_assertions".to_string(),
            input: "hi".to_string(),
            expect_contains: None,
            expect_tool_call: None,
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn run_test_case_provider_not_registered_errors() {
        let blueprint = basic_blueprint();
        let registry = ProviderRegistry::new(); // empty -- "anthropic" not registered

        let tc = TestCase {
            name: "no_provider".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("x".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        let err = result.unwrap_err().to_string();
        assert!(err.contains("not configured"));
    }

    #[tokio::test]
    async fn no_temperature_provider_metadata_is_exercised() {
        let p = NoTemperatureProvider;
        assert_eq!(p.name(), "no-temperature");
        assert_eq!(p.count_tokens("abcd", "m").await, 4);
        assert_eq!(p.max_context_tokens("m"), 8192);
    }

    #[tokio::test]
    async fn run_test_case_omits_temperature_when_provider_lacks_it() {
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register("anthropic".to_string(), Arc::new(NoTemperatureProvider));
        let tc = TestCase {
            name: "no_temp".to_string(),
            input: "hi".to_string(),
            expect_contains: Some("cold".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };
        assert!(
            run_test_case(&blueprint, &registry, &tc, &Default::default())
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn run_test_case_long_input_runs() {
        // A long input still seeds cleanly into the pinned task region.
        let blueprint = basic_blueprint();
        let mut registry = ProviderRegistry::new();
        registry.register(
            "anthropic".to_string(),
            Arc::new(MockProvider {
                content: "response text mentioning keyword".to_string(),
                tool_calls: vec![],
            }),
        );

        let tc = TestCase {
            name: "long_input".to_string(),
            input: "x".repeat(500),
            expect_contains: Some("keyword".to_string()),
            expect_tool_call: None,
            max_tokens: None,
        };

        let result = run_test_case(&blueprint, &registry, &tc, &Default::default()).await;
        assert!(result.unwrap());
    }

    // ─── execute_with_registry: non-dry-run path (mock provider) ────────────
    //
    // `execute()`'s non-dry-run path still calls the real `Config::load()`
    // (no path-injection seam for that without touching config.rs, out of
    // scope here). `execute_with_registry` takes the registry-building step
    // as a parameter, so we can hand it a registry built entirely from an
    // in-memory `MockProvider` and don't care what the config *contains* --
    // no network calls, no real API keys read. But `Config::load()?` still
    // propagates a hard error via `?` if it fails, which is *not* irrelevant:
    // every test below that reaches this line uses
    // `isolate_config_path_for_test` to point `LEVIATH_CONFIG_PATH` at a
    // guaranteed-absent path, so `Config::load()` deterministically falls
    // back to defaults instead of racing some *other*, concurrently-running
    // test's temporarily-malformed config file at the same process-global
    // env var (see `models.rs`'s own `isolate_config_path_for_test` users
    // for the other side of that race - without this, this whole group was
    // observed to fail intermittently, with a config-parse error instead of
    // the expected test-run outcome, when run alongside `commands::models`'s
    // test suite).

    fn mock_registry_builder(
        content: &'static str,
        tool_calls: Vec<ToolCall>,
    ) -> impl FnOnce(&Config) -> Result<ProviderRegistry, leviath_providers::ProviderError> {
        move |_config: &Config| {
            let mut reg = ProviderRegistry::new();
            reg.register(
                "anthropic".to_string(),
                Arc::new(MockProvider {
                    content: content.to_string(),
                    tool_calls,
                }),
            );
            Ok(reg)
        }
    }

    fn write_project_with_test_file(project: &std::path::Path, test_toml: &str) {
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("basic.toml"), test_toml).unwrap();
    }

    #[tokio::test]
    async fn execute_with_registry_non_dry_run_all_pass() {
        crate::config::with_isolated_config_path_async(
            "test-rs-non-dry-run-all-pass",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                write_project_with_test_file(
                    project,
                    r#"
[[test]]
name = "greeting"
input = "say hello"
expect_contains = "world"
"#,
                );

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result = with_tracing(|| {
                    execute_with_registry(
                        args,
                        Box::new(mock_registry_builder("Hello, world!", vec![])),
                    )
                })
                .await;
                assert!(result.is_ok());
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_none_path_defaults_to_current_dir() {
        // Covers the `unwrap_or_else(|| ".".to_string())` closure, never
        // invoked by any other test (all of which pass an explicit `path`).
        // `cargo test`'s cwd is this crate's own source directory, which
        // has no `agent.leviath`, so this deterministically hits the
        // "No agent.leviath found" bail - proving the closure ran without
        // depending on (or mutating) any real project directory.
        let args = TestArgs {
            path: None,
            filter: None,
            dry_run: true,
        };
        let result = execute_with_registry(args, Box::new(build_registry_from_config)).await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No agent.leviath found")
        );
    }

    #[tokio::test]
    async fn execute_with_registry_non_dry_run_failure_bails_with_count() {
        crate::config::with_isolated_config_path_async(
            "test-rs-non-dry-run-failure-bails-with-count",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                write_project_with_test_file(
                    project,
                    r#"
[[test]]
name = "greeting"
input = "say hello"
expect_contains = "world"
"#,
                );

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("goodbye", vec![])))
                        .await;
                let err = result.unwrap_err().to_string();
                assert!(err.contains("1 test(s) failed"));
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_non_dry_run_applies_filter() {
        crate::config::with_isolated_config_path_async(
            "test-rs-non-dry-run-applies-filter",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                write_project_with_test_file(
                    project,
                    r#"
[[test]]
name = "keep_me"
input = "say hello"
expect_contains = "world"

[[test]]
name = "skip_me"
input = "say hello"
expect_contains = "unmatchable content"
"#,
                );

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: Some("keep".to_string()),
                    dry_run: false,
                };

                // "skip_me" would fail (its expectation never matches the mock
                // response), but the filter excludes it - only "keep_me" runs, and
                // it passes, so the whole run succeeds.
                let result = execute_with_registry(
                    args,
                    Box::new(mock_registry_builder("Hello, world!", vec![])),
                )
                .await;
                assert!(result.is_ok());
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_non_dry_run_tool_call_assertion() {
        crate::config::with_isolated_config_path_async(
            "test-rs-non-dry-run-tool-call-assertion",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                write_project_with_test_file(
                    project,
                    r#"
[[test]]
name = "tool_test"
input = "run a command"
expect_tool_call = "bash"
"#,
                );

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let tool_calls = vec![ToolCall {
                    id: "call_1".to_string(),
                    name: "bash".to_string(),
                    arguments: serde_json::json!({}),
                    thought_signature: None,
                }];
                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("", tool_calls)))
                        .await;
                assert!(result.is_ok());
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_non_dry_run_provider_error_counts_as_failure() {
        crate::config::with_isolated_config_path_async(
            "test-rs-non-dry-run-provider-error-counts-as-failure",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                write_project_with_test_file(
                    project,
                    r#"
[[test]]
name = "no_such_provider"
input = "hi"
expect_contains = "x"
"#,
                );
                // Overwrite the manifest with a provider name the mock registry never
                // registers, so `run_test_case`'s "not configured" error path fires
                // (the `Err(e)` arm of `execute`'s match, not `Ok(false)`).
                std::fs::write(
                    project.join("agent.leviath"),
                    r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "nonexistent-provider", model = "x" }
"#,
                )
                .unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result = execute_with_registry(
                    args,
                    Box::new(mock_registry_builder("irrelevant", vec![])),
                )
                .await;
                let err = result.unwrap_err().to_string();
                assert!(err.contains("1 test(s) failed"));
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_non_dry_run_toml_malformed_errors() {
        crate::config::with_isolated_config_path_async(
            "test-rs-non-dry-run-toml-malformed-errors",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                write_project_with_test_file(project, "not valid {{{ toml");

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result = execute_with_registry(
                    args,
                    Box::new(mock_registry_builder("irrelevant", vec![])),
                )
                .await;
                assert!(result.is_err());
                assert!(result.unwrap_err().to_string().contains("Failed to parse"));
            },
        )
        .await;
    }

    // ─── rhai script execution path ──────────────────────────────────────────

    #[tokio::test]
    async fn execute_with_registry_rhai_script_passes() {
        crate::config::with_isolated_config_path_async(
            "test-rs-rhai-script-passes",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
                write_test_agent(project, manifest);
                let tests_dir = project.join("tests");
                std::fs::create_dir_all(&tests_dir).unwrap();
                std::fs::write(tests_dir.join("script.rhai"), "true").unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("unused", vec![])))
                        .await;
                assert!(result.is_ok());
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_rhai_script_returns_false_fails() {
        crate::config::with_isolated_config_path_async(
            "test-rs-rhai-script-returns-false-fails",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
                write_test_agent(project, manifest);
                let tests_dir = project.join("tests");
                std::fs::create_dir_all(&tests_dir).unwrap();
                std::fs::write(tests_dir.join("script.rhai"), "false").unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("unused", vec![])))
                        .await;
                let err = result.unwrap_err().to_string();
                assert!(err.contains("1 test(s) failed"));
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_rhai_script_error_fails() {
        crate::config::with_isolated_config_path_async(
            "test-rs-rhai-script-error-fails",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
                write_test_agent(project, manifest);
                let tests_dir = project.join("tests");
                std::fs::create_dir_all(&tests_dir).unwrap();
                std::fs::write(tests_dir.join("script.rhai"), "this is not valid rhai (((")
                    .unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("unused", vec![])))
                        .await;
                assert!(result.is_err());
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_rhai_script_non_bool_return_passes() {
        crate::config::with_isolated_config_path_async(
            "test-rs-rhai-script-non-bool-return-passes",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
                write_test_agent(project, manifest);
                let tests_dir = project.join("tests");
                std::fs::create_dir_all(&tests_dir).unwrap();
                // Returns an integer, not a bool - exercises the `else` arm of the
                // `result.as_bool()` match (treated as an automatic pass).
                std::fs::write(tests_dir.join("script.rhai"), "42").unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: None,
                    dry_run: false,
                };

                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("unused", vec![])))
                        .await;
                assert!(result.is_ok());
            },
        )
        .await;
    }

    #[tokio::test]
    async fn execute_with_registry_rhai_script_filter_excludes_all() {
        crate::config::with_isolated_config_path_async(
            "test-rs-rhai-script-filter-excludes-all",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().unwrap();
                let project = dir.path();
                let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
                write_test_agent(project, manifest);
                let tests_dir = project.join("tests");
                std::fs::create_dir_all(&tests_dir).unwrap();
                std::fs::write(tests_dir.join("script.rhai"), "false").unwrap();

                let args = TestArgs {
                    path: Some(project.to_str().unwrap().to_string()),
                    filter: Some("no-such-script".to_string()),
                    dry_run: false,
                };

                // Filter excludes the only script - 0 total, reports "no test files
                // found" and succeeds (rather than failing on the script's `false`).
                let result =
                    execute_with_registry(args, Box::new(mock_registry_builder("unused", vec![])))
                        .await;
                assert!(result.is_ok());
            },
        )
        .await;
    }

    // ─── build_registry_from_config ──────────────────────────────────────────
    //
    // The production registry builder passed to `execute_with_registry` by
    // `execute()`. `Provider::new`/`with_base_url` constructors just store
    // config - they don't make network calls - so this is safe to exercise
    // directly with fake keys, registering every provider branch.

    #[test]
    fn build_registry_from_config_registers_all_providers() {
        let config = Config {
            default_provider: "anthropic".to_string(),
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("fake-anthropic-key".to_string()),
                openai_api_key: Some("fake-openai-key".to_string()),
                google_api_key: Some("fake-google-key".to_string()),
                claude_code_enabled: false,
                claude_code_binary: None,
                claude_code_effort: None,
                anthropic_cache_ttl: None,
                fallback_order: Vec::new(),
            },
            openrouter_api_key: Some("fake-openrouter-key".to_string()),
            ollama_base_url: Some("http://localhost:12345".to_string()),
            ..Config::default()
        };

        let registry =
            build_registry_from_config(&config).expect("an HTTPS client builds in tests");
        assert!(registry.has("anthropic"));
        assert!(registry.has("openai"));
        assert!(registry.has("google"));
        assert!(registry.has("openrouter"));
        assert!(registry.has("ollama"));
    }

    #[test]
    fn build_registry_from_config_no_keys_still_registers_ollama_with_default_url() {
        let config = Config::default();
        let registry =
            build_registry_from_config(&config).expect("an HTTPS client builds in tests");
        assert!(!registry.has("anthropic"));
        assert!(!registry.has("openai"));
        assert!(!registry.has("google"));
        assert!(!registry.has("openrouter"));
        // ollama has no key gate - always registered, with the default URL
        // when `ollama_base_url` is unset.
        assert!(registry.has("ollama"));
    }

    /// Covers the implicit `else` branch in the `if .toml / else if .rhai`
    /// check: a file in tests/ whose extension is neither is silently skipped.
    #[tokio::test]
    async fn execute_with_registry_ignores_non_test_files_in_tests_dir() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path();
        let manifest = r#"
[agent]
name = "test-agent"
version = "0.1.0"
description = "test"

[stages.main]
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
"#;
        write_test_agent(project, manifest);
        let tests_dir = project.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        // A .txt file - neither .toml nor .rhai - exercises the implicit else
        // path that simply skips unrecognized files.
        std::fs::write(tests_dir.join("readme.txt"), "this file should be ignored").unwrap();
        let args = TestArgs {
            path: Some(project.to_str().unwrap().to_string()),
            filter: None,
            dry_run: true,
        };
        let result = execute_with_registry(args, Box::new(build_registry_from_config)).await;
        assert!(result.is_ok());
    }

    // ─── ErrorProvider trivial trait methods ─────────────────────────────────

    #[tokio::test]
    async fn error_provider_trivial_trait_methods() {
        let provider = ErrorProvider;
        assert_eq!(provider.count_tokens("hello", "any-model").await, 5);
        assert_eq!(provider.max_context_tokens("any-model"), 8192);
        assert_eq!(provider.name(), "error-provider");
        let caps = provider.capabilities("any-model");
        let _ = caps; // just verify it doesn't panic
    }

    // ─── MockProvider trivial trait methods ──────────────────────────────────

    #[tokio::test]
    async fn mock_provider_trivial_trait_methods() {
        let provider = MockProvider {
            content: "x".to_string(),
            tool_calls: vec![],
        };
        assert_eq!(provider.count_tokens("hello", "any-model").await, 5);
        assert_eq!(provider.max_context_tokens("any-model"), 8192);
        assert_eq!(provider.name(), "mock");
    }

    #[test]
    fn a_registry_needs_an_https_client_it_can_build() {
        // `lev test` registers every configured provider against one client;
        // if that client cannot be built there is nothing to test against.
        let mut config = Config::default();
        config.providers.anthropic_api_key = Some("k".to_string());
        let err = build_registry_from_config_with(&config, &|_t| {
            Err(leviath_providers::provider::malformed_url_error())
        })
        .err()
        .expect("a failing client factory should fail the registry");
        assert!(err.to_string().contains("root certificate store"));
    }

    #[tokio::test]
    async fn a_real_run_stops_when_the_registry_will_not_build() {
        // Not a dry run, so the registry is built - and a machine that cannot
        // build an HTTPS client has nothing to run the cases against.
        crate::config::with_isolated_config_path_async(
            "test-a_real_run_stops_when_the_registry_will_not_build",
            |_fake_dir| async move {
                let dir = tempfile::tempdir().expect("tempdir");
                let project = dir.path();
                write_project_with_test_file(project, "[[test]]\nname = \"t\"\ninput = \"hi\"\n");
                let args = TestArgs {
                    path: Some(project.to_str().expect("utf-8 path").to_string()),
                    filter: None,
                    dry_run: false,
                };
                let failing: RegistryBuilder = Box::new(|_config: &Config| {
                    Err(leviath_providers::ProviderError::ClientBuild(
                        "no roots".to_string(),
                    ))
                });
                let err = execute_with_registry(args, failing)
                    .await
                    .expect_err("a failing registry builder should stop the run");
                assert!(err.to_string().contains("no roots"), "{err}");
            },
        )
        .await;
    }
}