selfware 0.6.0

Your personal AI workshop — software you own, software that lasts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
use super::*;
use crate::config::Config;
use crate::testing::mock_api::MockLlmServer;

#[test]
fn confirm_response_requires_explicit_yolo_word() {
    use super::{parse_confirm_response, ConfirmDecision};
    assert_eq!(parse_confirm_response("y"), ConfirmDecision::ExecuteOnce);
    assert_eq!(parse_confirm_response("YES"), ConfirmDecision::ExecuteOnce);
    assert_eq!(parse_confirm_response("yolo"), ConfirmDecision::EnableYolo);
    assert_eq!(
        parse_confirm_response(" YOLO "),
        ConfirmDecision::EnableYolo
    );
    // The old footgun keys must now be harmless skips, not a session downgrade.
    assert_eq!(parse_confirm_response("s"), ConfirmDecision::Skip);
    assert_eq!(parse_confirm_response("skip"), ConfirmDecision::Skip);
    assert_eq!(parse_confirm_response("n"), ConfirmDecision::Skip);
    assert_eq!(parse_confirm_response(""), ConfirmDecision::Skip);
}

#[test]
fn confirm_response_always_allow_is_tool_scoped_session_grant() {
    use super::{parse_confirm_response, ConfirmDecision};
    // "a"/"always" = always allow THIS tool for the session (P1-5b) —
    // deliberately distinct from "yolo", which drops ALL confirmations.
    assert_eq!(parse_confirm_response("a"), ConfirmDecision::AlwaysAllow);
    assert_eq!(parse_confirm_response("A"), ConfirmDecision::AlwaysAllow);
    assert_eq!(
        parse_confirm_response("always"),
        ConfirmDecision::AlwaysAllow
    );
    assert_eq!(
        parse_confirm_response(" Always "),
        ConfirmDecision::AlwaysAllow
    );
    // Nearby keystrokes must not be misread as always-allow.
    assert_ne!(parse_confirm_response("al"), ConfirmDecision::AlwaysAllow);
    assert_eq!(parse_confirm_response("y"), ConfirmDecision::ExecuteOnce);
    assert_eq!(parse_confirm_response("yolo"), ConfirmDecision::EnableYolo);
}

#[test]
fn test_shell_verification_matches_at_command_boundary() {
    // Plain and flagged forms still match.
    assert!(shell_command_is_verification("cargo check"));
    assert!(shell_command_is_verification("cargo test --all"));
    // Regression: full-path / cd-prefixed invocations must be credited too
    // (the model used ~/.cargo/bin/cargo to dodge a PATH issue and looped).
    assert!(shell_command_is_verification("~/.cargo/bin/cargo check"));
    assert!(shell_command_is_verification(
        "/usr/bin/cargo check --message-format short"
    ));
    assert!(shell_command_is_verification("cd crates/foo && cargo test"));
    // Non-verification commands are not falsely credited.
    assert!(!shell_command_is_verification("cargo add serde"));
    assert!(!shell_command_is_verification("echo cargo checkers"));
    assert!(!shell_command_is_verification("ls -la"));
}

#[test]
fn test_shell_verification_credits_direct_test_script_runs() {
    // P0-2 regression: on a non-Rust project the model verifies by running
    // the project's own test/check script directly. Those runs must count
    // as verification or a correct fix livelocks on StaleVerification.
    assert!(shell_command_is_verification("python3 test_calc.py"));
    assert!(shell_command_is_verification("python test_calc.py"));
    assert!(shell_command_is_verification("python3 tests/test_calc.py"));
    assert!(shell_command_is_verification(
        "python3 -c \"assert add(2, 2) == 4\""
    ));
    assert!(shell_command_is_verification("node tests/smoke.test.js"));
    assert!(shell_command_is_verification("node test_smoke.js"));
    assert!(shell_command_is_verification("ruby test_foo.rb"));
    assert!(shell_command_is_verification("bash tests/run.sh"));
    // Executing the test script itself, full-path interpreters, and
    // cd-prefixed forms count too.
    assert!(shell_command_is_verification("./test_x.py"));
    assert!(shell_command_is_verification("/usr/bin/python3 test_x.py"));
    assert!(shell_command_is_verification("cd sub && python3 test_x.py"));
    assert!(shell_command_is_verification("python3 -u test_x.py"));
    // NOT verification: running the app, arbitrary inline code, or a
    // non-test script that merely takes a test-named data file.
    assert!(!shell_command_is_verification("python3 app.py"));
    assert!(!shell_command_is_verification("python3 -c \"print('hi')\""));
    assert!(!shell_command_is_verification(
        "python3 process.py test_data.csv"
    ));
    assert!(!shell_command_is_verification("node server.js"));
    assert!(!shell_command_is_verification("bash deploy.sh"));
}

#[test]
fn test_observational_includes_direct_test_script_runs() {
    // P0-2 regression (b): a passing verification run must not re-stale
    // the gate, so a direct test-script run is observational (no mutation
    // bump) — exactly like `pytest` / `cargo test` already were.
    assert!(shell_command_is_observational("python3 test_calc.py"));
    assert!(shell_command_is_observational(
        "python3 -c \"assert x == 1\""
    ));
    assert!(!tool_call_is_mutating(
        "shell_exec",
        &serde_json::json!({"command": "python3 test_calc.py"})
    ));
    // Inline snippets NOT framed as checks stay mutating, a redirect
    // still writes a file, and running the app is not observational.
    assert!(!shell_command_is_observational(
        "python3 -c \"open('f','w').write('x')\""
    ));
    assert!(!shell_command_is_observational(
        "python3 test_calc.py > out.txt"
    ));
    assert!(!shell_command_is_observational("python3 app.py"));
}

#[test]
fn test_pty_shell_verification_credited_like_shell_exec() {
    // Mutation accounting already covered pty_shell; verification credit
    // must be symmetric or PTY-run tests never satisfy the gate.
    let verification = r#"{"command":"python3 test_calc.py"}"#;
    assert!(tool_call_is_verification("shell_exec", verification));
    assert!(tool_call_is_verification("pty_shell", verification));
    assert!(!tool_call_is_verification(
        "pty_shell",
        r#"{"command":"python3 app.py"}"#
    ));
}

#[tokio::test]
async fn passing_direct_python_test_run_is_credited_without_re_staling() {
    // P0-2 regression: simulate the dispatch accounting path exactly —
    // a real edit, then the project's own passing test run.
    let mut agent = Agent::new(test_config("http://127.0.0.1:1".to_string()))
        .await
        .expect("agent should build");

    // The edit bumps the mutation sequence.
    agent.note_mutating_tool_call();
    assert_eq!(agent.mutation_sequence, 1);

    // The model runs the project's own check directly; it exits 0. Apply
    // the same accounting the dispatch loop applies, in the same order.
    let args = serde_json::json!({"command": "python3 test_calc.py"});
    if tool_call_is_mutating("shell_exec", &args) {
        agent.note_mutating_tool_call();
    }
    agent.note_verification_outcome("shell_exec", &args.to_string(), true, "1 passed");

    assert_eq!(
        agent.mutation_sequence, 1,
        "a passing verification run must not bump the mutation sequence (re-stale the gate)"
    );
    assert_eq!(
        agent.last_successful_verification_mutation_sequence, 1,
        "the passing direct test run must be credited as verification"
    );
    assert!(agent.last_failed_verification_summary.is_none());
}

#[tokio::test]
async fn failing_direct_python_test_run_records_failure_summary() {
    let mut agent = Agent::new(test_config("http://127.0.0.1:1".to_string()))
        .await
        .expect("agent should build");
    agent.note_mutating_tool_call();

    let args = serde_json::json!({"command": "python3 test_calc.py"});
    agent.note_verification_outcome(
        "shell_exec",
        &args.to_string(),
        false,
        "FAILED test_calc.py::test_div",
    );

    assert_eq!(
        agent.last_successful_verification_mutation_sequence, 0,
        "a failing verification run must not be credited"
    );
    let summary = agent
        .last_failed_verification_summary
        .clone()
        .expect("a failing verification run must be recorded");
    assert!(summary.contains("shell_exec failed"), "{summary}");
}

#[test]
fn patch_target_paths_extracts_targets() {
    let diff = "--- a/src/a.rs\n+++ b/src/a.rs\n@@ -1 +1 @@\n-x\n+y\n\
                    --- a/b.txt\n+++ b/b.txt\n@@ -0,0 +1,1 @@\n+z\n";
    let paths = patch_target_paths(diff);
    assert_eq!(
        paths,
        vec![
            std::path::PathBuf::from("src/a.rs"),
            std::path::PathBuf::from("b.txt")
        ]
    );
    // Deleted files (+++ /dev/null) have no pre-edit content to snapshot.
    let deleted = "--- a/gone.rs\n+++ /dev/null\n@@ -1 +0,0 @@\n-x\n";
    assert!(patch_target_paths(deleted).is_empty());
}

