leviath-cli 0.1.1

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
//! Session setup: task resolution, editor launching, engine setup.

use crate::config::Config;
use leviath_runtime::ProviderRegistry;

// `ProviderCreds` + `build_provider_registry(&[ProviderCreds])` live in
// `leviath-runtime` (plain data + provider instantiation, no `Config`
// dependency). Re-exported here so `commands::run`'s public re-export and all
// existing call sites keep resolving. The `Config`-based translators
// (`provider_creds_from_config` / `build_provider_registry_from_config`) stay
// below because they need the CLI's `Config`.
pub use leviath_runtime::provider_creds::{ProviderCreds, build_provider_registry};

/// Resolve the task string from a CLI argument.
///
/// - `Some(s)` where `s` is an existing file path → read file contents.
/// - `Some(s)` otherwise → use `s` as a literal prompt.
/// - `None` when stdin is not a TTY → error.
/// - `None` when stdin is a TTY → launch the user's editor on a temp prompt file.
///
/// `stdin_is_terminal` is injected (a `&dyn Fn() -> bool`) rather than probing
/// the real process stdin here, so the library core stays free of direct
/// `std::io::stdin()` access and is fully testable. In production the binary
/// passes `&|| std::io::stdin().is_terminal()`.
pub fn resolve_task(
    arg: &Option<String>,
    agent_name: &str,
    description: Option<&str>,
    stdin_is_terminal: &dyn Fn() -> bool,
) -> anyhow::Result<String> {
    resolve_task_with(arg, agent_name, description, stdin_is_terminal)
}

/// Same as [`resolve_task`], but with the stdin-is-a-TTY check injected
/// instead of hardcoded - lets tests deterministically exercise both the
/// "not a TTY" error path and the "is a TTY" editor-launch path regardless
/// of whether the test runner's own stdin happens to be a real terminal
/// (e.g. a human running `cargo test` interactively vs. CI).
///
/// `stdin_is_terminal` is a trait-object reference (`&dyn Fn`) rather than
/// `impl FnOnce` deliberately: this function is called from many test sites,
/// each passing a distinct closure *type* even when the closures are
/// behaviorally identical (e.g. multiple `|| true`s are still different
/// anonymous types). A generic `impl Trait` parameter gives `rustc` one
/// monomorphization per call site, and `cargo llvm-cov` sometimes reports a
/// region as uncovered for one instantiation even though the union of all
/// instantiations covers every source position - a confirmed llvm-cov
/// limitation (see `xtask/src/coverage.rs`'s doc comment on generic-function
/// monomorphization). Erasing the closure type with `&dyn Fn` collapses
/// every call site back down to a single instantiation, avoiding that noise
/// entirely.
fn resolve_task_with(
    arg: &Option<String>,
    agent_name: &str,
    description: Option<&str>,
    stdin_is_terminal: &dyn Fn() -> bool,
) -> anyhow::Result<String> {
    resolve_task_with_editor(
        arg,
        agent_name,
        description,
        stdin_is_terminal,
        &launch_editor,
        &std::env::temp_dir,
    )
}

/// Resolve one CLI region-flag value: `@path` reads (and trims) that file's
/// contents; anything else is literal text. Unlike `--task`, the `@` is an
/// explicit file marker, so a missing `@file` is an error (the user meant a
/// file), not a literal fallback.
pub fn read_region_value(raw: &str) -> anyhow::Result<String> {
    match raw.strip_prefix('@') {
        Some(path) => {
            let content = std::fs::read_to_string(path)
                .map_err(|e| anyhow::anyhow!("Failed to read region file '{}': {}", path, e))?;
            let trimmed = content.trim().to_string();
            if trimmed.is_empty() {
                anyhow::bail!("Region file '{}' is empty.", path);
            }
            Ok(trimmed)
        }
        None => Ok(raw.to_string()),
    }
}

/// Same as [`resolve_task_with`], but with the editor launch itself injected
/// too - lets tests deterministically exercise `launch_editor`'s error
/// propagating out of `resolve_task_with` (the `result?` a few lines down)
/// without needing a real failing subprocess/PATH setup. On Windows there is
/// no safe way to make the real `launch_editor`'s platform-default candidate
/// (`notepad`, resolved via `System32` unconditionally) fail without
/// mutating the real system directory, so `resolve_task_with`'s own
/// `#[cfg(unix)]`-only real-PATH-starvation test for this can't be mirrored
/// there - injecting the editor launcher closes that gap on every platform.
///
/// Also takes the temp-directory provider (`tmp_dir_fn`) as an injectable
/// closure so tests can point the task-template write at a guaranteed-
/// unwritable directory (e.g. one whose parent doesn't exist) and
/// deterministically exercise `write_task_template`'s `?` propagating out of
/// this function - the real OS temp directory used in production is
/// essentially always writable, so that error path is otherwise untestable.
///
/// All closures are `&dyn Fn` for the same monomorphization-noise reason
/// documented on [`resolve_task_with`].
fn resolve_task_with_editor(
    arg: &Option<String>,
    agent_name: &str,
    description: Option<&str>,
    stdin_is_terminal: &dyn Fn() -> bool,
    launch_editor_fn: &dyn Fn(&std::path::Path) -> anyhow::Result<()>,
    tmp_dir_fn: &dyn Fn() -> std::path::PathBuf,
) -> anyhow::Result<String> {
    match arg {
        Some(s) => {
            let p = std::path::Path::new(s);
            if p.is_file() {
                let content = std::fs::read_to_string(p)
                    .map_err(|e| anyhow::anyhow!("Failed to read task file '{}': {}", s, e))?;
                let trimmed = content.trim().to_string();
                if trimmed.is_empty() {
                    anyhow::bail!("Task file '{}' is empty.", s);
                }
                return Ok(trimmed);
            }
            Ok(s.clone())
        }
        None => {
            if !stdin_is_terminal() {
                anyhow::bail!(
                    "No task provided. Pass --task \"<prompt>\" or --task <file>.\n\
                     (stdin is not a TTY, so the interactive editor cannot be used)"
                );
            }

            // Build a commented template file for the editor
            let template = build_task_template(agent_name, description);

            // A randomly named file created `O_EXCL`, not `lev-task-<pid>.txt`.
            // A predictable name is an attack surface because `fs::write`
            // follows symlinks: on a shared host another user pre-creates that
            // path as a link to `~/.leviath/config.toml` or
            // `~/.ssh/authorized_keys`, and the next `lev run` writes the
            // template - and then everything the user types into their editor -
            // straight through it. `tempfile`
            // also creates it owner-only, so the task prompt is not world
            // readable while the editor holds it open.
            let tmp = write_task_template(&tmp_dir_fn(), &template)?;
            // Close our own handle before the editor opens the file: Windows
            // refuses a second writer while the first still holds it, so the
            // editor could not save. `TempPath` keeps the delete-on-drop.
            let tmp = tmp.into_temp_path();
            let tmp_path = tmp.to_path_buf();

            // Launch the editor (exits only when the user closes it)
            let result = launch_editor_fn(&tmp_path);
            let content = std::fs::read_to_string(&tmp_path).unwrap_or_default();
            let _ = std::fs::remove_file(&tmp_path);
            result?;

            // Strip comment lines and trim
            let task: String = content
                .lines()
                .filter(|l| !l.trim_start().starts_with('#'))
                .collect::<Vec<_>>()
                .join("\n")
                .trim()
                .to_string();

            if task.is_empty() {
                anyhow::bail!("Aborting run: empty task.");
            }
            Ok(task)
        }
    }
}

fn build_task_template(agent_name: &str, description: Option<&str>) -> String {
    let mut template = format!("# Task for agent: {}\n", agent_name);
    if let Some(desc) = description
        && !desc.is_empty()
    {
        template.push_str(&format!("# {}\n", desc));
    }
    template.push_str("#\n# Describe your task below. Lines starting with '#' are ignored.\n\n");
    template
}

fn write_task_template(
    dir: &std::path::Path,
    content: &str,
) -> anyhow::Result<tempfile::NamedTempFile> {
    use std::io::Write as _;

    // Creating and writing in one fallible step, through the handle the builder
    // opened. Two steps would mean re-opening by path between them - a window in
    // which the name could be swapped - and a second error arm that a freshly
    // created, writable handle can never actually take.
    // A combinator chain rather than `?`s: each `?` would be an error arm that
    // a freshly created, writable handle can never take, and the whole point of
    // reporting here is the one failure that is real - the file could not be
    // created at all.
    tempfile::Builder::new()
        .prefix("lev-task-")
        .suffix(".txt")
        .tempfile_in(dir)
        .and_then(|mut file| {
            file.as_file_mut()
                .write_all(content.as_bytes())
                .and_then(|()| file.as_file_mut().flush())
                .map(|()| file)
        })
        .map_err(|e| anyhow::anyhow!("Failed to create task temp file: {}", e))
}