#[tokio::test]
async fn multi_file_snapshot_captures_every_target_for_undo() {
    let mut agent = Agent::new(test_config("http://127.0.0.1:1".to_string()))
        .await
        .expect("agent should build");
    let dir = tempfile::tempdir().unwrap();
    let f1 = dir.path().join("a.txt");
    let f2 = dir.path().join("b.txt");
    std::fs::write(&f1, "alpha\n").unwrap();
    std::fs::write(&f2, "beta\n").unwrap();

    Agent::snapshot_files_for_undo(
        &mut agent.edit_history,
        vec![f1.clone(), f2.clone()],
        "patch_apply",
    )
    .await;

    let checkpoint = agent
        .edit_history
        .current_checkpoint()
        .expect("snapshot must create a checkpoint");
    match &checkpoint.action {
        crate::session::edit_history::EditAction::MultiFileEdit { paths, tool } => {
            assert_eq!(tool, "patch_apply");
            assert_eq!(paths.len(), 2);
        }
        other => panic!("expected MultiFileEdit, got {other:?}"),
    }
    assert_eq!(
        checkpoint.files[&f1].content, "alpha\n",
        "pre-edit content must be captured for /undo"
    );
    assert_eq!(checkpoint.files[&f2].content, "beta\n");

    // Simulate /undo: restoring from the checkpoint must bring back the
    // pre-edit contents.
    std::fs::write(&f1, "EDITED\n").unwrap();
    for (path, snap) in &checkpoint.files {
        std::fs::write(path, &snap.content).unwrap();
    }
    assert_eq!(std::fs::read_to_string(&f1).unwrap(), "alpha\n");
}

#[tokio::test]
async fn file_multi_edit_dispatch_snapshots_undo_and_clears_cache() {
    let mut agent = Agent::new(test_config("http://127.0.0.1:1".to_string()))
        .await
        .expect("agent should build");
    let dir = tempfile::tempdir().unwrap();
    let f1 = dir.path().join("m1.txt");
    let f2 = dir.path().join("m2.txt");
    std::fs::write(&f1, "one\n").unwrap();
    std::fs::write(&f2, "two\n").unwrap();

    // Seed a stale cached read result that must not survive the mutation.
    let status_args = serde_json::json!({"repo_path": "."});
    agent
        .cache_manager
        .tool_cache
        .set(
            "git_status",
            &status_args,
            serde_json::json!({"branch": "old"}),
        )
        .await;

    let args = serde_json::json!({
        "edits": [
            {"path": f1.to_str().unwrap(), "old_str": "one", "new_str": "ONE"},
            {"path": f2.to_str().unwrap(), "old_str": "two", "new_str": "TWO"}
        ]
    });
    let args_str = args.to_string();
    let (ok, result, _) = agent
        .execute_single_tool(
            "file_multi_edit",
            &args_str,
            &args,
            std::time::Instant::now(),
        )
        .await
        .expect("dispatch should run");
    assert!(ok, "multi_edit should succeed: {result}");

    // /undo snapshot: ONE checkpoint holding BOTH pre-edit files —
    // previously nothing was captured and /undo reverted an unrelated
    // older checkpoint while claiming success.
    let checkpoint = agent
        .edit_history
        .current_checkpoint()
        .expect("file_multi_edit must capture a pre-edit checkpoint");
    assert!(
        matches!(
            checkpoint.action,
            crate::session::edit_history::EditAction::MultiFileEdit { .. }
        ),
        "expected a MultiFileEdit checkpoint, got {:?}",
        checkpoint.action
    );
    assert_eq!(checkpoint.files[&f1].content, "one\n");
    assert_eq!(checkpoint.files[&f2].content, "two\n");

    // The tool-result cache must be cleared so a follow-up git_status does
    // not serve the pre-edit result.
    assert!(agent
        .cache_manager
        .tool_cache
        .get("git_status", &status_args)
        .await
        .is_none());
}

fn test_config(endpoint: String) -> Config {
    Config {
        endpoint,
        model: "mock-model".to_string(),
        agent: crate::config::AgentConfig {
            max_iterations: 50,
            step_timeout_secs: 10,
            streaming: false,
            native_function_calling: false,
            min_completion_steps: 0,
            require_verification_before_completion: false,
            ..Default::default()
        },
        safety: crate::config::SafetyConfig {
            allowed_paths: vec!["./**".to_string(), "/**".to_string()],
            ..Default::default()
        },
        execution_mode: crate::config::ExecutionMode::Yolo,
        ..Default::default()
    }
}

// =========================================================================
// ToolErrorKind Classification Tests
// =========================================================================

#[test]
fn test_tool_error_kind_classify_safety_violation() {
    // Test safety-related keywords
    assert_eq!(
        ToolErrorKind::classify("safety check failed"),
        ToolErrorKind::SafetyViolation
    );
    assert_eq!(
        ToolErrorKind::classify("Operation blocked by safety policy"),
        ToolErrorKind::SafetyViolation
    );
    assert_eq!(
        ToolErrorKind::classify("BLOCKED: File access denied"),
        ToolErrorKind::SafetyViolation
    );
}

#[test]
fn test_tool_error_kind_classify_resource_not_found() {
    // Test resource not found keywords
    assert_eq!(
        ToolErrorKind::classify("File not found"),
        ToolErrorKind::ResourceNotFound
    );
    assert_eq!(
        ToolErrorKind::classify("No such file or directory"),
        ToolErrorKind::ResourceNotFound
    );
    assert_eq!(
        ToolErrorKind::classify("resource NOT FOUND"),
        ToolErrorKind::ResourceNotFound
    );
}

#[test]
fn test_tool_error_kind_classify_permission_denied() {
    // Test permission-related keywords
    assert_eq!(
        ToolErrorKind::classify("Permission denied"),
        ToolErrorKind::PermissionDenied
    );
    assert_eq!(
        ToolErrorKind::classify("Access denied"),
        ToolErrorKind::PermissionDenied
    );
    assert_eq!(
        ToolErrorKind::classify("operation not permitted"),
        ToolErrorKind::PermissionDenied
    );
}

#[test]
fn test_tool_error_kind_classify_argument_error() {
    // Test parse/JSON/invalid keywords
    assert_eq!(
        ToolErrorKind::classify("Failed to parse JSON"),
        ToolErrorKind::ArgumentError
    );
    assert_eq!(
        ToolErrorKind::classify("Invalid argument provided"),
        ToolErrorKind::ArgumentError
    );
    assert_eq!(
        ToolErrorKind::classify("JSON parsing error"),
        ToolErrorKind::ArgumentError
    );
    assert_eq!(
        ToolErrorKind::classify("parse error at line 5"),
        ToolErrorKind::ArgumentError
    );
}

#[test]
fn test_tool_error_kind_classify_timeout() {
    // Test timeout keyword
    assert_eq!(
        ToolErrorKind::classify("Request timeout"),
        ToolErrorKind::Timeout
    );
    assert_eq!(
        ToolErrorKind::classify("Operation timed out after 30s"),
        ToolErrorKind::Timeout
    );
}

#[test]
fn test_tool_error_kind_classify_execution_error_fallback() {
    // Test that unknown errors fall back to ExecutionError
    assert_eq!(
        ToolErrorKind::classify("Something went wrong"),
        ToolErrorKind::ExecutionError
    );
    assert_eq!(
        ToolErrorKind::classify("Unknown error occurred"),
        ToolErrorKind::ExecutionError
    );
    assert_eq!(ToolErrorKind::classify(""), ToolErrorKind::ExecutionError);
}

#[test]
fn test_tool_error_kind_classify_case_insensitive() {
    // Test that classification is case-insensitive
    assert_eq!(
        ToolErrorKind::classify("SAFETY VIOLATION"),
        ToolErrorKind::SafetyViolation
    );
    assert_eq!(ToolErrorKind::classify("Timeout"), ToolErrorKind::Timeout);
    assert_eq!(
        ToolErrorKind::classify("JSON error"),
        ToolErrorKind::ArgumentError
    );
}

// =========================================================================
// ToolErrorKind String Representation Tests
// =========================================================================

#[test]
fn test_tool_error_kind_as_str() {
    assert_eq!(ToolErrorKind::SafetyViolation.as_str(), "SAFETY_VIOLATION");
    assert_eq!(
        ToolErrorKind::ResourceNotFound.as_str(),
        "RESOURCE_NOT_FOUND"
    );
    assert_eq!(
        ToolErrorKind::PermissionDenied.as_str(),
        "PERMISSION_DENIED"
    );
    assert_eq!(ToolErrorKind::ArgumentError.as_str(), "ARGUMENT_ERROR");
    assert_eq!(ToolErrorKind::Timeout.as_str(), "TIMEOUT");
    assert_eq!(ToolErrorKind::ExecutionError.as_str(), "EXECUTION_ERROR");
}

// =========================================================================
// ToolErrorKind Recovery Hint Tests
// =========================================================================

#[test]
fn test_tool_error_kind_recovery_hint_safety() {
    let hint = ToolErrorKind::SafetyViolation.recovery_hint();
    assert!(hint.contains("protected files"));
    assert!(!hint.is_empty());
}

#[test]
fn test_tool_error_kind_recovery_hint_resource_not_found() {
    let hint = ToolErrorKind::ResourceNotFound.recovery_hint();
    assert!(hint.contains("path exists"));
    assert!(!hint.is_empty());
}

#[test]
fn test_tool_error_kind_recovery_hint_permission_denied() {
    let hint = ToolErrorKind::PermissionDenied.recovery_hint();
    assert!(hint.contains("sudo") || hint.contains("permissions"));
    assert!(!hint.is_empty());
}

#[test]
fn test_tool_error_kind_recovery_hint_argument_error() {
    let hint = ToolErrorKind::ArgumentError.recovery_hint();
    assert!(hint.contains("schema") || hint.contains("arguments"));
    assert!(!hint.is_empty());
}

#[test]
fn test_tool_error_kind_recovery_hint_timeout() {
    let hint = ToolErrorKind::Timeout.recovery_hint();
    assert!(hint.contains("smaller steps") || hint.contains("timeout"));
    assert!(!hint.is_empty());
}

#[test]
fn test_tool_error_kind_recovery_hint_execution_error() {
    let hint = ToolErrorKind::ExecutionError.recovery_hint();
    assert!(hint.contains("adjust") || hint.contains("Review"));
    assert!(!hint.is_empty());
}

#[test]
fn test_tool_error_kind_all_hints_are_non_empty() {
    // Ensure all error kinds have meaningful recovery hints
    for kind in [
        ToolErrorKind::SafetyViolation,
        ToolErrorKind::ResourceNotFound,
        ToolErrorKind::PermissionDenied,
        ToolErrorKind::ArgumentError,
        ToolErrorKind::Timeout,
        ToolErrorKind::ExecutionError,
    ] {
        let hint = kind.recovery_hint();
        assert!(
            hint.len() > 10,
            "Recovery hint for {:?} should be meaningful, got: {}",
            kind,
            hint
        );
    }
}

// =========================================================================
// Integration Test: Round-trip Classification
// =========================================================================

#[test]
fn test_tool_error_kind_roundtrip_classification() {
    // Test that classified errors can be converted back to strings
    let test_errors = vec![
        ("safety block triggered", ToolErrorKind::SafetyViolation),
        ("file not found error", ToolErrorKind::ResourceNotFound),
        ("permission denied on read", ToolErrorKind::PermissionDenied),
        ("invalid JSON format", ToolErrorKind::ArgumentError),
        ("connection timeout", ToolErrorKind::Timeout),
        ("unexpected failure", ToolErrorKind::ExecutionError),
    ];

    for (error_msg, expected_kind) in test_errors {
        let classified = ToolErrorKind::classify(error_msg);
        assert_eq!(
            classified, expected_kind,
            "Failed to classify '{}' correctly",
            error_msg
        );

        // Verify we can get string representation and hint
        let _ = classified.as_str();
        let _ = classified.recovery_hint();
    }
}

// =========================================================================
// Helper Function Tests
// =========================================================================

#[test]
fn test_truncate_chars_short_string() {
    let input = "short";
    let result = truncate_chars(input, 100);
    assert_eq!(result, input);
}

#[test]
fn test_truncate_chars_exact_length() {
    let input = "exactly10";
    let result = truncate_chars(input, 9);
    assert_eq!(result, input);
}

#[test]
fn test_truncate_chars_long_string() {
    let input = "this is a very long string";
    let result = truncate_chars(input, 10);
    assert_eq!(result, "this is a ...");
}

#[test]
fn test_truncate_chars_unicode() {
    let input = "🎉🎊🎁🎄🎃🎅🤶🧑‍🎄";
    let result = truncate_chars(input, 3);
    assert_eq!(result, "🎉🎊🎁...");
}

#[test]
fn summarize_generic_preserves_tail_marker() {
    // A large result whose FAILURE marker is at the very end must survive
    // summarization — head-only truncation would drop it and the gate would
    // miss the failure.
    let middle = "x".repeat(60_000);
    let raw = format!(
        "START\n{}\n<verification_failed>tests FAILED</verification_failed>",
        middle
    );
    let summary = summarize_generic(&raw);
    assert!(summary.contains("START"), "head kept");
    assert!(
        summary.contains("<verification_failed>") && summary.contains("FAILED"),
        "tail failure marker must survive summarization: {}",
        &summary[summary.len().saturating_sub(200)..]
    );
    // Middle was actually elided (summary far smaller than raw).
    assert!(summary.chars().count() < raw.chars().count());
    assert!(summary.contains("omitted from the middle"));
}

#[test]
fn summarize_generic_keeps_small_input_verbatim() {
    let raw = "short output\nline 2\n<verification_failed>nope</verification_failed>";
    assert_eq!(summarize_generic(raw), raw);
}

#[tokio::test]
async fn summarize_and_spill_redacts_secrets_on_disk() {
    // A large shell result carrying a credential must not land unredacted
    // in the plaintext spill file under .selfware/tool_results/.
    let secret = format!("ghp_{}", "a".repeat(36)); // matches the github_token pattern
    let raw = format!(
        "{{\"output\":\"export TOKEN={secret}\\n{}\"}}",
        "x".repeat(60_000)
    );
    let call_id = "spillredacttest01";

    let _summary = summarize_and_spill("shell_exec", call_id, &raw, 9999).await;

    let spill_file = std::path::Path::new(TOOL_RESULTS_DIR).join(format!(
        "shell_exec_{}.json",
        call_id.chars().take(12).collect::<String>()
    ));
    let on_disk = std::fs::read_to_string(&spill_file).expect("spill file should exist");
    let _ = std::fs::remove_file(&spill_file);

    assert!(
        !on_disk.contains(&secret),
        "secret leaked to the spill file on disk"
    );
    assert!(
        on_disk.contains("[REDACTED]"),
        "spill file should contain the redaction marker"
    );
}

#[test]
fn test_canonicalize_tool_args_valid_json() {
    let input = r#"{"key": "value", "num": 42}"#;
    let result = canonicalize_tool_args(input);
    // Should parse and re-serialize
    assert!(result.contains("key"));
    assert!(result.contains("value"));
}

#[test]
fn test_canonicalize_tool_args_invalid_json() {
    let input = "not valid json";
    let result = canonicalize_tool_args(input);
    // Should return original string
    assert_eq!(result, input);
}

#[test]
fn test_hash_tool_args_consistency() {
    // Same input should produce same hash
    let input = r#"{"key": "value"}"#;
    let hash1 = hash_tool_args(input);
    let hash2 = hash_tool_args(input);
    assert_eq!(hash1, hash2);
}

#[test]
fn test_hash_tool_args_equivalent_json() {
    // Different formatting of same JSON should produce same hash
    let input1 = r#"{"a":1,"b":2}"#;
    let input2 = r#"{"b":2,"a":1}"#;
    let hash1 = hash_tool_args(input1);
    let hash2 = hash_tool_args(input2);
    // Note: This depends on JSON canonicalization
    // The current implementation uses serde_json which preserves order
    // This test documents current behavior
    let _ = (hash1, hash2);
}

#[test]
fn test_extract_explicit_allowed_tools_from_task_prompt() {
    let task = "Use only these concrete tools for this task:\n- `file_read`\n- `file_edit`\n- `file_write`\n- `shell_exec`\n";
    let allowed = extract_explicit_allowed_tools(task).expect("expected allowlist");
    assert!(allowed.contains("file_read"));
    assert!(allowed.contains("file_edit"));
    assert!(allowed.contains("file_write"));
    assert!(allowed.contains("shell_exec"));
    assert_eq!(allowed.len(), 4);
}

#[test]
fn test_extract_explicit_requested_tools_detects_imperative_use() {
    let required = extract_explicit_requested_tools(
        "Use vision_analyze on ./sample.jpg and answer in one sentence.",
        ["vision_analyze", "file_read"].iter().copied(),
    );
    assert!(required.contains("vision_analyze"));
    assert_eq!(required.len(), 1);
}

#[test]
fn test_extract_explicit_requested_tools_detects_backticked_tool() {
    let required = extract_explicit_requested_tools(
        "Please call `file_read` on Cargo.toml before answering.",
        ["vision_analyze", "file_read"].iter().copied(),
    );
    assert!(required.contains("file_read"));
}

#[test]
fn test_negated_tool_mention_is_not_a_required_tool() {
    let required = extract_explicit_requested_tools(
        "Create notes.txt, but don't use `shell_exec`.",
        ["shell_exec", "file_write"].iter().copied(),
    );
    assert!(!required.contains("shell_exec"));
}

#[test]
fn test_shell_category_denial_overrides_plain_tool_mention() {
    let task =
        "Create user-check_1+2=3.txt using file_write. Do not run shell commands or use pty_shell.";
    let required = extract_explicit_requested_tools(
        task,
        ["file_write", "shell_exec", "pty_shell"].iter().copied(),
    );

    assert!(required.contains("file_write"));
    assert!(!required.contains("shell_exec"));
    assert!(!required.contains("pty_shell"));
}

#[test]
fn test_shell_exec_verification_commands_are_observational() {
    assert!(shell_command_is_observational("cargo test --quiet"));
    assert!(shell_command_is_observational("cargo check"));
    assert!(!shell_command_is_observational("cargo fmt"));
    assert!(!shell_command_is_observational("mkdir tmp"));
}

#[test]
fn test_shell_redirect_writes_are_not_observational() {
    // Redirects WITHOUT a leading space used to slip through (#22).
    assert!(!shell_command_is_observational("echo x>y"));
    assert!(!shell_command_is_observational("cat>file"));
    assert!(!shell_command_is_observational("echo hi > out.txt"));
    assert!(!shell_command_is_observational("cat a >> b"));
    assert!(!shell_command_is_observational("echo data >/etc/thing"));
}