/// Platform-specific fallback editor candidates, appended after any
/// $VISUAL/$EDITOR candidates.
///
/// Extracted into its own pure, injectable function (rather than inlined
/// directly in [`launch_editor`]) so tests can assert on the Windows
/// candidate list containing `notepad` without ever having to actually
/// spawn it - launching a real, blocking, interactive GUI text editor with
/// no timeout would hang CI indefinitely.
fn platform_default_editors() -> Vec<String> {
    #[cfg(unix)]
    {
        vec!["vim".to_string(), "nano".to_string(), "vi".to_string()]
    }
    #[cfg(windows)]
    {
        vec!["notepad".to_string()]
    }
}

/// Launch the user's preferred editor on `path` and wait for it to exit.
///
/// Editor resolution order: $VISUAL$EDITOR → platform default.
/// Platform defaults: Unix tries `vim` then `nano`; Windows uses `notepad`.
/// Outcome of running one editor candidate, abstracting over the raw
/// `ExitStatus`. This exists so the "ran but ended with no exit code" case (a
/// signal kill on Unix) is injectable in tests on *every* platform: on Windows
/// an `ExitStatus` always carries a code (even via `ExitStatusExt::from_raw`),
/// so that case cannot be fabricated from a status directly. The injected `run`
/// seam of [`launch_editor_with`] therefore yields this enum rather than an
/// `ExitStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EditorRunOutcome {
    /// Process finished (success, or any explicit exit code) - treat as the
    /// user having closed the editor.
    Completed,
    /// Process ended with no exit code (e.g. killed by a signal) - try the next
    /// candidate.
    Aborted,
}

/// Classify an editor subprocess's exit. `code == None` means it ended without
/// an exit code (a signal kill). A pure function so both arms are unit-testable
/// on every platform, independent of whether a real process can produce a
/// code-less status there.
fn classify_editor_exit(success: bool, code: Option<i32>) -> EditorRunOutcome {
    if success || code.is_some() {
        EditorRunOutcome::Completed
    } else {
        EditorRunOutcome::Aborted
    }
}

fn launch_editor(path: &std::path::Path) -> anyhow::Result<()> {
    launch_editor_with(path, &mut |cmd| {
        cmd.status()
            .map(|s| classify_editor_exit(s.success(), s.code()))
    })
}

/// Core of [`launch_editor`], with the actual "run this candidate and get its
/// exit status" step injected as `run` instead of hardcoded to
/// `Command::status()`.
///
/// This seam exists specifically so the final "no editor found" `bail!` below
/// can be exercised deterministically on every platform. On Unix that branch
/// is reachable by starving `$PATH` so even the real `vim`/`nano`/`vi`
/// fallbacks fail to resolve (see the real-subprocess tests below), but there
/// is no safe real-subprocess equivalent on Windows: `Command::new("notepad")`
/// resolves via the `System32` search path that `CreateProcess` consults
/// *before* `$PATH`, so it can't be made to fail short of tampering with a
/// real system directory. Injecting `run` lets a single, platform-independent
/// test force every candidate to fail with `NotFound` without spawning any
/// process at all - proving the `bail!` is reachable production code on
/// every platform, not a permanent gap.
///
/// `run` is `&mut dyn FnMut` rather than `impl FnMut` for the same
/// monomorphization-noise reason documented on
/// [`resolve_task_with`](super::session::resolve_task_with): several test
/// call sites below pass distinct closure literals directly to this
/// function, and a generic parameter would give each one its own
/// instantiation.
fn launch_editor_with(
    path: &std::path::Path,
    run: &mut dyn FnMut(&mut std::process::Command) -> std::io::Result<EditorRunOutcome>,
) -> anyhow::Result<()> {
    use std::process::Command;

    // Resolve editor candidates in priority order
    let mut candidates: Vec<String> = Vec::new();
    if let Ok(v) = std::env::var("VISUAL")
        && !v.is_empty()
    {
        candidates.push(v);
    }
    if let Ok(e) = std::env::var("EDITOR")
        && !e.is_empty()
    {
        candidates.push(e);
    }

    candidates.extend(platform_default_editors());
    let path_str = path.to_string_lossy();

    for editor in &candidates {
        // Handle editor strings that may include flags (e.g. "code --wait")
        let parts: Vec<&str> = editor.split_whitespace().collect();
        if parts.is_empty() {
            continue;
        }

        let mut cmd = Command::new(parts[0]);
        for arg in &parts[1..] {
            cmd.arg(arg);
        }
        cmd.arg(path_str.as_ref());

        match run(&mut cmd) {
            // Exited (even non-zero means the user closed it - treat as OK).
            Ok(EditorRunOutcome::Completed) => {
                return Ok(());
            }
            Ok(EditorRunOutcome::Aborted) => {
                // Ended with no exit code (e.g. killed by signal on Unix) -
                // try the next candidate.
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // Try next candidate
                continue;
            }
            Err(e) => {
                return Err(anyhow::anyhow!(
                    "Failed to launch editor '{}': {}",
                    editor,
                    e
                ));
            }
        }
    }

    anyhow::bail!("No editor found. Set $VISUAL or $EDITOR, or install vim/nano/notepad.")
}

/// Build the list of [`ProviderCreds`] a [`Config`] implies. `ollama` is always
/// present (it needs no key); the API-key providers are included only when their
/// key is configured, and `claude-code` only when explicitly enabled. This is the
/// sole point that reads provider settings out of `Config`.
pub fn provider_creds_from_config(config: &Config) -> Vec<ProviderCreds> {
    let caps = &config.model_capabilities;
    let timeout = config.request_timeout_secs;
    let mut creds = Vec::new();

    let keyed = [
        ("anthropic", config.providers.anthropic_api_key.as_deref()),
        ("openai", config.providers.openai_api_key.as_deref()),
        ("google", config.providers.google_api_key.as_deref()),
        ("openrouter", config.openrouter_api_key.as_deref()),
    ];
    for (name, key) in keyed {
        // A blank key is not a key: `lev setup` writes empty strings for
        // providers the user skipped, and registering one produces a provider
        // that authenticates as nobody and fails at the first call.
        if let Some(key) = key.map(str::trim).filter(|k| !k.is_empty()) {
            creds.push(ProviderCreds {
                name: name.to_string(),
                api_key: Some(key.to_string()),
                base_url: None,
                model_capabilities: caps.clone(),
                request_timeout_secs: timeout,
                rate_limit: config.rate_limits.get(name).cloned(),
                options: std::collections::HashMap::new(),
            });
        }
    }

    // Ollama is always available (no key); carry any configured base URL.
    creds.push(ProviderCreds {
        name: "ollama".to_string(),
        api_key: None,
        base_url: Some(
            config
                .ollama_base_url
                .as_deref()
                .unwrap_or("http://localhost:11434")
                .to_string(),
        ),
        model_capabilities: caps.clone(),
        request_timeout_secs: timeout,
        rate_limit: None,
        options: std::collections::HashMap::new(),
    });

    // Claude Code needs no API key, but it is opt-in rather than always-on: the
    // CLI puts the user's account email address into every call and that cannot
    // be turned off. Leaving it unregistered is also how it stays out of an
    // agent's model fallback chain - `resolve_stage_model` skips any provider
    // the registry doesn't have.
    if config.providers.claude_code_enabled {
        let mut options = std::collections::HashMap::new();
        if let Some(binary) = &config.providers.claude_code_binary {
            options.insert("binary".to_string(), binary.clone());
        }
        if let Some(effort) = &config.providers.claude_code_effort {
            options.insert("effort".to_string(), effort.clone());
        }
        creds.push(ProviderCreds {
            name: "claude-code".to_string(),
            api_key: None,
            base_url: None,
            model_capabilities: caps.clone(),
            request_timeout_secs: None,
            rate_limit: None,
            options,
        });
    }

    creds
}

/// Convenience wrapper: build a [`ProviderRegistry`] straight from a [`Config`].
///
/// Kept as a `fn(&Config) -> ProviderRegistry` so it can be passed as the
/// registry-builder seam that `run`/`models`/`dashboard` inject for tests.
///
/// Native providers are registered eagerly from [`provider_creds_from_config`];
/// a [`ScriptProviderLayer`](leviath_runtime::script_provider::ScriptProviderLayer)
/// is then attached so Rhai *script providers* resolve lazily and
/// hot-reload from `~/.leviath/providers/`.
pub fn build_provider_registry_from_config(config: &Config) -> ProviderRegistry {
    let registry = build_provider_registry(&provider_creds_from_config(config));
    attach_script_layer(registry, crate::config::providers_dir(), config)
}

/// Attach a [`ScriptProviderLayer`](leviath_runtime::script_provider::ScriptProviderLayer)
/// over `dir` (the providers directory) when one is available; otherwise return
/// the registry unchanged. Split out so both the with-dir and no-home paths are
/// unit-testable.
fn attach_script_layer(
    registry: ProviderRegistry,
    dir: Option<std::path::PathBuf>,
    config: &Config,
) -> ProviderRegistry {
    let Some(dir) = dir else {
        return registry;
    };
    let overrides = config
        .model_providers
        .iter()
        .map(|(name, mp)| (name.clone(), script_provider_spec(mp)))
        .collect();
    let layer = leviath_runtime::script_provider::ScriptProviderLayer::new(
        dir,
        overrides,
        config.model_capabilities.clone(),
        config.request_timeout_secs,
        config.security.allow_env_vars.clone(),
    );
    registry.with_script_layer(std::sync::Arc::new(layer))
}