#[test]
fn test_shell_fd_dup_and_quoted_gt_stay_observational() {
    // 2>&1 duplicates a descriptor — it writes no file.
    assert!(shell_command_is_observational("cargo test 2>&1"));
    assert!(shell_command_is_observational("grep foo bar 2>&1"));
    // A '>' inside quotes is data, not a redirect.
    assert!(shell_command_is_observational(r#"grep "->" file"#));
    assert!(shell_command_is_observational("echo 'a>b'"));
}

#[test]
fn test_tool_call_counts_shell_exec_state_changes_correctly() {
    assert!(!tool_call_counts_as_state_change(
        "shell_exec",
        r#"{"command":"cargo test"}"#
    ));
    assert!(tool_call_counts_as_state_change(
        "shell_exec",
        r#"{"command":"cargo fmt"}"#
    ));
    assert!(!tool_call_counts_as_state_change("shell_exec", r#"{}"#));
}

#[tokio::test]
async fn test_task_tool_policy_blocks_unlisted_tools() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();
    agent.current_task_context = "Use only these concrete tools for this task:\n- `file_read`\n- `file_edit`\n- `file_write`\n- `shell_exec`\nNever call `tool_search`.".to_string();

    agent
        .execute_tool_batch(vec![(
            crate::tools::context::CONTEXT_BULK_READ.to_string(),
            r#"{"pattern":"src/**/*.rs","max_files":2}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    let last = agent
        .messages
        .last()
        .expect("expected tool policy rejection");
    assert!(last.content.text().contains("Task tool policy violation"));
    assert!(last.content.text().contains("Allowed tools"));
    assert!(agent
        .recent_failed_tool_attempts
        .back()
        .is_some_and(|attempt| attempt.failure_kind == "task_policy"));

    server.stop().await;
}

#[tokio::test]
async fn test_operator_denial_is_remembered_for_exact_retry() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();
    let args = r#"{"path":"notes.txt","content":"hello"}"#;

    agent.record_failed_tool_attempt(
        "file_write",
        args,
        "operator_denied",
        "Tool execution denied via TUI permission prompt",
    );

    let failure = agent
        .recent_failed_tool_attempts
        .back()
        .expect("operator denial should be task-local retry memory");
    assert_eq!(failure.failure_kind, "operator_denied");
    let retry_message = agent.build_failed_tool_retry_suppressed_message(failure);
    assert!(retry_message.contains("operator denied `file_write`"));
    assert!(retry_message.contains("Do not ask for the same permission again"));

    server.stop().await;
}

#[tokio::test]
async fn test_progress_guard_blocks_read_only_batches_after_threshold() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();
    agent.current_task_context =
        "Fix the failing tests, make code changes, and keep going until everything is green."
            .to_string();
    // New pre-edit block_threshold is 12, escalation_threshold is 18.
    // Set above escalation so the guard fires AND synthesis is triggered.
    agent.consecutive_read_only_steps = 19;

    agent
        .execute_tool_batch(vec![(
            "shell_exec".to_string(),
            r#"{"command":"cargo test"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    assert!(agent
        .messages
        .iter()
        .any(|msg| msg.content.text().contains("PROGRESS GUARD")));
    let last = agent
        .messages
        .last()
        .expect("expected follow-up progress directive");
    assert!(last
        .content
        .text()
        .contains("READ-LOOP FORCE-MUTATION MODE"));
    assert!(last.content.text().contains("<name>file_edit</name>"));
    assert_eq!(
        agent.pending_synthesis.as_deref(),
        Some("Fix the failing tests, make code changes, and keep going until everything is green.")
    );
    assert!(agent
        .recent_failed_tool_attempts
        .back()
        .is_some_and(|attempt| attempt.failure_kind == "progress_guard"));

    // guard_count is now 1 (first fire).  Need >= 3 for hard abort.
    agent.consecutive_read_only_steps = 14;
    agent
        .execute_tool_batch(vec![(
            "shell_exec".to_string(),
            r#"{"command":"git status"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();
    // guard_count is now 2 — still not enough for hard abort (>= 3).
    agent.consecutive_read_only_steps = 15;
    let err = agent
        .execute_tool_batch(vec![(
            "shell_exec".to_string(),
            r#"{"command":"git status"}"#.to_string(),
            None,
        )])
        .await
        .unwrap_err();
    assert!(err.to_string().contains("READ_LOOP_NO_EDIT"));

    server.stop().await;
}

#[tokio::test]
async fn test_progress_guard_novel_reads_decrement_counter() {
    // Bug #13: reading DISTINCT new files should NOT trip the guard as fast
    // as re-reading the same file.  We verify that the investigation-progress
    // reset causes `consecutive_read_only_steps` to DECREASE when the agent
    // reads a novel file, while re-reading the same file INCREASES it.
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();
    agent.current_task_context =
        "Refactor the module: read many files, then make changes.".to_string();

    // Start with a moderate read-only streak.
    agent.consecutive_read_only_steps = 5;

    // Read file A — novel target, counter should DECREMENT.
    agent.update_read_only_step_tracking(
        &[(
            "file_read".to_string(),
            r#"{"path":"src/main.rs"}"#.to_string(),
            None,
        )],
        false,
    );
    assert_eq!(
        agent.consecutive_read_only_steps, 4,
        "novel read should decrement counter"
    );

    // Read file B — novel target, counter should DECREMENT again.
    agent.update_read_only_step_tracking(
        &[(
            "file_read".to_string(),
            r#"{"path":"src/lib.rs"}"#.to_string(),
            None,
        )],
        false,
    );
    assert_eq!(
        agent.consecutive_read_only_steps, 3,
        "second novel read should decrement counter"
    );

    // Re-read file A — redundant, counter should INCREMENT.
    agent.update_read_only_step_tracking(
        &[(
            "file_read".to_string(),
            r#"{"path":"src/main.rs"}"#.to_string(),
            None,
        )],
        false,
    );
    assert_eq!(
        agent.consecutive_read_only_steps, 4,
        "redundant re-read should increment counter"
    );

    // Re-read file A again — still redundant, counter should INCREMENT.
    agent.update_read_only_step_tracking(
        &[(
            "file_read".to_string(),
            r#"{"path":"src/main.rs"}"#.to_string(),
            None,
        )],
        false,
    );
    assert_eq!(
        agent.consecutive_read_only_steps, 5,
        "second redundant re-read should increment counter"
    );

    // A write tool should reset counter AND clear the seen-set.
    agent.update_read_only_step_tracking(
        &[(
            "file_edit".to_string(),
            r#"{"path":"src/main.rs"}"#.to_string(),
            None,
        )],
        true,
    );
    assert_eq!(
        agent.consecutive_read_only_steps, 0,
        "write should reset counter to 0"
    );
    assert!(
        agent.seen_read_targets.is_empty(),
        "write should clear seen_read_targets"
    );

    server.stop().await;
}

#[test]
fn test_inject_runtime_tool_defaults_uses_vision_profile() {
    let mut config = crate::config::Config::default();
    config.models.insert(
        "vision".to_string(),
        crate::config::ModelProfile {
            endpoint: "https://vision.example/v1".to_string(),
            model: "remote-vision".to_string(),
            api_key: None,
            max_tokens: 192,
            temperature: 0.0,
            modalities: vec!["text".to_string(), "vision".to_string()],
            context_length: 262_144,
            extra_body: Some({
                let mut map = serde_json::Map::new();
                map.insert(
                    "chat_template_kwargs".to_string(),
                    serde_json::json!({ "enable_thinking": false }),
                );
                map
            }),
            native_function_calling: None,
        },
    );

    let effective = inject_runtime_tool_defaults(
        &config,
        "vision_analyze",
        r#"{"prompt":"describe","image_base64":"AAAA"}"#,
    );
    let parsed: serde_json::Value = serde_json::from_str(&effective).unwrap();
    assert_eq!(parsed["endpoint"], "https://vision.example/v1");
    assert_eq!(parsed["model"], "remote-vision");
    assert_eq!(parsed["max_tokens"], 192);
    assert_eq!(parsed["temperature"], 0.0);
    assert_eq!(parsed["detail"], "low");
    assert_eq!(
        parsed["extra_body"]["chat_template_kwargs"]["enable_thinking"],
        serde_json::json!(false)
    );
}

#[test]
fn test_inject_runtime_tool_defaults_preserves_explicit_values() {
    let mut config = crate::config::Config::default();
    config.models.insert(
        "vision".to_string(),
        crate::config::ModelProfile {
            endpoint: "https://vision.example/v1".to_string(),
            model: "remote-vision".to_string(),
            api_key: None,
            max_tokens: 192,
            temperature: 0.0,
            modalities: vec!["text".to_string(), "vision".to_string()],
            context_length: 262_144,
            extra_body: None,
            native_function_calling: None,
        },
    );

    let effective = inject_runtime_tool_defaults(
        &config,
        "vision_compare",
        r#"{"image_a":"a.png","image_b":"b.png","endpoint":"http://custom/v1","model":"custom-model","max_tokens":512,"temperature":0.5,"detail":"high"}"#,
    );
    let parsed: serde_json::Value = serde_json::from_str(&effective).unwrap();
    assert_eq!(parsed["endpoint"], "http://custom/v1");
    assert_eq!(parsed["model"], "custom-model");
    assert_eq!(parsed["max_tokens"], 512);
    assert_eq!(parsed["temperature"], 0.5);
    assert_eq!(parsed["detail"], "high");
}

#[test]
fn test_inject_runtime_tool_defaults_ignores_text_only_default_profile() {
    let mut config = crate::config::Config::default();
    config.models.insert(
        "default".to_string(),
        crate::config::ModelProfile {
            endpoint: "https://text.example/v1".to_string(),
            model: "text-only".to_string(),
            api_key: None,
            max_tokens: 512,
            temperature: 0.3,
            modalities: vec!["text".to_string()],
            context_length: 131_072,
            extra_body: None,
            native_function_calling: None,
        },
    );

    let effective = inject_runtime_tool_defaults(
        &config,
        "vision_analyze",
        r#"{"prompt":"describe","image_base64":"AAAA"}"#,
    );
    let parsed: serde_json::Value = serde_json::from_str(&effective).unwrap();
    assert!(parsed.get("endpoint").is_none());
    assert!(parsed.get("model").is_none());
}

// =========================================================================
// summarize_directory_tree tests
// =========================================================================

#[test]
fn test_summarize_directory_tree_basic() {
    let raw = serde_json::json!({
        "root": "/home/user/project",
        "total": 5,
        "entries": [
            {"path": "/home/user/project/src/main.rs", "type": "file", "size": 1024},
            {"path": "/home/user/project/src/lib.rs", "type": "file", "size": 512},
            {"path": "/home/user/project/src", "type": "directory", "size": 0},
            {"path": "/home/user/project/Cargo.toml", "type": "file", "size": 256},
            {"path": "/home/user/project/README.md", "type": "file", "size": 128}
        ]
    });
    let summary = summarize_directory_tree(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("/home/user/project"));
    assert!(summary.contains("5 entries"));
}

#[test]
fn test_summarize_directory_tree_empty() {
    let raw = serde_json::json!({"root": ".", "total": 0, "entries": []});
    let summary = summarize_directory_tree(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("0 entries"));
}

#[test]
fn test_summarize_directory_tree_invalid_json() {
    let summary = summarize_directory_tree("not json");
    assert!(summary.contains("0 entries"));
}

// =========================================================================
// summarize_file_read tests
// =========================================================================

#[test]
fn test_summarize_file_read_short() {
    let raw = serde_json::json!({
        "total_lines": 5,
        "content": "line1\nline2\nline3\nline4\nline5"
    });
    let summary = summarize_file_read(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("5 total lines"));
    assert!(summary.contains("line1"));
}

#[test]
fn test_summarize_file_read_long() {
    let lines: String = (0..200)
        .map(|i| format!("line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    let raw = serde_json::json!({
        "total_lines": 200,
        "content": lines
    });
    let summary = summarize_file_read(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("200 total lines"));
    assert!(summary.contains("First 100 lines"));
    assert!(summary.contains("Last 50 lines"));
    assert!(summary.contains("lines omitted"));
}

#[test]
fn test_summarize_file_read_empty() {
    let raw = serde_json::json!({"total_lines": 0, "content": ""});
    let summary = summarize_file_read(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("0 total lines"));
}

#[test]
fn test_summarize_file_read_150_boundary_no_silent_drop() {
    // Regression: files of 101–150 lines used to show only the first 100 and
    // silently drop the rest (the tail required > 150). Ensure lines 101–150
    // now appear and nothing is marked omitted (found by GLM-5.2).
    let lines: String = (0..150)
        .map(|i| format!("line {}", i))
        .collect::<Vec<_>>()
        .join("\n");
    let raw = serde_json::json!({"total_lines": 150, "content": lines});
    let summary = summarize_file_read(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("line 0"), "head present");
    assert!(
        summary.contains("line 149"),
        "last line must not be dropped"
    );
    assert!(
        summary.contains("line 120"),
        "mid-tail line must be present"
    );
    assert!(
        !summary.contains("lines omitted"),
        "nothing is actually omitted at 150 lines"
    );
}

// =========================================================================
// summarize_git_diff tests
// =========================================================================

#[test]
fn test_summarize_git_diff_single_file() {
    let diff = "diff --git a/src/main.rs b/src/main.rs\n--- a/src/main.rs\n+++ b/src/main.rs\n+added line\n-removed line\n+another add";
    let raw = serde_json::json!({"diff": diff});
    let summary = summarize_git_diff(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("1 files changed"));
    assert!(summary.contains("+2"));
    assert!(summary.contains("-1"));
}

#[test]
fn test_summarize_git_diff_multiple_files() {
    let diff = "diff --git a/a.rs b/a.rs\n+line1\ndiff --git a/b.rs b/b.rs\n-line2";
    let raw = serde_json::json!({"diff": diff});
    let summary = summarize_git_diff(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("2 files changed"));
}

#[test]
fn test_summarize_git_diff_empty() {
    let raw = serde_json::json!({"diff": ""});
    let summary = summarize_git_diff(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("0 files changed"));
}

// =========================================================================
// summarize_bulk_read tests
// =========================================================================

#[test]
fn test_summarize_bulk_read() {
    let raw = serde_json::json!({"loaded": 5, "skipped": 2, "tokens_added": 10000});
    let summary = summarize_bulk_read(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("5 files loaded"));
    assert!(summary.contains("2 skipped"));
    assert!(summary.contains("10000 tokens"));
}

#[test]
fn test_summarize_bulk_read_empty() {
    let raw = serde_json::json!({});
    let summary = summarize_bulk_read(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("0 files loaded"));
}

// =========================================================================
// summarize_shell_exec tests
// =========================================================================

#[test]
fn test_summarize_shell_exec_basic() {
    let raw = serde_json::json!({
        "exit_code": 0,
        "stdout": "Hello World\nLine 2",
        "stderr": ""
    });
    let summary = summarize_shell_exec(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("Exit code: 0"));
    assert!(summary.contains("Hello World"));
}

#[test]
fn test_summarize_shell_exec_with_stderr() {
    let raw = serde_json::json!({
        "exit_code": 1,
        "stdout": "",
        "stderr": "error: something failed"
    });
    let summary = summarize_shell_exec(&serde_json::to_string(&raw).unwrap());
    assert!(summary.contains("Exit code: 1"));
    assert!(summary.contains("error: something failed"));
}

// =========================================================================
// summarize_generic tests
// =========================================================================

#[test]
fn test_summarize_generic_short() {
    // Small results are now returned verbatim (no head/tail elision needed),
    // so no summary/stats banner is added.
    let summary = summarize_generic("hello world");
    assert_eq!(summary, "hello world");
}

#[test]
fn test_summarize_generic_long() {
    let long = "x".repeat(20000);
    let summary = summarize_generic(&long);
    assert!(summary.contains("see raw file"));
}

// =========================================================================
// task_requires_mutation tests
// =========================================================================

#[test]
fn test_task_requires_mutation_fix() {
    assert!(task_requires_mutation("Fix the failing test"));
}

#[test]
fn test_task_requires_mutation_respects_negation() {
    // Regression: a read-only review whose prompt says "do NOT edit" must not
    // be classified as mutation-required just because it contains "edit".
    assert!(!task_requires_mutation(
        "Review the codebase and produce a report. Do NOT edit any files."
    ));
    assert!(!task_requires_mutation(
        "Analyze src/ for dead code without modifying anything; output your findings."
    ));
    // But an un-negated mutation verb still wins even alongside a negation.
    assert!(task_requires_mutation(
        "Fix the bug, but do not edit the tests."
    ));
    // Plain mutation instructions are unaffected.
    assert!(task_requires_mutation("edit main.rs to add a field"));
}

#[test]
fn test_task_requires_mutation_make_imperative() {
    // Regression (MUT-MAKE-VERB): "Make X return Y" with no other mutation
    // verb must be treated as a mutation task so the safety gates arm.
    assert!(task_requires_mutation(
        "Make parse_port return Result<u16, String> instead of panicking"
    ));
    assert!(task_requires_mutation("Make the function generic over T"));
    // But qualifier phrases are not mutations on their own.
    assert!(!task_requires_mutation(
        "Make sure you understand how the parser works"
    ));
    assert!(!task_requires_mutation("Explain the makefile targets"));
    assert!(!task_requires_mutation(
        "Review the code but do not make any changes"
    ));
}

#[test]
fn test_task_requires_mutation_implement() {
    assert!(task_requires_mutation("Implement the new feature"));
}

#[test]
fn test_task_requires_mutation_edit() {
    assert!(task_requires_mutation("Edit the config file"));
}

#[test]
fn test_task_requires_mutation_modify() {
    assert!(task_requires_mutation("Modify the agent loop"));
}

#[test]
fn test_task_requires_mutation_update() {
    assert!(task_requires_mutation("Update the dependencies"));
}

#[test]
fn test_task_requires_mutation_write() {
    assert!(task_requires_mutation("Write the new module"));
}

#[test]
fn test_task_requires_mutation_create() {
    assert!(task_requires_mutation("Create a new tool"));
}

#[test]
fn test_task_requires_mutation_review_deliverable_is_read_only() {
    // "Create a code review" is read-only despite the word "create".
    assert!(!task_requires_mutation(
        "Create a thorough code review of src/agent/verification.rs with line references"
    ));
    assert!(!task_requires_mutation("Audit the auth module for issues"));
    // But a review paired with a real edit verb is still a mutation task.
    assert!(task_requires_mutation(
        "Review the code and fix the bug in parser.rs"
    ));
    // And an ordinary "create a tool" stays a mutation task.
    assert!(task_requires_mutation("Create a new benchmark tool"));
}

#[test]
fn test_task_requires_mutation_prose_deliverable_is_read_only() {
    // Prose deliverables are read-only despite the create/write verbs.
    assert!(!task_requires_mutation("Create a summary of the auth flow"));
    assert!(!task_requires_mutation(
        "Write a report on the test coverage"
    ));
    assert!(!task_requires_mutation(
        "Explain how the completion gate works"
    ));
    assert!(!task_requires_mutation("Summarize the recent changes"));
    // But naming a code artifact makes it a genuine mutation task.
    assert!(task_requires_mutation("Write a report generator function"));
    assert!(task_requires_mutation(
        "Create a summary parser in parser.rs"
    ));
}

#[test]
fn test_task_requires_mutation_refactor() {
    assert!(task_requires_mutation("Refactor the parser"));
}

#[test]
fn test_task_requires_mutation_rename() {
    assert!(task_requires_mutation("Rename the variable"));
}

#[test]
fn test_task_requires_mutation_delete() {
    assert!(task_requires_mutation("Delete the unused file"));
}

#[test]
fn test_task_requires_mutation_remove() {
    assert!(task_requires_mutation("Remove dead code"));
}

#[test]
fn test_task_requires_mutation_make_tests_pass() {
    assert!(task_requires_mutation("Make tests pass"));
}

#[test]
fn test_task_requires_mutation_until_green() {
    assert!(task_requires_mutation("Keep going until green"));
}

#[test]
fn test_task_no_mutation_read() {
    assert!(!task_requires_mutation("Read the log file"));
}

#[test]
fn test_task_no_mutation_explore() {
    assert!(!task_requires_mutation("Explore the codebase structure"));
}

#[test]
fn test_task_no_mutation_understand() {
    assert!(!task_requires_mutation("Understand how the system works"));
}

// =========================================================================
// shell_command_is_observational tests
// =========================================================================

#[test]
fn test_observational_cargo_test() {
    assert!(shell_command_is_observational("cargo test"));
}

#[test]
fn test_observational_cargo_check() {
    assert!(shell_command_is_observational("cargo check"));
}

#[test]
fn test_observational_cargo_clippy() {
    assert!(shell_command_is_observational("cargo clippy"));
}

#[test]
fn test_observational_git_status() {
    assert!(shell_command_is_observational("git status"));
}

#[test]
fn test_observational_git_diff() {
    assert!(shell_command_is_observational("git diff"));
}

#[test]
fn test_observational_git_log() {
    assert!(shell_command_is_observational("git log"));
}

#[test]
fn test_observational_ls() {
    assert!(shell_command_is_observational("ls"));
}

#[test]
fn test_observational_pwd() {
    assert!(shell_command_is_observational("pwd"));
}

#[test]
fn test_observational_find() {
    assert!(shell_command_is_observational("find . -name '*.rs'"));
}

#[test]
fn test_observational_grep() {
    assert!(shell_command_is_observational("grep -r 'pattern'"));
}

#[test]
fn test_observational_cat() {
    assert!(shell_command_is_observational("cat file.txt"));
}

#[test]
fn test_observational_head() {
    assert!(shell_command_is_observational("head -20 file.txt"));
}

#[test]
fn test_observational_tail() {
    assert!(shell_command_is_observational("tail -f log.txt"));
}

#[test]
fn test_observational_wc() {
    assert!(shell_command_is_observational("wc -l file.txt"));
}

#[test]
fn test_observational_tree() {
    assert!(shell_command_is_observational("tree src/"));
}

#[test]
fn test_observational_which() {
    assert!(shell_command_is_observational("which cargo"));
}

#[test]
fn test_observational_echo() {
    assert!(shell_command_is_observational("echo hello"));
}

#[test]
fn test_observational_pytest() {
    assert!(shell_command_is_observational("pytest tests/"));
}

#[test]
fn test_observational_sed_n() {
    assert!(shell_command_is_observational("sed -n '1,10p' file.txt"));
}

#[test]
fn test_not_observational_cargo_fmt() {
    assert!(!shell_command_is_observational("cargo fmt"));
}

#[test]
fn test_not_observational_cargo_fix() {
    assert!(!shell_command_is_observational("cargo fix"));
}

#[test]
fn test_not_observational_cargo_update() {
    assert!(!shell_command_is_observational("cargo update"));
}

#[test]
fn test_not_observational_mkdir() {
    assert!(!shell_command_is_observational("mkdir new_dir"));
}

#[test]
fn test_not_observational_touch() {
    assert!(!shell_command_is_observational("touch file.txt"));
}

#[test]
fn test_not_observational_rm() {
    assert!(!shell_command_is_observational("rm file.txt"));
}

#[test]
fn test_not_observational_mv() {
    assert!(!shell_command_is_observational("mv a.txt b.txt"));
}

#[test]
fn test_not_observational_cp() {
    assert!(!shell_command_is_observational("cp a.txt b.txt"));
}

#[test]
fn test_not_observational_sed_inplace() {
    assert!(!shell_command_is_observational(
        "sed -i 's/foo/bar/' file.txt"
    ));
}

#[test]
fn test_not_observational_git_add() {
    assert!(!shell_command_is_observational("git add ."));
}

#[test]
fn test_not_observational_git_commit() {
    assert!(!shell_command_is_observational("git commit -m 'msg'"));
}

#[test]
fn test_not_observational_redirect() {
    assert!(!shell_command_is_observational("echo hi > file.txt"));
}

#[test]
fn test_not_observational_npm_install() {
    assert!(!shell_command_is_observational("npm install express"));
}

#[test]
fn test_not_observational_pip_install() {
    assert!(!shell_command_is_observational("pip install requests"));
}

#[test]
fn test_observational_empty() {
    assert!(!shell_command_is_observational(""));
}

// =========================================================================
// tool_call_is_observational tests
// =========================================================================

#[test]
fn test_observational_file_read() {
    assert!(tool_call_is_observational("file_read", "{}"));
}

#[test]
fn test_observational_directory_tree() {
    assert!(tool_call_is_observational("directory_tree", "{}"));
}

#[test]
fn test_observational_glob_find() {
    assert!(tool_call_is_observational("glob_find", "{}"));
}

#[test]
fn test_observational_grep_search() {
    assert!(tool_call_is_observational("grep_search", "{}"));
}

#[test]
fn test_observational_symbol_search() {
    assert!(tool_call_is_observational("symbol_search", "{}"));
}

#[test]
fn test_observational_git_status_tool() {
    assert!(tool_call_is_observational("git_status", "{}"));
}

#[test]
fn test_observational_cargo_check_tool() {
    assert!(tool_call_is_observational("cargo_check", "{}"));
}

#[test]
fn test_observational_cargo_test_tool() {
    assert!(tool_call_is_observational("cargo_test", "{}"));
}

#[test]
fn test_not_observational_file_write() {
    assert!(!tool_call_is_observational("file_write", "{}"));
}

#[test]
fn test_not_observational_file_edit() {
    assert!(!tool_call_is_observational("file_edit", "{}"));
}

#[test]
fn test_observational_shell_exec_read_only() {
    assert!(tool_call_is_observational(
        "shell_exec",
        r#"{"command":"cargo test"}"#
    ));
}

#[test]
fn test_not_observational_shell_exec_mutating() {
    assert!(!tool_call_is_observational(
        "shell_exec",
        r#"{"command":"cargo fmt"}"#
    ));
}

#[test]
fn test_not_observational_shell_exec_no_command() {
    assert!(!tool_call_is_observational("shell_exec", "{}"));
}

// =========================================================================
// tool_call_counts_as_state_change tests
// =========================================================================

#[test]
fn test_state_change_file_write() {
    assert!(tool_call_counts_as_state_change("file_write", "{}"));
}

#[test]
fn test_state_change_file_edit() {
    assert!(tool_call_counts_as_state_change("file_edit", "{}"));
}

#[test]
fn test_no_state_change_file_read() {
    assert!(!tool_call_counts_as_state_change("file_read", "{}"));
}

#[test]
fn test_no_state_change_cargo_check() {
    assert!(!tool_call_counts_as_state_change("cargo_check", "{}"));
}

#[test]
fn test_no_state_change_cargo_test() {
    assert!(!tool_call_counts_as_state_change("cargo_test", "{}"));
}

#[test]
fn test_no_state_change_cargo_clippy() {
    assert!(!tool_call_counts_as_state_change("cargo_clippy", "{}"));
}

// =========================================================================
// extract_backticked_tool_names tests
// =========================================================================

#[test]
fn test_extract_backticked_tool_names_basic() {
    let names = extract_backticked_tool_names("Use `file_read` and `file_edit`");
    assert_eq!(names, vec!["file_read", "file_edit"]);
}

#[test]
fn test_extract_backticked_tool_names_empty() {
    let names = extract_backticked_tool_names("no tools here");
    assert!(names.is_empty());
}

#[test]
fn test_extract_backticked_tool_names_invalid_chars() {
    let names = extract_backticked_tool_names("Use `File Read` and `hello-world`");
    // Only lowercase, digits, underscore
    assert!(names.is_empty());
}

#[test]
fn test_extract_backticked_tool_names_single() {
    let names = extract_backticked_tool_names("`shell_exec`");
    assert_eq!(names, vec!["shell_exec"]);
}

#[test]
fn test_extract_backticked_tool_names_with_digits() {
    let names = extract_backticked_tool_names("`tool_v2`");
    assert_eq!(names, vec!["tool_v2"]);
}

// =========================================================================
// extract_explicit_allowed_tools tests
// =========================================================================

#[test]
fn test_extract_allowed_tools_no_section() {
    let task = "Just do something useful.";
    assert!(extract_explicit_allowed_tools(task).is_none());
}

#[test]
fn test_extract_allowed_tools_with_bullets() {
    let task = "Use only these concrete tools:\n- `file_read`\n- `shell_exec`\n\nDo the task.";
    let allowed = extract_explicit_allowed_tools(task).unwrap();
    assert!(allowed.contains("file_read"));
    assert!(allowed.contains("shell_exec"));
    assert_eq!(allowed.len(), 2);
}

#[test]
fn test_extract_allowed_tools_case_variations() {
    let task = "Allowed tools:\n- `grep_search`\n- `glob_find`\n";
    let allowed = extract_explicit_allowed_tools(task).unwrap();
    assert!(allowed.contains("grep_search"));
    assert!(allowed.contains("glob_find"));
}

// =========================================================================
// extract_explicit_disallowed_tools tests
// =========================================================================

#[test]
fn test_extract_disallowed_never_call() {
    let task = "Never call `tool_search`.";
    let disallowed = extract_explicit_disallowed_tools(task);
    assert!(disallowed.contains("tool_search"));
}

#[test]
fn test_extract_disallowed_do_not_use() {
    let task = "Do not use `file_delete`.";
    let disallowed = extract_explicit_disallowed_tools(task);
    assert!(disallowed.contains("file_delete"));
}

#[test]
fn test_extract_disallowed_dont_use() {
    let task = "Don't use `shell_exec`.";
    let disallowed = extract_explicit_disallowed_tools(task);
    assert!(disallowed.contains("shell_exec"));
}

#[test]
fn test_extract_disallowed_avoid() {
    let task = "Avoid `git_commit` for now.";
    let disallowed = extract_explicit_disallowed_tools(task);
    assert!(disallowed.contains("git_commit"));
}

#[test]
fn test_extract_disallowed_shell_category() {
    let task = "Do not run shell commands or use pty_shell.";
    let disallowed = extract_explicit_disallowed_tools(task);
    assert!(disallowed.contains("shell_exec"));
    assert!(disallowed.contains("pty_shell"));
}

#[test]
fn test_extract_disallowed_empty() {
    let task = "Just do the task.";
    let disallowed = extract_explicit_disallowed_tools(task);
    assert!(disallowed.is_empty());
}

// =========================================================================
// insert_missing_tool_arg tests
// =========================================================================

#[test]
fn test_insert_missing_arg_adds_when_absent() {
    let mut obj = serde_json::Map::new();
    let inserted = insert_missing_tool_arg(&mut obj, "key", serde_json::json!("value"));
    assert!(inserted);
    assert_eq!(obj["key"], "value");
}

#[test]
fn test_insert_missing_arg_skips_when_present() {
    let mut obj = serde_json::Map::new();
    obj.insert("key".to_string(), serde_json::json!("existing"));
    let inserted = insert_missing_tool_arg(&mut obj, "key", serde_json::json!("new"));
    assert!(!inserted);
    assert_eq!(obj["key"], "existing");
}

#[test]
fn test_insert_missing_arg_replaces_null() {
    let mut obj = serde_json::Map::new();
    obj.insert("key".to_string(), serde_json::Value::Null);
    let inserted = insert_missing_tool_arg(&mut obj, "key", serde_json::json!("value"));
    assert!(inserted);
    assert_eq!(obj["key"], "value");
}

// =========================================================================
// shell_exec mutating-counter classification (#4)
// =========================================================================

/// Helper that mirrors the increment-site's classification predicate so we
/// can unit-test it without spinning up a full agent loop.
fn classify_shell_as_mutating(name: &str, command: Option<&str>) -> bool {
    if matches!(
        name,
        "file_edit" | "file_write" | "file_delete" | "file_fim_edit"
    ) {
        return true;
    }
    if name == "shell_exec" {
        if let Some(cmd) = command {
            return !shell_command_is_observational(cmd);
        }
    }
    false
}

#[test]
fn shell_exec_cargo_check_does_not_count_as_mutating() {
    assert!(!classify_shell_as_mutating(
        "shell_exec",
        Some("cargo check")
    ));
    assert!(!classify_shell_as_mutating(
        "shell_exec",
        Some("git status")
    ));
    assert!(!classify_shell_as_mutating("shell_exec", Some("ls -la")));
}

#[test]
fn shell_exec_mutating_commands_count_as_mutating() {
    // git add / rm / cargo fmt / mv / sed -i — all should bump the counter.
    assert!(classify_shell_as_mutating(
        "shell_exec",
        Some("git add src/")
    ));
    assert!(classify_shell_as_mutating(
        "shell_exec",
        Some("rm /tmp/foo")
    ));
    assert!(classify_shell_as_mutating("shell_exec", Some("cargo fmt")));
    assert!(classify_shell_as_mutating(
        "shell_exec",
        Some("mv a.txt b.txt")
    ));
    assert!(classify_shell_as_mutating(
        "shell_exec",
        Some("sed -i 's/a/b/' file.rs")
    ));
    // file_* tools are always mutating.
    assert!(classify_shell_as_mutating("file_write", None));
    assert!(classify_shell_as_mutating("file_edit", None));
}

#[tokio::test]
async fn tui_permission_response_denies_when_no_channel_wired() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    // No channel wired at all -- must fail closed, not auto-approve.
    assert!(!agent.await_tui_permission_response().await);
    server.stop().await;
}

#[cfg(feature = "tui")]
#[tokio::test]
async fn tui_permission_response_relays_user_answer() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    let (tx, rx) = std::sync::mpsc::channel();
    agent = agent.with_permission_channel(rx);
    tx.send(true).unwrap();
    assert!(agent.await_tui_permission_response().await);

    let (tx, rx) = std::sync::mpsc::channel();
    agent = agent.with_permission_channel(rx);
    tx.send(false).unwrap();
    assert!(!agent.await_tui_permission_response().await);

    server.stop().await;
}

#[cfg(feature = "tui")]
#[tokio::test]
async fn tui_permission_response_denies_when_sender_dropped() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    let (tx, rx) = std::sync::mpsc::channel::<bool>();
    agent = agent.with_permission_channel(rx);
    drop(tx); // simulate the TUI thread exiting without answering

    assert!(!agent.await_tui_permission_response().await);
    server.stop().await;
}

#[tokio::test]
async fn yolo_gate_blocks_protected_path_write() {
    // YoloConfig's protected_paths (e.g. /etc) apply to any tool with a
    // path/file/directory argument, independent of the pre-existing
    // SafetyChecker/path_validator's allowed_paths -- this test's config
    // permissively allows "/**" and only denies .env/.ssh/secrets, so
    // /etc is only blocked because of the (newly wired-in) YOLO gate.
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![(
            "file_write".to_string(),
            r#"{"path":"/etc/selfware-test.conf","content":"x"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    let last = agent.messages.last().expect("expected a skip message");
    assert!(last.content.text().contains("Blocked by YOLO safety gate"));
    server.stop().await;
}

#[tokio::test]
async fn yolo_gate_applies_in_parallel_batch_too() {
    // Regression test: execute_parallel_tools (used when 2+ tools in a
    // batch are in PARALLEL_SAFE_TOOLS) never called
    // confirm_tool_execution at all, so the YOLO gate silently didn't
    // apply to any tool executed that way -- a file_read of a
    // YOLO-protected path would be Block-ed via the sequential path but
    // ran unchecked here just because a second parallel-safe call
    // happened to land in the same batch. Uses two file_read calls
    // (file_read is parallel-safe) to force the parallel path.
    let _g = crate::test_support::ExecGuard::hold();
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![
            // /etc/hostname (not /etc/passwd -- that one's already
            // caught by an earlier, narrower hardcoded dangerous-files
            // list in path_validator.rs, which would pass regardless of
            // this fix and defeat the point of this test).
            (
                "file_read".to_string(),
                r#"{"path":"/etc/hostname"}"#.to_string(),
                None,
            ),
            (
                "file_read".to_string(),
                r#"{"path":"Cargo.toml"}"#.to_string(),
                None,
            ),
        ])
        .await
        .unwrap();

    let all_text: String = agent
        .messages
        .iter()
        .map(|m| m.content.text())
        .collect::<Vec<_>>()
        .join("\n---\n");
    assert!(
        all_text.contains("Blocked by YOLO safety gate"),
        "expected the /etc/hostname read to be blocked; got: {all_text}"
    );
    // The unrelated, unprotected read should have gone through untouched.
    assert!(
        all_text.contains("[package]"),
        "expected the Cargo.toml read to succeed; got: {all_text}"
    );
    server.stop().await;
}

#[tokio::test]
async fn yolo_gate_denies_destructive_shell_without_operator() {
    // Destructive but not forbidden -- YoloDecision::RequireConfirmation.
    // No CLI/TUI operator is attached in this test harness, so it must
    // fail closed rather than hang or silently auto-approve.
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![(
            "shell_exec".to_string(),
            r#"{"command":"rm -rf ./scratch"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    let last = agent.messages.last().expect("expected a skip message");
    assert!(last.content.text().contains("unattended session"));
    server.stop().await;
}

#[tokio::test]
async fn yolo_gate_allows_non_destructive_shell_command() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = test_config(format!("{}/v1", server.url()));
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![(
            "shell_exec".to_string(),
            r#"{"command":"echo hello"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    let last = agent.messages.last().expect("expected a tool result");
    assert!(!last.content.text().contains("Blocked by YOLO safety gate"));
    assert!(!last.content.text().contains("unattended session"));
    server.stop().await;
}

#[tokio::test]
async fn yolo_gate_denies_git_push_when_disallowed() {
    // Push to a non-protected branch so this exercises the YOLO gate's
    // own git-push handling specifically, not the separate
    // protected_branches check (covered below).
    let server = MockLlmServer::builder().with_response("done").build().await;
    let mut config = test_config(format!("{}/v1", server.url()));
    config.yolo.allow_git_push = false;
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![(
            "git_push".to_string(),
            r#"{"branch":"feature-branch"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    let last = agent.messages.last().expect("expected a skip message");
    assert!(last.content.text().contains("unattended session"));
    server.stop().await;
}

#[tokio::test]
async fn git_push_to_protected_branch_is_blocked_even_with_git_push_allowed() {
    // protected_branches is a hard block, distinct from (and checked
    // before) the YOLO allow_git_push toggle -- allowing git_push in
    // general must not bypass it.
    let server = MockLlmServer::builder().with_response("done").build().await;
    let mut config = test_config(format!("{}/v1", server.url()));
    config.yolo.allow_git_push = true;
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![(
            "git_push".to_string(),
            r#"{"branch":"main"}"#.to_string(),
            None,
        )])
        .await
        .unwrap();

    let last = agent.messages.last().expect("expected a skip message");
    assert!(last.content.text().contains("protected branch"));
    server.stop().await;
}

#[tokio::test]
async fn confirmation_error_in_batch_still_pushes_tool_result() {
    // Regression: when execute_single_tool_in_batch returns Err BEFORE
    // pushing a tool-result (e.g. confirmation rejection in non-YOLO
    // headless mode), the catch-and-continue loop must push a synthetic
    // error result for that tool_call_id so native-FC history stays
    // balanced (N calls → N results).  Without the fix, the tool_call_id
    // had NO result → 400 on the next API call.
    //
    // We use Normal mode (not Yolo) so confirmation is required for
    // file_write.  In the test runner stdin is not a terminal, so
    // confirm_tool_execution returns Err("requires confirmation but
    // cannot prompt in headless mode").  The fix pushes a synthetic
    // error result and the batch continues with the second tool.
    let server = MockLlmServer::builder().with_response("done").build().await;
    let mut config = test_config(format!("{}/v1", server.url()));
    config.execution_mode = crate::config::ExecutionMode::Normal;
    let mut agent = Agent::new(config).await.unwrap();

    agent
        .execute_tool_batch(vec![
            (
                "file_write".to_string(),
                r#"{"path":"/tmp/selfware-test-confirm.txt","content":"x"}"#.to_string(),
                Some("call_confirm_err".to_string()),
            ),
            // A second tool that should still execute.
            (
                "shell_exec".to_string(),
                r#"{"command":"echo hello"}"#.to_string(),
                Some("call_after_err".to_string()),
            ),
        ])
        .await
        .unwrap();

    let all_text: String = agent
        .messages
        .iter()
        .map(|m| m.content.text())
        .collect::<Vec<_>>()
        .join("\n---\n");

    // The confirmation-errored tool must have a synthetic error result
    // pushed (contains "headless mode" from the error message).
    assert!(
        all_text.contains("headless mode"),
        "expected a synthetic error result for the confirmation-errored tool; got: {all_text}"
    );
    // The second tool should also have executed (its result present).
    assert!(
            all_text.contains("hello"),
            "expected the second tool in the batch to still execute after the first errored; got: {all_text}"
        );

    server.stop().await;
}

#[tokio::test]
async fn run_tool_bounded_returns_result_when_fast() {
    use std::sync::atomic::AtomicBool;
    use std::sync::Arc;
    let cancel = Arc::new(AtomicBool::new(false));
    let fut = async { Ok(serde_json::json!({"ok": true})) };
    let out = run_tool_bounded(fut, std::time::Duration::from_secs(5), cancel).await;
    assert!(out.is_ok());
    assert!(out.unwrap().is_ok());
}

#[tokio::test]
async fn run_tool_bounded_times_out() {
    use std::sync::atomic::AtomicBool;
    use std::sync::Arc;
    let cancel = Arc::new(AtomicBool::new(false));
    let slow = async {
        tokio::time::sleep(std::time::Duration::from_secs(30)).await;
        Ok(serde_json::json!({}))
    };
    let out = run_tool_bounded(slow, std::time::Duration::from_millis(50), cancel).await;
    assert_eq!(out.unwrap_err(), ToolHalt::TimedOut);
}

#[tokio::test]
async fn run_tool_bounded_cancels_in_flight() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    let cancel = Arc::new(AtomicBool::new(false));
    let c2 = cancel.clone();
    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
        c2.store(true, Ordering::Relaxed);
    });
    let slow = async {
        tokio::time::sleep(std::time::Duration::from_secs(30)).await;
        Ok(serde_json::json!({}))
    };
    // Deadline is long (10s) so the ONLY way this returns quickly is cancellation.
    let out = run_tool_bounded(slow, std::time::Duration::from_secs(10), cancel).await;
    assert_eq!(out.unwrap_err(), ToolHalt::Cancelled);
}

#[tokio::test]
async fn run_tool_bounded_fast_path_already_cancelled() {
    use std::sync::atomic::AtomicBool;
    use std::sync::Arc;
    let cancel = Arc::new(AtomicBool::new(true));
    let fut = async { Ok(serde_json::json!({})) };
    let out = run_tool_bounded(fut, std::time::Duration::from_secs(5), cancel).await;
    assert_eq!(out.unwrap_err(), ToolHalt::Cancelled);
}

#[test]
fn mutating_predicate_covers_all_real_editors() {
    use serde_json::json;
    let empty = json!({});
    // Direct editors — including the previously-missed ones.
    for t in [
        "file_edit",
        "file_write",
        "file_delete",
        "file_fim_edit",
        "file_multi_edit",
        "patch_apply",
    ] {
        assert!(tool_call_is_mutating(t, &empty), "{t} should be mutating");
    }
    // Mutating git ops.
    for t in ["git_commit", "git_add", "git_apply", "git_reset"] {
        assert!(tool_call_is_mutating(t, &empty), "{t} should be mutating");
    }
    // Observational tools are NOT mutating.
    for t in [
        "file_read",
        "git_status",
        "git_log",
        "git_diff",
        "grep",
        "list_dir",
    ] {
        assert!(
            !tool_call_is_mutating(t, &empty),
            "{t} should NOT be mutating"
        );
    }
    // Shell is mutating only for non-observational commands.
    assert!(tool_call_is_mutating(
        "shell_exec",
        &json!({"command": "rm -rf build"})
    ));
    assert!(tool_call_is_mutating(
        "shell_exec",
        &json!({"command": "npm install"})
    ));
    assert!(!tool_call_is_mutating(
        "shell_exec",
        &json!({"command": "cargo check"})
    ));
    assert!(!tool_call_is_mutating(
        "shell_exec",
        &json!({"command": "git status"})
    ));
}

#[tokio::test]
async fn over_budget_batch_does_not_execute_tools() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let mut config = test_config(format!("{}/v1", server.url()));
    config.agent.max_budget_tokens = Some(1);
    let mut agent = Agent::new(config).await.unwrap();
    // Drive cumulative usage over the 1-token cap.
    agent.cumulative_token_usage.total = 100;

    // A file_write whose target must NOT be created once we are over budget.
    let marker = std::env::temp_dir().join(format!("sw_budget_guard_{}.tmp", std::process::id()));
    let _ = std::fs::remove_file(&marker);

    let result = agent
        .execute_tool_batch(vec![(
            "file_write".to_string(),
            serde_json::json!({"path": marker.to_string_lossy(), "content": "x"}).to_string(),
            None,
        )])
        .await;

    assert!(
        result.is_err(),
        "over-budget batch must bail before executing tools"
    );
    assert!(
        result
            .unwrap_err()
            .to_string()
            .to_lowercase()
            .contains("budget"),
        "error should mention the budget"
    );
    assert!(
        !marker.exists(),
        "over-budget batch must NOT run the file_write"
    );
    let _ = std::fs::remove_file(&marker);

    server.stop().await;
}