/// Translate a CLI [`ModelProviderConfig`](crate::config::ModelProviderConfig)
/// into the runtime's plain-data
/// [`ScriptProviderSpec`](leviath_runtime::script_provider::ScriptProviderSpec):
/// `base_url`/`api_key`/extra keys become the `initialize(config)` map.
fn script_provider_spec(
    mp: &crate::config::ModelProviderConfig,
) -> leviath_runtime::script_provider::ScriptProviderSpec {
    let mut cfg = serde_json::Map::new();
    if let Some(b) = &mp.base_url {
        cfg.insert("base_url".to_string(), serde_json::Value::String(b.clone()));
    }
    if let Some(k) = &mp.api_key {
        cfg.insert("api_key".to_string(), serde_json::Value::String(k.clone()));
    }
    for (k, v) in &mp.extra {
        cfg.insert(
            k.clone(),
            serde_json::to_value(v).unwrap_or(serde_json::Value::Null),
        );
    }
    leviath_runtime::script_provider::ScriptProviderSpec {
        script: mp.script.clone(),
        rate_limit: mp.rate_limit.clone(),
        init_config: serde_json::Value::Object(cfg),
    }
}

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

    /// Shared "stdin is never a TTY" probe for the `resolve_task` tests whose
    /// argument is `Some(..)` (so the probe is never consulted) or that
    /// explicitly want the non-TTY error path. A single named `fn` (rather than
    /// a fresh `|| false` closure per call site) keeps every call site sharing
    /// one instantiation and one covered region.
    fn never_a_tty() -> bool {
        false
    }

    /// Shared `assert!`-with-dynamic-message helper: several `launch_editor`
    /// success tests assert `result.is_ok()` while formatting the actual
    /// result into the panic message for diagnostics if the assertion ever
    /// fails. The panic-message formatting is only evaluated on failure,
    /// which otherwise leaves it permanently uncovered by `cargo llvm-cov`.
    /// Extracted once here (rather than per call site) and exercised below
    /// via `#[should_panic]`.
    fn assert_launch_ok(result: &anyhow::Result<()>) {
        assert!(result.is_ok(), "expected Ok, got {:?}", result);
    }

    #[test]
    #[should_panic(expected = "expected Ok, got Err(boom)")]
    fn assert_launch_ok_panics_when_err() {
        assert_launch_ok(&Err(anyhow::anyhow!("boom")));
    }

    // ─── read_region_value ────────────────────────────────────────────────

    #[test]
    fn read_region_value_literal_passthrough() {
        assert_eq!(read_region_value("just text").unwrap(), "just text");
    }

    #[test]
    fn read_region_value_at_path_reads_and_trims() {
        let dir = std::env::temp_dir().join("lev-test-region-value");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("r.md");
        std::fs::write(&file, "  hello region  \n").unwrap();
        let raw = format!("@{}", file.to_string_lossy());
        assert_eq!(read_region_value(&raw).unwrap(), "hello region");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn read_region_value_at_missing_file_errors() {
        let err = read_region_value("@/no/such/region/file.md").unwrap_err();
        assert!(err.to_string().contains("Failed to read region file"));
    }

    #[test]
    fn read_region_value_at_empty_file_errors() {
        let dir = std::env::temp_dir().join("lev-test-region-empty");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("empty.md");
        std::fs::write(&file, "   \n").unwrap();
        let raw = format!("@{}", file.to_string_lossy());
        let err = read_region_value(&raw).unwrap_err();
        assert!(err.to_string().contains("is empty"));
        std::fs::remove_dir_all(&dir).ok();
    }

    // ─── platform_default_editors ─────────────────────────────────────────

    #[cfg(windows)]
    #[test]
    fn platform_default_editors_includes_notepad() {
        assert_eq!(platform_default_editors(), vec!["notepad".to_string()]);
    }

    #[cfg(unix)]
    #[test]
    fn platform_default_editors_includes_vim_nano_vi() {
        assert_eq!(
            platform_default_editors(),
            vec!["vim".to_string(), "nano".to_string(), "vi".to_string()]
        );
    }

    #[test]
    fn resolve_task_with_literal_string() {
        let result = resolve_task(
            &Some("do something".to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "do something");
    }

    #[test]
    fn resolve_task_with_file_path() {
        let dir = std::env::temp_dir().join("lev-test-resolve-task");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("task.txt");
        std::fs::write(&file, "task from file\n").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "task from file");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_task_with_empty_file_errors() {
        let dir = std::env::temp_dir().join("lev-test-resolve-empty");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("empty.txt");
        std::fs::write(&file, "   \n  ").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_task_nonexistent_file_used_as_literal() {
        let result = resolve_task(
            &Some("/nonexistent/path/do_something".to_string()),
            "test",
            None,
            &never_a_tty,
        );
        // Path doesn't exist as a file, so it's treated as a literal string
        assert_eq!(result.unwrap(), "/nonexistent/path/do_something");
    }

    #[test]
    fn resolve_task_file_with_whitespace_only_errors() {
        let dir = std::env::temp_dir().join("lev-test-resolve-ws");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("whitespace.txt");
        std::fs::write(&file, "   \n\t\n  \n").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_task_file_trims_content() {
        let dir = std::env::temp_dir().join("lev-test-resolve-trim");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("trimme.txt");
        std::fs::write(&file, "  hello world  \n\n").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "hello world");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_task_preserves_literal_string_as_is() {
        let result = resolve_task(
            &Some("  spaces around  ".to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "  spaces around  ");
    }

    #[test]
    fn build_provider_registry_with_empty_config() {
        let config = Config::default();
        let registry = build_provider_registry_from_config(&config);
        // Ollama needs no key and is always on.
        assert!(registry.has("ollama"));
        // Claude Code needs no key either, but is opt-in - a default config
        // must not reach the user's Claude subscription (or send their account
        // email to it) without them having said yes.
        assert!(!registry.has("claude-code"));
        // Should NOT have anthropic, openai, google without keys
        assert!(!registry.has("anthropic"));
        assert!(!registry.has("openai"));
        assert!(!registry.has("google"));
    }

    #[test]
    fn build_provider_registry_with_anthropic_key() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-test-key-12345".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("anthropic"));
    }

    #[test]
    fn build_provider_registry_with_openai_key() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                openai_api_key: Some("sk-test-key-12345".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("openai"));
    }

    #[test]
    fn build_provider_registry_with_google_key() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                google_api_key: Some("AIzatest12345".to_string()),
                claude_code_enabled: false,
                claude_code_binary: None,
                claude_code_effort: None,
                ..Config::default().providers
            },
            ..Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("google"));
    }

    #[test]
    fn build_provider_registry_with_openrouter_key() {
        let config = Config {
            openrouter_api_key: Some("sk-or-test-12345".to_string()),
            ..Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("openrouter"));
    }

    #[test]
    fn build_provider_registry_custom_ollama_url() {
        let config = Config {
            ollama_base_url: Some("http://my-server:11434".to_string()),
            ..Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("ollama"));
    }

    #[test]
    fn script_provider_spec_assembles_init_config() {
        let mut extra = std::collections::HashMap::new();
        extra.insert("region".to_string(), toml::Value::String("us".to_string()));
        let mp = crate::config::ModelProviderConfig {
            script: Some("groq".to_string()),
            api_key: Some("k".to_string()),
            base_url: Some("http://api".to_string()),
            rate_limit: Some(leviath_providers::RateLimitConfig {
                requests_per_minute: 30,
                tokens_per_minute: 1000,
            }),
            extra,
        };
        let spec = script_provider_spec(&mp);
        assert_eq!(spec.script.as_deref(), Some("groq"));
        assert!(spec.rate_limit.is_some());
        assert_eq!(spec.init_config["base_url"], "http://api");
        assert_eq!(spec.init_config["api_key"], "k");
        assert_eq!(spec.init_config["region"], "us");
    }

    #[test]
    fn attach_script_layer_without_home_is_a_noop() {
        // No providers directory (no resolvable home) → registry unchanged, no
        // script provider resolves.
        let registry = attach_script_layer(ProviderRegistry::new(), None, &Config::default());
        assert!(!registry.has("groq"));
    }

    #[test]
    fn build_registry_resolves_a_configured_script_provider() {
        let home = tempfile::tempdir().unwrap();
        let providers = home.path().join(".leviath").join("providers");
        std::fs::create_dir_all(&providers).unwrap();
        std::fs::write(
            providers.join("groq.rhai"),
            "fn initialize(config) { #{} }\nfn inference(state, request) { #{ content: \"ok\" } }",
        )
        .unwrap();

        let mut model_providers = std::collections::HashMap::new();
        model_providers.insert(
            "groq".to_string(),
            crate::config::ModelProviderConfig::default(),
        );
        let config = Config {
            model_providers,
            ..Config::default()
        };
        temp_env::with_var("LEVIATH_HOME", Some(home.path().as_os_str()), || {
            let registry = build_provider_registry_from_config(&config);
            assert!(registry.has("groq"));
            assert!(registry.get("groq").is_some());
        });
    }

    // ─── build_provider_registry with all keys ──────────────────────────

    #[test]
    fn build_provider_registry_all_keys_set() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-test".to_string()),
                openai_api_key: Some("sk-test".to_string()),
                google_api_key: Some("AIza-test".to_string()),
                claude_code_enabled: false,
                claude_code_binary: None,
                claude_code_effort: None,
            },
            openrouter_api_key: Some("sk-or-test".to_string()),
            ollama_base_url: Some("http://custom:11434".to_string()),
            ..Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("anthropic"));
        assert!(registry.has("openai"));
        assert!(registry.has("google"));
        assert!(registry.has("openrouter"));
        assert!(registry.has("ollama"));
        // Every key in the world doesn't enable Claude Code - only opting in does.
        assert!(!registry.has("claude-code"));
    }

    // ─── ProviderCreds seam ─────────────────────────────────────────────

    #[test]
    fn provider_creds_from_config_includes_defaults_and_keyed() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant".to_string()),
                ..Config::default().providers
            },
            ollama_base_url: Some("http://custom:11434".to_string()),
            ..Config::default()
        };
        let creds = provider_creds_from_config(&config);
        let names: Vec<&str> = creds.iter().map(|c| c.name.as_str()).collect();
        // anthropic (keyed) + ollama, but not openai/google/openrouter, and not
        // claude-code (opt-in, not enabled here).
        assert!(names.contains(&"anthropic"));
        assert!(names.contains(&"ollama"));
        assert!(!names.contains(&"claude-code"));
        assert!(!names.contains(&"openai"));
        assert!(!names.contains(&"google"));
        assert!(!names.contains(&"openrouter"));
        // The ollama base URL is carried through.
        let ollama = creds.iter().find(|c| c.name == "ollama").unwrap();
        assert_eq!(ollama.base_url.as_deref(), Some("http://custom:11434"));
        assert!(ollama.api_key.is_none());
    }

    /// `lev setup` writes an empty string for a provider the user skipped, so
    /// a blank key must not register one: doing so produced a provider that
    /// authenticates as nobody and fails at the first call, and it crowded out
    /// the provider the user actually configured.
    #[test]
    fn provider_creds_from_config_ignores_blank_keys() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some(String::new()),
                openai_api_key: Some("   ".to_string()),
                google_api_key: Some("AIza-real".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };
        let creds = provider_creds_from_config(&config);
        let names: Vec<&str> = creds.iter().map(|c| c.name.as_str()).collect();
        assert!(
            names.contains(&"google"),
            "the configured provider must register: {names:?}"
        );
        assert!(!names.contains(&"anthropic"), "empty key must not register");
        assert!(
            !names.contains(&"openai"),
            "whitespace-only key must not register"
        );
    }

    #[test]
    fn provider_creds_from_config_carries_rate_limits() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant".to_string()),
                openai_api_key: Some("sk-oa".to_string()),
                ..Config::default().providers
            },
            rate_limits: std::collections::HashMap::from([(
                "anthropic".to_string(),
                leviath_providers::RateLimitConfig {
                    requests_per_minute: 50,
                    tokens_per_minute: 40_000,
                },
            )]),
            ..Config::default()
        };
        let creds = provider_creds_from_config(&config);
        let anthropic = creds.iter().find(|c| c.name == "anthropic").unwrap();
        assert_eq!(
            anthropic.rate_limit.as_ref().map(|r| r.requests_per_minute),
            Some(50)
        );
        // A provider without a [rate_limits.<name>] entry stays unthrottled.
        let openai = creds.iter().find(|c| c.name == "openai").unwrap();
        assert!(openai.rate_limit.is_none());
    }

    // ─── resolve_task: multiline file content ───────────────────────────

    #[test]
    fn resolve_task_multiline_file() {
        let dir = std::env::temp_dir().join("lev-test-resolve-multiline");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("multi.txt");
        std::fs::write(&file, "line one\nline two\nline three\n").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "test",
            None,
            &never_a_tty,
        );
        let task = result.unwrap();
        assert!(task.contains("line one"));
        assert!(task.contains("line two"));
        assert!(task.contains("line three"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ─── resolve_task: literal string with special chars ────────────────

    #[test]
    fn resolve_task_literal_with_special_chars() {
        let result = resolve_task(
            &Some("Write a function that does X & Y <html>".to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "Write a function that does X & Y <html>");
    }

    // ─── build_provider_registry: no providers except defaults ──────────

    #[test]
    fn build_provider_registry_defaults_have_ollama_only() {
        let config = Config::default();
        let registry = build_provider_registry_from_config(&config);
        // Ollama is present regardless of key configuration; claude-code is not,
        // until the user opts in.
        assert!(registry.has("ollama"));
        assert!(!registry.has("claude-code"));
    }

    #[test]
    fn enabling_claude_code_registers_it_with_its_options() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                claude_code_enabled: true,
                claude_code_binary: Some("/opt/bin/claude".to_string()),
                claude_code_effort: Some("low".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };
        let creds = provider_creds_from_config(&config);
        let cc = creds
            .iter()
            .find(|c| c.name == "claude-code")
            .expect("enabled ⇒ present");
        assert_eq!(
            cc.options.get("binary").map(String::as_str),
            Some("/opt/bin/claude")
        );
        assert_eq!(cc.options.get("effort").map(String::as_str), Some("low"));
        assert!(cc.api_key.is_none());
        assert!(build_provider_registry_from_config(&config).has("claude-code"));
    }

    #[test]
    fn enabling_claude_code_without_options_carries_none() {
        let config = Config {
            providers: crate::config::ProviderConfig {
                claude_code_enabled: true,
                ..Config::default().providers
            },
            ..Config::default()
        };
        let creds = provider_creds_from_config(&config);
        let cc = creds.iter().find(|c| c.name == "claude-code").unwrap();
        // Absent settings stay absent so the provider applies its own defaults
        // (the `claude` binary on PATH, DEFAULT_EFFORT).
        assert!(cc.options.is_empty());
    }

    // ─── resolve_task: file with only comments in editor-like format ────

    #[test]
    fn resolve_task_literal_empty_string() {
        // Empty string is treated as literal, returns as-is
        let result = resolve_task(&Some("".to_string()), "test", None, &never_a_tty);
        assert_eq!(result.unwrap(), "");
    }

    // ─── resolve_task: file with multiple lines and trailing whitespace ──

    #[test]
    fn resolve_task_file_with_multiple_trailing_newlines() {
        let dir = std::env::temp_dir().join("lev-test-resolve-trail");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("trail.txt");
        std::fs::write(&file, "task content\n\n\n\n").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "test",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "task content");

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ─── build_provider_registry: model_capabilities propagated ──────────

    #[test]
    fn build_provider_registry_propagates_model_capabilities() {
        use leviath_providers::ModelCapabilities;
        let mut caps = std::collections::HashMap::new();
        caps.insert(
            "custom-model".to_string(),
            ModelCapabilities {
                supports_temperature: true,
                supports_streaming: true,
                supports_tools: true,
                supports_system_prompt: true,
                max_context_tokens: 9999,
                max_output_tokens: 999,
            },
        );
        let config = crate::config::Config {
            model_capabilities: caps,
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-test".to_string()),
                openai_api_key: None,
                google_api_key: None,
                claude_code_enabled: false,
                claude_code_binary: None,
                claude_code_effort: None,
            },
            ..crate::config::Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        // Verify anthropic provider was registered
        assert!(registry.has("anthropic"));
        // Verify ollama always registered
        assert!(registry.has("ollama"));
    }

    // ─── launch_editor: candidates exhausted when no editors available ────

    #[test]
    fn resolve_task_file_with_real_content() {
        let dir = std::env::temp_dir().join("lev-test-resolve-real");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("real.txt");
        std::fs::write(&file, "Implement a REST API server\nwith authentication\n").unwrap();

        let result = resolve_task(
            &Some(file.to_str().unwrap().to_string()),
            "api-agent",
            Some("API agent"),
            &never_a_tty,
        );
        let task = result.unwrap();
        assert!(task.contains("Implement a REST API server"));
        assert!(task.contains("with authentication"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ─── build_provider_registry: all providers registered ───────────────

    #[test]
    fn build_provider_registry_ollama_with_custom_url_propagates_caps() {
        use leviath_providers::ModelCapabilities;
        let mut caps = std::collections::HashMap::new();
        caps.insert(
            "llama3-8b".to_string(),
            ModelCapabilities {
                supports_temperature: false,
                supports_streaming: false,
                supports_tools: false,
                supports_system_prompt: false,
                max_context_tokens: 99,
                max_output_tokens: 99,
            },
        );
        let config = crate::config::Config {
            ollama_base_url: Some("http://custom-ollama:11434".to_string()),
            model_capabilities: caps,
            ..crate::config::Config::default()
        };
        let registry = build_provider_registry_from_config(&config);
        assert!(registry.has("ollama"));
    }

    // ─── resolve_task: None arg, non-TTY stdin ───────────────────────────

    #[test]
    fn resolve_task_none_arg_errors_when_stdin_not_tty() {
        // The TTY check is injected (not the real std::io::stdin()) so this
        // is deterministic regardless of whether the test runner's own
        // stdin happens to be a real terminal - a human running `cargo test`
        // interactively has a real TTY on stdin, unlike CI, so hardcoding
        // "stdin is never a TTY under cargo test" was a false assumption.
        let result = resolve_task_with(&None, "test-agent", None, &|| false);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("No task provided"));
        assert!(msg.contains("stdin is not a TTY"));
    }

    #[test]
    fn resolve_task_none_arg_uses_injected_probe_via_public_wrapper() {
        // Smoke test that the public `resolve_task()` wrapper still compiles
        // and delegates to `resolve_task_with` with the caller-supplied probe.
        // A literal task never consults the probe, so the outcome is
        // deterministic regardless of environment.
        let result = resolve_task(
            &Some("literal task".to_string()),
            "test-agent",
            None,
            &never_a_tty,
        );
        assert_eq!(result.unwrap(), "literal task");
    }

    #[test]
    fn resolve_task_none_arg_errors_via_public_wrapper_when_not_a_tty() {
        // Drives `resolve_task`'s public wrapper with an injected "never a TTY"
        // probe: no task + not-a-TTY hits the "no task provided" error,
        // cross-platform, without touching real stdin or launching an editor.
        let result = resolve_task(&None, "test-agent", None, &never_a_tty);
        assert!(result.is_err());
    }

    // ─── launch_editor: VISUAL takes priority and succeeds ───────────────

    // These `launch_editor` tests point VISUAL/EDITOR at `/usr/bin/true` (or
    // rely on PATH-starvation to prevent any editor being found) - both
    // assumptions are Unix-only. On Windows, `/usr/bin/true` doesn't exist,
    // so the NotFound-branch falls through to the windows-only "notepad"
    // candidate, which Windows resolves via its System32 search path
    // *regardless* of $PATH - so PATH-starvation doesn't stop it either.
    // Either way that means launching a real, blocking GUI text editor with
    // no timeout, which hung a Windows CI run indefinitely. Gated to `unix`.
    #[cfg(unix)]
    #[test]
    fn launch_editor_visual_env_success() {
        temp_env::with_vars(
            [("VISUAL", Some("/usr/bin/true")), ("EDITOR", None)],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-visual");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: EDITOR used when VISUAL unset ────────────────────

    #[cfg(unix)]
    #[test]
    fn launch_editor_editor_env_success() {
        temp_env::with_vars(
            [("VISUAL", None), ("EDITOR", Some("/usr/bin/true"))],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-editor");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: exit code (even non-zero) is treated as success ──

    #[cfg(unix)]
    #[test]
    fn launch_editor_nonzero_exit_still_ok() {
        temp_env::with_vars(
            [("VISUAL", Some("/usr/bin/false")), ("EDITOR", None)],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-nonzero");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                // A non-zero-but-present exit code is treated as the user having
                // closed the editor - not an error.
                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: terminated by signal (no exit code) tries next ───

    #[test]
    fn classify_editor_exit_success_is_completed() {
        assert_eq!(
            classify_editor_exit(true, Some(0)),
            EditorRunOutcome::Completed
        );
    }

    #[test]
    fn classify_editor_exit_nonzero_code_is_completed() {
        // Non-zero but present exit code = user closed the editor = done.
        assert_eq!(
            classify_editor_exit(false, Some(1)),
            EditorRunOutcome::Completed
        );
    }

    #[test]
    fn classify_editor_exit_no_code_is_aborted() {
        // No exit code (e.g. killed by a Unix signal) = try the next candidate.
        // Exercised here as a pure function so it's covered on every platform,
        // including Windows where a real `ExitStatus` always carries a code.
        assert_eq!(classify_editor_exit(false, None), EditorRunOutcome::Aborted);
    }

    #[test]
    fn launch_editor_with_aborted_candidate_falls_through_to_next() {
        // An injected `run` reporting `Aborted` exercises the `Ok(Aborted) => {}`
        // arm (try the next candidate) on every platform, without needing a real
        // signal-killed subprocess (which can't be fabricated on Windows). With
        // every candidate aborting, the loop exhausts them and bails.
        temp_env::with_vars(
            [("VISUAL", Some("editor-a")), ("EDITOR", Some("editor-b"))],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-aborted");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let mut calls = 0;
                let result = launch_editor_with(&file, &mut |_cmd| {
                    calls += 1;
                    Ok(EditorRunOutcome::Aborted)
                });
                // Every candidate "ran" but aborted, so it tried them all then bailed.
                assert!(result.is_err());
                assert!(calls >= 2, "expected multiple candidates to be tried");

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: command with flags is split correctly ────────────

    #[cfg(unix)]
    #[test]
    fn launch_editor_command_with_flags_splits_correctly() {
        // `/usr/bin/true` ignores all arguments, so appending a flag
        // and the file path is harmless; this exercises the
        // whitespace-splitting logic for editor strings like
        // "code --wait".
        temp_env::with_vars(
            [
                ("VISUAL", Some("/usr/bin/true --some-flag")),
                ("EDITOR", None),
            ],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-flags");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: whitespace-only VISUAL falls through, EDITOR used ─

    #[cfg(unix)]
    #[test]
    fn launch_editor_whitespace_only_visual_falls_through_to_editor() {
        // Whitespace-only string is non-empty so it IS pushed as a
        // candidate, but splitting on whitespace yields an empty parts
        // vec, which triggers the `continue` branch.
        temp_env::with_vars(
            [("VISUAL", Some("   ")), ("EDITOR", Some("/usr/bin/true"))],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-ws-visual");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor_with: truly-empty VISUAL/EDITOR, injected (cross-platform) ─

    /// Exercises the `!v.is_empty()`/`!e.is_empty()` false arm (empty-string
    /// `VISUAL`/`EDITOR` never gets pushed onto the candidates list) the same
    /// way the "no editor found" test above closes the Windows gap: via the
    /// injected `run` seam instead of PATH-starvation.
    ///
    /// The Unix test below needs PATH-starvation only to keep an
    /// empty-VISUAL/EDITOR fallthrough to the real `vim`/`nano`/`vi`
    /// platform defaults from actually launching a real, blocking editor --
    /// it isn't inherent to the branch itself. That real-editor risk doesn't
    /// exist here: `run` never spawns anything real regardless of which
    /// candidate string `launch_editor_with` resolved to, so this needs no
    /// PATH manipulation (and thus no `PATH_ENV_LOCK`) at all. Re-spawning
    /// the current test binary (rather than fabricating a `std::process::
    /// ExitStatus` directly, which has no portable stable constructor) gives
    /// a real, immediate, always-terminates `ExitStatus` on every platform --
    /// same technique `commands::serve::agents` uses to get a real child
    /// process without depending on what it actually does.
    #[test]
    fn launch_editor_with_empty_visual_and_editor_are_skipped() {
        temp_env::with_vars([("VISUAL", Some("")), ("EDITOR", Some(""))], || {
            let dir = std::env::temp_dir().join("lev-test-launch-editor-with-empty-skip");
            let _ = std::fs::create_dir_all(&dir);
            let file = dir.join("edit.txt");
            std::fs::write(&file, "content").unwrap();

            let result = launch_editor_with(&file, &mut |_cmd| {
                // Ignores the actual candidate `launch_editor_with` resolved to
                // (the platform default, since VISUAL/EDITOR are both empty) and
                // spawns the current test binary instead - any exit status it
                // produces (even a nonzero "unrecognized option" error) classifies
                // as `Completed`.
                std::process::Command::new(std::env::current_exe().unwrap())
                    .arg("--this-flag-does-not-exist")
                    .status()
                    .map(|s| classify_editor_exit(s.success(), s.code()))
            });
            assert_launch_ok(&result);

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    // ─── launch_editor: truly-empty VISUAL/EDITOR are skipped entirely ────

    // Unlike the whitespace-only case above (non-empty string, pushed as a
    // candidate that then fails to split into any usable parts), a truly
    // empty `VISUAL`/`EDITOR` value never even gets pushed onto the
    // candidates list - exercising the `!v.is_empty()`/`!e.is_empty()`
    // false arm for both. With both vars empty, resolution falls through to
    // the unix platform defaults (vim/nano/vi) unless PATH is also starved --
    // so this test combines the empty-string case with the same
    // PATH-starvation trick as `launch_editor_no_editor_found_when_path_has_no_candidates`
    // below, guaranteeing a deterministic `Err` instead of ever risking a
    // real, blocking, interactive editor launch. Kept as extra real-PATH
    // insurance on Unix alongside the injected-seam version above, which is
    // what actually closes the Windows gap for this branch.
    #[cfg(unix)]
    #[test]
    fn launch_editor_empty_visual_and_editor_are_skipped() {
        temp_env::with_vars(
            [
                ("VISUAL", Some("")),
                ("EDITOR", Some("")),
                ("PATH", Some("/lev-definitely-empty-path-dir")),
            ],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-empty-visual-editor");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                // Neither empty var is pushed as a candidate, and PATH starvation
                // means even the unix platform defaults (vim/nano/vi) fail to
                // resolve - so this deterministically reaches "no editor found"
                // rather than ever spawning a real editor.
                let result = launch_editor(&file);
                assert!(result.is_err());
                assert!(result.unwrap_err().to_string().contains("No editor found"));

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: NotFound candidate is skipped, next one used ─────

    #[cfg(unix)]
    #[test]
    fn launch_editor_not_found_candidate_falls_through_to_next() {
        // VISUAL points at a nonexistent binary, which should be
        // skipped (NotFound branch, `continue`) in favor of EDITOR.
        temp_env::with_vars(
            [
                ("VISUAL", Some("lev-definitely-not-a-real-binary-xyz")),
                ("EDITOR", Some("/usr/bin/true")),
            ],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-notfound");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: non-NotFound spawn error propagates ──────────────

    #[cfg(unix)]
    #[test]
    fn launch_editor_permission_denied_returns_error() {
        use std::os::unix::fs::PermissionsExt;

        let dir = std::env::temp_dir().join("lev-test-launch-editor-perm-denied");
        let _ = std::fs::create_dir_all(&dir);
        // A regular, non-executable file: spawning it directly fails with
        // `PermissionDenied`, not `NotFound` - exercising the generic
        // `Err(e)` arm (as opposed to the `NotFound` "try next candidate"
        // arm already covered above).
        let not_executable = dir.join("not-executable");
        std::fs::write(&not_executable, "not a script").unwrap();
        let mut perms = std::fs::metadata(&not_executable).unwrap().permissions();
        perms.set_mode(0o600);
        std::fs::set_permissions(&not_executable, perms).unwrap();

        temp_env::with_vars(
            [("VISUAL", Some(&not_executable)), ("EDITOR", None)],
            || {
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert!(result.is_err());
                assert!(
                    result
                        .unwrap_err()
                        .to_string()
                        .contains("Failed to launch editor")
                );

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor_with: no candidate resolves (injected, cross-platform) ─

    /// Exercises the final `bail!("No editor found...")` in
    /// [`launch_editor_with`] via the injected `run` seam rather than real
    /// PATH/filesystem state - see the doc comment on `launch_editor_with`
    /// for why that matters on Windows specifically (real PATH-starvation
    /// can't fail `Command::new("notepad")`, which resolves via `System32`
    /// unconditionally). Forcing every candidate to fail with `NotFound`
    /// here doesn't depend on the platform at all: no real process is ever
    /// spawned, so this runs identically - and actually proves the `bail!`
    /// line is reachable production code - on Unix, Windows, and macOS
    /// alike. Doesn't need `ENV_LOCK`/`PATH_ENV_LOCK`: whatever `$VISUAL`/
    /// `$EDITOR` happen to be set to by a concurrently-running test is
    /// irrelevant, since the injected closure fails every candidate the same
    /// way regardless of its name.
    #[test]
    fn launch_editor_with_no_editor_found_when_every_candidate_not_found() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-with-no-editor");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("edit.txt");
        std::fs::write(&file, "content").unwrap();

        let result = launch_editor_with(&file, &mut |_cmd| {
            Err(std::io::Error::from(std::io::ErrorKind::NotFound))
        });
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No editor found"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ─── launch_editor: no candidate resolves anywhere on PATH ────────────

    // Windows resolves "notepad" via the System32 search path regardless of
    // $PATH, so PATH-starvation can't produce a "no editor found" outcome
    // there the way it does on Unix (breaking PATH so vim/nano/vi can't
    // resolve) - gated to `unix` for the same real-blocking-editor-hang
    // reason as the tests above. Kept alongside
    // `launch_editor_with_no_editor_found_when_every_candidate_not_found`
    // above as extra real-subprocess insurance on Unix; the injected-seam
    // test is what actually closes the Windows gap.
    #[cfg(unix)]
    #[test]
    fn launch_editor_no_editor_found_when_path_has_no_candidates() {
        // No VISUAL/EDITOR (both unset), and PATH points nowhere - so even
        // the unix platform-default candidates (vim/nano/vi) all fail to
        // resolve.
        temp_env::with_vars(
            [
                ("VISUAL", None),
                ("EDITOR", None),
                ("PATH", Some("/lev-definitely-empty-path-dir")),
            ],
            || {
                let dir = std::env::temp_dir().join("lev-test-launch-editor-no-editor");
                let _ = std::fs::create_dir_all(&dir);
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert!(result.is_err());
                assert!(result.unwrap_err().to_string().contains("No editor found"));

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── launch_editor: Windows twin suite ────────────────────────────────
    //
    // Windows can't reuse the Unix tests above verbatim: `/usr/bin/true` /
    // `/usr/bin/false` don't exist, shebang scripts can't execute (`os error
    // 193`), and Unix permission bits (`PermissionsExt`) don't apply. Batch
    // (`.bat`) files stand in for the shebang scripts - they're directly
    // executable via `Command::new(path)` on Windows, exit instantly, and
    // never touch a real interactive editor.
    //
    // The "editor ended with no exit code" case (killed by a Unix signal) is a
    // Windows testability challenge: on Windows `ExitStatus::code()` is always
    // `Some(_)` (even via `ExitStatusExt::from_raw`), so no real or fabricated
    // status reaches the "try next candidate" arm there. The injected `run`
    // seam returns `EditorRunOutcome` rather than `ExitStatus`: the
    // status-to-outcome decision lives in the pure `classify_editor_exit`
    // (unit-tested for the code-less case on every platform), and the
    // "outcome == Aborted, try next" arm is driven directly via injection in
    // `launch_editor_with_aborted_candidate_falls_through_to_next` - both
    // cross-platform, no code-less `ExitStatus` required.
    //
    // Three other Unix tests rely on PATH-starvation --
    // `launch_editor_empty_visual_and_editor_are_skipped`,
    // `launch_editor_no_editor_found_when_path_has_no_candidates`, and
    // `resolve_task_with_editor_path_propagates_launch_editor_error`.
    // PATH-starvation has no safe Windows equivalent: `Command::new("notepad")`
    // resolves via `System32` unconditionally before consulting `$PATH`, so
    // PATH-starvation can't make it fail there. Instead, injecting the "run
    // this candidate" step itself (`launch_editor_with`'s `run` parameter) or
    // the "launch the editor" step (`resolve_task_with_editor`'s
    // `launch_editor_fn` parameter) sidesteps real process resolution
    // entirely, closing all three gaps on every platform - see
    // `launch_editor_with_no_editor_found_when_every_candidate_not_found`,
    // `launch_editor_with_empty_visual_and_editor_are_skipped`, and
    // `resolve_task_with_editor_injected_editor_failure_propagates` above.

    #[cfg(windows)]
    fn write_bat(path: &std::path::Path, body: &str) {
        std::fs::write(path, format!("@echo off\r\n{}\r\n", body)).unwrap();
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_visual_env_success() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-visual-win");
        let _ = std::fs::create_dir_all(&dir);
        let ok_bat = dir.join("ok.bat");
        write_bat(&ok_bat, "exit /b 0");

        temp_env::with_vars([("VISUAL", Some(&ok_bat)), ("EDITOR", None)], || {
            let file = dir.join("edit.txt");
            std::fs::write(&file, "content").unwrap();

            let result = launch_editor(&file);
            assert_launch_ok(&result);

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_editor_env_success() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-editor-win");
        let _ = std::fs::create_dir_all(&dir);
        let ok_bat = dir.join("ok.bat");
        write_bat(&ok_bat, "exit /b 0");

        temp_env::with_vars([("VISUAL", None), ("EDITOR", Some(&ok_bat))], || {
            let file = dir.join("edit.txt");
            std::fs::write(&file, "content").unwrap();

            let result = launch_editor(&file);
            assert_launch_ok(&result);

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_nonzero_exit_still_ok() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-nonzero-win");
        let _ = std::fs::create_dir_all(&dir);
        let fail_bat = dir.join("fail.bat");
        write_bat(&fail_bat, "exit /b 1");

        temp_env::with_vars([("VISUAL", Some(&fail_bat)), ("EDITOR", None)], || {
            let file = dir.join("edit.txt");
            std::fs::write(&file, "content").unwrap();

            // A non-zero-but-present exit code is treated as the user having
            // closed the editor - not an error.
            let result = launch_editor(&file);
            assert_launch_ok(&result);

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_command_with_flags_splits_correctly() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-flags-win");
        let _ = std::fs::create_dir_all(&dir);
        let ok_bat = dir.join("ok.bat");
        write_bat(&ok_bat, "exit /b 0");

        // The batch file ignores all arguments, so appending a flag and
        // the file path is harmless; this exercises the
        // whitespace-splitting logic for editor strings like
        // "code --wait".
        temp_env::with_vars(
            [
                ("VISUAL", Some(format!("{} --some-flag", ok_bat.display()))),
                ("EDITOR", None),
            ],
            || {
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_whitespace_only_visual_falls_through_to_editor() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-ws-visual-win");
        let _ = std::fs::create_dir_all(&dir);
        let ok_bat = dir.join("ok.bat");
        write_bat(&ok_bat, "exit /b 0");

        // Whitespace-only string is non-empty so it IS pushed as a
        // candidate, but splitting on whitespace yields an empty parts
        // vec, which triggers the `continue` branch.
        temp_env::with_vars(
            [
                ("VISUAL", Some(std::ffi::OsString::from("   "))),
                ("EDITOR", Some(ok_bat.clone().into_os_string())),
            ],
            || {
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_not_found_candidate_falls_through_to_next() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-notfound-win");
        let _ = std::fs::create_dir_all(&dir);
        let ok_bat = dir.join("ok.bat");
        write_bat(&ok_bat, "exit /b 0");

        // VISUAL points at a nonexistent binary, which should be
        // skipped (NotFound branch, `continue`) in favor of EDITOR.
        temp_env::with_vars(
            [
                (
                    "VISUAL",
                    Some(std::ffi::OsString::from(
                        "lev-definitely-not-a-real-binary-xyz",
                    )),
                ),
                ("EDITOR", Some(ok_bat.clone().into_os_string())),
            ],
            || {
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert_launch_ok(&result);

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    #[cfg(windows)]
    #[test]
    fn launch_editor_permission_denied_returns_error() {
        let dir = std::env::temp_dir().join("lev-test-launch-editor-perm-denied-win");
        let _ = std::fs::create_dir_all(&dir);
        // A plain, non-executable text file: Windows' `CreateProcess` can't
        // recognize it as an executable image and fails with
        // `ERROR_BAD_EXE_FORMAT` (os error 193), not `NotFound` - exercising
        // the generic `Err(e)` arm (as opposed to the `NotFound` "try next
        // candidate" arm already covered above).
        let not_executable = dir.join("not-executable.txt");
        std::fs::write(&not_executable, "not a script").unwrap();

        temp_env::with_vars(
            [("VISUAL", Some(&not_executable)), ("EDITOR", None)],
            || {
                let file = dir.join("edit.txt");
                std::fs::write(&file, "content").unwrap();

                let result = launch_editor(&file);
                assert!(result.is_err());
                assert!(
                    result
                        .unwrap_err()
                        .to_string()
                        .contains("Failed to launch editor")
                );

                let _ = std::fs::remove_dir_all(&dir);
            },
        );
    }

    // ─── resolve_task_with: editor path (stdin is a TTY) ──────────────────

    #[cfg(unix)]
    #[test]
    fn resolve_task_with_editor_path_happy_case() {
        use std::os::unix::fs::PermissionsExt;

        // A tiny "editor" script that appends a non-comment line to
        // whatever file it's invoked on ($1) - standing in for a real
        // interactive editor session.
        let dir = std::env::temp_dir().join("lev-test-resolve-task-editor-happy");
        let _ = std::fs::create_dir_all(&dir);
        let script = dir.join("fake-editor.sh");
        std::fs::write(
            &script,
            "#!/bin/sh\necho \"task body from editor\" >> \"$1\"\n",
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o700);
        std::fs::set_permissions(&script, perms).unwrap();

        temp_env::with_vars([("VISUAL", Some(&script)), ("EDITOR", None)], || {
            let result = resolve_task_with(
                &None,
                "test-agent",
                Some("a non-empty description"),
                &|| true,
            );
            assert_eq!(result.unwrap(), "task body from editor");

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    #[cfg(unix)]
    #[test]
    fn resolve_task_with_editor_path_empty_after_stripping_comments_errors() {
        // /usr/bin/true "opens" the file and does nothing to it, so only the
        // commented-out template remains - stripped down to an empty task.
        temp_env::with_vars(
            [("VISUAL", Some("/usr/bin/true")), ("EDITOR", None)],
            || {
                let result = resolve_task_with(&None, "test-agent", None, &|| true);
                assert!(result.is_err());
                assert!(result.unwrap_err().to_string().contains("Aborting run"));
            },
        );
    }

    // Same Windows PATH-starvation caveat as
    // `launch_editor_no_editor_found_when_path_has_no_candidates` above. Kept
    // as extra real-PATH insurance on Unix alongside the injected-seam
    // version below, which is what actually closes the Windows gap.
    #[cfg(unix)]
    #[test]
    fn resolve_task_with_editor_path_propagates_launch_editor_error() {
        // No VISUAL/EDITOR (both unset), and PATH points nowhere - so even
        // the unix platform-default candidates (vim/nano/vi) all fail to
        // resolve, propagating the "no editor found" error.
        temp_env::with_vars(
            [
                ("VISUAL", None),
                ("EDITOR", None),
                ("PATH", Some("/lev-definitely-empty-path-dir")),
            ],
            || {
                let result = resolve_task_with(&None, "test-agent", None, &|| true);
                assert!(result.is_err());
                assert!(result.unwrap_err().to_string().contains("No editor found"));
            },
        );
    }

    /// Shared stub editor-launcher used by both
    /// `resolve_task_with_editor_injected_editor_failure_propagates` (where
    /// it's actually invoked) and
    /// `resolve_task_with_editor_tmp_file_write_failure_propagates` (where,
    /// by design, `write_task_template`'s earlier `?` should short-circuit
    /// before this is ever reached). Extracted into a single named `fn`
    /// rather than an inline closure per call site so that if the latter
    /// test's control flow ever regresses and this stub *does* get called,
    /// llvm-cov's function-level coverage for it is still merged from the
    /// former test - an inline closure unique to the latter test would
    /// otherwise show up as a brand new "0 calls" function purely because
    /// that particular test is designed to never reach it.
    fn stub_editor_returns_no_editor_found(_path: &std::path::Path) -> anyhow::Result<()> {
        Err(anyhow::anyhow!(
            "No editor found. Set $VISUAL or $EDITOR, or install vim/nano/notepad."
        ))
    }

    /// Cross-platform twin of
    /// `resolve_task_with_editor_path_propagates_launch_editor_error` via
    /// `resolve_task_with_editor`'s injected editor launcher - see that
    /// function's doc comment for why real PATH-starvation can't be mirrored
    /// on Windows here. Doesn't touch `PATH`/`VISUAL`/`EDITOR` at all (no
    /// `ENV_LOCK`/`PATH_ENV_LOCK` needed): the injected closure fails
    /// unconditionally regardless of environment state.
    #[test]
    fn resolve_task_with_editor_injected_editor_failure_propagates() {
        let result = resolve_task_with_editor(
            &None,
            "test-agent",
            None,
            &|| true,
            &stub_editor_returns_no_editor_found,
            &std::env::temp_dir,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No editor found"));
    }

    /// Exercises `write_task_template(&tmp_path, &template)?`'s error path at
    /// its actual call site inside `resolve_task_with_editor` (as opposed to
    /// `write_task_template_error_on_bad_path` below, which calls
    /// `write_task_template` directly). The real OS temp directory used in
    /// production is essentially always writable, so this is only reachable
    /// at all via the injected `tmp_dir_fn` - pointed here at a directory
    /// whose parent doesn't exist, so the write fails deterministically on
    /// both Unix (ENOENT) and Windows (ERROR_PATH_NOT_FOUND) before the
    /// editor launcher is ever reached (if it *were* reached, the assertion
    /// below on the error message would fail, since
    /// `stub_editor_returns_no_editor_found`'s error text differs).
    #[test]
    fn resolve_task_with_editor_tmp_file_write_failure_propagates() {
        let bad_tmp_dir = std::env::temp_dir()
            .join("lev-definitely-nonexistent-parent-dir-for-task-template-xyz")
            .join("nested");
        let result = resolve_task_with_editor(
            &None,
            "test-agent",
            None,
            &|| true,
            &stub_editor_returns_no_editor_found,
            &move || bad_tmp_dir.clone(),
        );
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Failed to create task temp file")
        );
    }

    // ─── resolve_task_with: editor path (stdin is a TTY) - Windows twins ──

    #[cfg(windows)]
    #[test]
    fn resolve_task_with_editor_path_happy_case() {
        // A tiny batch "editor" that appends a non-comment line to whatever
        // file it's invoked on (%~1) - standing in for a real interactive
        // editor session. `%~1` strips any surrounding quotes Windows adds
        // around a path containing spaces.
        let dir = std::env::temp_dir().join("lev-test-resolve-task-editor-happy-win");
        let _ = std::fs::create_dir_all(&dir);
        let script = dir.join("fake-editor.bat");
        write_bat(&script, "echo task body from editor>>\"%~1\"");

        temp_env::with_vars([("VISUAL", Some(&script)), ("EDITOR", None)], || {
            let result = resolve_task_with(
                &None,
                "test-agent",
                Some("a non-empty description"),
                &|| true,
            );
            assert_eq!(result.unwrap(), "task body from editor");

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    #[cfg(windows)]
    #[test]
    fn resolve_task_with_editor_path_empty_after_stripping_comments_errors() {
        // A no-op batch file "opens" the file and does nothing to it, so
        // only the commented-out template remains - stripped down to an
        // empty task.
        let dir = std::env::temp_dir().join("lev-test-resolve-task-editor-empty-win");
        let _ = std::fs::create_dir_all(&dir);
        let ok_bat = dir.join("ok.bat");
        write_bat(&ok_bat, "exit /b 0");

        temp_env::with_vars([("VISUAL", Some(&ok_bat)), ("EDITOR", None)], || {
            let result = resolve_task_with(&None, "test-agent", None, &|| true);
            assert!(result.is_err());
            assert!(result.unwrap_err().to_string().contains("Aborting run"));

            let _ = std::fs::remove_dir_all(&dir);
        });
    }

    // ─── build_task_template: description branch ──────────────────────────

    #[test]
    fn build_task_template_with_empty_description_skips_desc_line() {
        let t = build_task_template("agent", Some(""));
        assert!(!t.contains("# \n"));
        assert!(t.contains("# Task for agent: agent\n"));
    }

    #[test]
    fn build_task_template_with_non_empty_description_adds_desc_line() {
        let t = build_task_template("my-agent", Some("Build a web server"));
        assert!(t.contains("# Task for agent: my-agent\n"));
        assert!(t.contains("# Build a web server\n"));
    }

    #[test]
    fn build_task_template_with_no_description() {
        let t = build_task_template("my-agent", None);
        assert!(t.contains("# Task for agent: my-agent\n"));
        assert!(t.contains("Describe your task below"));
    }

    // ─── write_task_template: error path ─────────────────────────────────

    /// A temp file that cannot be created is reported rather than swallowed.
    #[test]
    fn write_task_template_error_on_bad_path() {
        // A directory that is not one: creation fails, which is the single
        // error this reports.
        let dir = tempfile::tempdir().unwrap();
        let blocker = dir.path().join("blocker");
        std::fs::write(&blocker, b"x").unwrap();
        let result = write_task_template(&blocker, "content");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Failed to create task temp file")
        );
    }

    // ─── resolve_task: unreadable file errors ────────────────────────────

    #[cfg(unix)]
    #[test]
    fn resolve_task_unreadable_file_returns_error() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join("lev-test-resolve-unreadable");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("secret.txt");
        std::fs::write(&file, "secret content").unwrap();
        let mut perms = std::fs::metadata(&file).unwrap().permissions();
        perms.set_mode(0o000);
        std::fs::set_permissions(&file, perms).unwrap();

        let result = resolve_task_with(
            &Some(file.to_str().unwrap().to_string()),
            "test-agent",
            None,
            &|| false,
        );
        // Restore perms before asserting (so cleanup works)
        let mut perms2 = std::fs::metadata(&file).unwrap().permissions();
        perms2.set_mode(0o644);
        std::fs::set_permissions(&file, perms2).ok();
        let _ = std::fs::remove_dir_all(&dir);

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Failed to read task file")
        );
    }

    // Windows has no chmod-style permission bits; instead, opening the file
    // for writing with a zero share mode (no `FILE_SHARE_READ`) makes any
    // concurrent read attempt fail with a sharing violation for as long as
    // the handle stays open - a deterministic Windows-native way to force
    // the same "file exists but can't be read" outcome the Unix test above
    // produces via `chmod 000`.
    #[cfg(windows)]
    #[test]
    fn resolve_task_unreadable_file_returns_error() {
        use std::fs::OpenOptions;
        use std::os::windows::fs::OpenOptionsExt;

        let dir = std::env::temp_dir().join("lev-test-resolve-unreadable-win");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("secret.txt");
        std::fs::write(&file, "secret content").unwrap();

        // Hold an exclusive (no-share) handle open for the duration of the
        // read attempt below.
        let _locked = OpenOptions::new()
            .write(true)
            .share_mode(0)
            .open(&file)
            .unwrap();

        let result = resolve_task_with(
            &Some(file.to_str().unwrap().to_string()),
            "test-agent",
            None,
            &|| false,
        );

        drop(_locked);
        let _ = std::fs::remove_dir_all(&dir);

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Failed to read task file")
        );
    }
}