yoyo-agent 0.1.8

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

use crate::commands::auto_compact_if_needed;
use crate::format::*;
use crate::git::*;
use crate::prompt::*;

use std::io::{self, Write};
use yoagent::agent::Agent;
use yoagent::*;

// ── /diff ────────────────────────────────────────────────────────────────

/// A parsed line from `git diff --stat` output.
/// Example: " src/main.rs | 42 +++++++++-------"
#[derive(Debug, Clone, PartialEq)]
pub struct DiffStatEntry {
    pub file: String,
    pub insertions: u32,
    pub deletions: u32,
}

/// Summary totals from `git diff --stat` output.
#[derive(Debug, Clone, PartialEq)]
pub struct DiffStatSummary {
    pub entries: Vec<DiffStatEntry>,
    pub total_insertions: u32,
    pub total_deletions: u32,
}

/// Parse `git diff --stat` output into structured entries.
///
/// Each line looks like:
///   " src/commands.rs | 42 +++++++++-------"
/// The last line is a summary like:
///   " 3 files changed, 25 insertions(+), 10 deletions(-)"
pub fn parse_diff_stat(stat_output: &str) -> DiffStatSummary {
    let mut entries = Vec::new();
    let mut total_insertions: u32 = 0;
    let mut total_deletions: u32 = 0;

    for line in stat_output.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Try to parse summary line: "N file(s) changed, N insertion(s)(+), N deletion(s)(-)"
        if trimmed.contains("changed")
            && (trimmed.contains("insertion") || trimmed.contains("deletion"))
        {
            // Parse insertions
            if let Some(ins_part) = trimmed.split("insertion").next() {
                if let Some(num_str) = ins_part.split(',').next_back() {
                    if let Ok(n) = num_str.trim().parse::<u32>() {
                        total_insertions = n;
                    }
                }
            }
            // Parse deletions
            if let Some(del_part) = trimmed.split("deletion").next() {
                if let Some(num_str) = del_part.split(',').next_back() {
                    if let Ok(n) = num_str.trim().parse::<u32>() {
                        total_deletions = n;
                    }
                }
            }
            continue;
        }

        // Try to parse file entry: "file | N +++---" or "file | Bin 0 -> 1234 bytes"
        if let Some(pipe_pos) = trimmed.find('|') {
            let file = trimmed[..pipe_pos].trim().to_string();
            let stats_part = trimmed[pipe_pos + 1..].trim();

            if file.is_empty() {
                continue;
            }

            // Count + and - characters in the visual bar
            let insertions = stats_part.chars().filter(|&c| c == '+').count() as u32;
            let deletions = stats_part.chars().filter(|&c| c == '-').count() as u32;

            entries.push(DiffStatEntry {
                file,
                insertions,
                deletions,
            });
        }
    }

    // If no summary line was found, compute totals from entries
    if total_insertions == 0 && total_deletions == 0 {
        total_insertions = entries.iter().map(|e| e.insertions).sum();
        total_deletions = entries.iter().map(|e| e.deletions).sum();
    }

    DiffStatSummary {
        entries,
        total_insertions,
        total_deletions,
    }
}

/// Format a diff stat summary with colors for display.
pub fn format_diff_stat(summary: &DiffStatSummary) -> String {
    let mut output = String::new();

    if summary.entries.is_empty() {
        return output;
    }

    // Find max filename length for alignment
    let max_name_len = summary
        .entries
        .iter()
        .map(|e| e.file.len())
        .max()
        .unwrap_or(0);

    output.push_str(&format!("{DIM}  File summary:{RESET}\n"));
    for entry in &summary.entries {
        let total_changes = entry.insertions + entry.deletions;
        let ins_str = if entry.insertions > 0 {
            format!("{GREEN}+{}{RESET}", entry.insertions)
        } else {
            String::new()
        };
        let del_str = if entry.deletions > 0 {
            format!("{RED}-{}{RESET}", entry.deletions)
        } else {
            String::new()
        };
        let sep = if entry.insertions > 0 && entry.deletions > 0 {
            " "
        } else {
            ""
        };
        output.push_str(&format!(
            "    {:<width$}  {}{DIM}{:>4}{RESET} {ins_str}{sep}{del_str}\n",
            entry.file,
            "",
            total_changes,
            width = max_name_len,
        ));
    }

    // Summary line
    let files_count = summary.entries.len();
    output.push_str(&format!(
        "\n  {DIM}{files_count} file{s} changed{RESET}",
        s = if files_count == 1 { "" } else { "s" }
    ));
    if summary.total_insertions > 0 {
        output.push_str(&format!(", {GREEN}+{}{RESET}", summary.total_insertions));
    }
    if summary.total_deletions > 0 {
        output.push_str(&format!(", {RED}-{}{RESET}", summary.total_deletions));
    }
    output.push('\n');

    output
}

/// Parsed options for the `/diff` command.
#[derive(Debug, Clone, PartialEq)]
pub struct DiffOptions {
    pub staged_only: bool,
    pub name_only: bool,
    pub file: Option<String>,
}

/// Parse `/diff` arguments into structured options.
///
/// Supports:
/// - `/diff` — all changes (default)
/// - `/diff --staged` or `/diff --cached` — staged only
/// - `/diff --name-only` — filenames only
/// - `/diff <file>` — diff for a specific file
/// - Combined: `/diff --staged --name-only src/main.rs`
pub fn parse_diff_args(input: &str) -> DiffOptions {
    let rest = input.strip_prefix("/diff").unwrap_or("").trim();
    let parts: Vec<&str> = rest.split_whitespace().collect();
    let mut staged_only = false;
    let mut name_only = false;
    let mut file = None;

    for part in parts {
        match part {
            "--staged" | "--cached" => staged_only = true,
            "--name-only" => name_only = true,
            _ => file = Some(part.to_string()),
        }
    }

    DiffOptions {
        staged_only,
        name_only,
        file,
    }
}

pub fn handle_diff(input: &str) {
    let opts = parse_diff_args(input);

    // Check if we're in a git repo
    match run_git(&["status", "--short"]) {
        Ok(status) if status.is_empty() => {
            println!("{DIM}  (no uncommitted changes){RESET}\n");
        }
        Ok(_status) => {
            // ── Name-only mode: just list changed filenames ──────────
            if opts.name_only {
                let mut args = vec!["diff", "--name-only"];
                if opts.staged_only {
                    args.push("--cached");
                }
                let file_ref;
                if let Some(ref f) = opts.file {
                    args.push("--");
                    file_ref = f.as_str();
                    args.push(file_ref);
                }
                let names = run_git(&args).unwrap_or_default();
                // If not staged-only, also grab staged names
                if !opts.staged_only {
                    let mut staged_args = vec!["diff", "--name-only", "--cached"];
                    let staged_file_ref;
                    if let Some(ref f) = opts.file {
                        staged_args.push("--");
                        staged_file_ref = f.as_str();
                        staged_args.push(staged_file_ref);
                    }
                    let staged_names = run_git(&staged_args).unwrap_or_default();
                    // Combine and deduplicate
                    let mut all_files: Vec<&str> = names
                        .lines()
                        .chain(staged_names.lines())
                        .filter(|l| !l.trim().is_empty())
                        .collect();
                    all_files.sort();
                    all_files.dedup();
                    if all_files.is_empty() {
                        println!("{DIM}  (no changed files){RESET}\n");
                    } else {
                        println!("{DIM}  Changed files:{RESET}");
                        for f in &all_files {
                            println!("    {f}");
                        }
                        println!();
                    }
                } else if names.trim().is_empty() {
                    println!("{DIM}  (no staged files){RESET}\n");
                } else {
                    println!("{DIM}  Staged files:{RESET}");
                    for f in names.lines().filter(|l| !l.trim().is_empty()) {
                        println!("    {f}");
                    }
                    println!();
                }
                return;
            }

            // ── Staged-only mode ────────────────────────────────────
            if opts.staged_only {
                let mut stat_args = vec!["diff", "--cached", "--stat"];
                let stat_file_ref;
                if let Some(ref f) = opts.file {
                    stat_args.push("--");
                    stat_file_ref = f.as_str();
                    stat_args.push(stat_file_ref);
                }
                let stat_text = run_git(&stat_args).unwrap_or_default();

                if stat_text.trim().is_empty() {
                    println!("{DIM}  (no staged changes){RESET}\n");
                    return;
                }

                let summary = parse_diff_stat(&stat_text);
                let formatted = format_diff_stat(&summary);
                if !formatted.is_empty() {
                    print!("{formatted}");
                }

                // Full staged diff
                let mut diff_args = vec!["diff", "--cached"];
                let diff_file_ref;
                if let Some(ref f) = opts.file {
                    diff_args.push("--");
                    diff_file_ref = f.as_str();
                    diff_args.push(diff_file_ref);
                }
                let full_diff = run_git(&diff_args).unwrap_or_default();
                if !full_diff.trim().is_empty() {
                    println!("\n{DIM}  ── Staged diff ──{RESET}");
                    print!("{}", colorize_diff(&full_diff));
                    println!();
                }
                return;
            }

            // ── File-specific mode (unstaged + staged) ──────────────
            if let Some(ref file) = opts.file {
                let stat_text =
                    run_git(&["diff", "--stat", "--", file.as_str()]).unwrap_or_default();
                let staged_stat_text =
                    run_git(&["diff", "--cached", "--stat", "--", file.as_str()])
                        .unwrap_or_default();

                let combined_stat = combine_stats(&stat_text, &staged_stat_text);
                if combined_stat.trim().is_empty() {
                    println!("{DIM}  (no changes for {file}){RESET}\n");
                    return;
                }

                let summary = parse_diff_stat(&combined_stat);
                let formatted = format_diff_stat(&summary);
                if !formatted.is_empty() {
                    print!("{formatted}");
                }

                let full_diff = run_git(&["diff", "--", file.as_str()]).unwrap_or_default();
                let staged_diff =
                    run_git(&["diff", "--cached", "--", file.as_str()]).unwrap_or_default();
                let combined_diff = combine_stats(&full_diff, &staged_diff);
                if !combined_diff.trim().is_empty() {
                    println!("\n{DIM}  ── Diff for {file} ──{RESET}");
                    print!("{}", colorize_diff(&combined_diff));
                    println!();
                }
                return;
            }

            // ── Default: show all changes (original behavior) ───────
            let stat_text = run_git(&["diff", "--stat"]).unwrap_or_default();
            let staged_stat_text = run_git(&["diff", "--cached", "--stat"]).unwrap_or_default();

            // Show file status list
            println!("{DIM}  Changes:");
            for line in _status.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }
                let (color, rest) = if trimmed.len() >= 2 {
                    match trimmed.chars().next().unwrap_or(' ') {
                        'M' | 'A' | 'R' => (format!("{GREEN}"), trimmed),
                        'D' => (format!("{RED}"), trimmed),
                        '?' => (format!("{YELLOW}"), trimmed),
                        _ => (format!("{DIM}"), trimmed),
                    }
                } else {
                    (format!("{DIM}"), trimmed)
                };
                println!("    {color}{rest}{RESET}");
            }
            println!("{RESET}");

            let combined_stat = combine_stats(&stat_text, &staged_stat_text);
            if !combined_stat.trim().is_empty() {
                let summary = parse_diff_stat(&combined_stat);
                let formatted = format_diff_stat(&summary);
                if !formatted.is_empty() {
                    print!("{formatted}");
                }
            }

            let full_diff = run_git(&["diff"]).unwrap_or_default();
            if !full_diff.trim().is_empty() {
                println!("\n{DIM}  ── Full diff ──{RESET}");
                print!("{}", colorize_diff(&full_diff));
                println!();
            }
        }
        _ => eprintln!("{RED}  error: not in a git repository{RESET}\n"),
    }
}

/// Combine two stat/diff outputs, deduplicating if both are present.
fn combine_stats(a: &str, b: &str) -> String {
    if !a.trim().is_empty() && !b.trim().is_empty() {
        format!("{}\n{}", a, b)
    } else if !b.trim().is_empty() {
        b.to_string()
    } else {
        a.to_string()
    }
}

// ── /undo ────────────────────────────────────────────────────────────────

/// Build a context note describing what `/undo` reverted, for injection into
/// the agent's next turn so it knows files have changed under it.
fn build_undo_context(actions: &[String]) -> String {
    let count = actions.len();
    let file_word = crate::format::pluralize(count, "file", "files");
    let mut note =
        format!("[System note: /undo reverted {count} {file_word} from a previous turn:\n");
    for action in actions {
        note.push_str(&format!("- {action}\n"));
    }
    note.push_str(
        "⚠️ The code referenced in my previous response may no longer exist. \
         Re-read affected files before making new changes. \
         Verify current file state before continuing.]",
    );
    note
}

/// Handle `/undo` with per-turn granularity.
///
/// - `/undo` — undo the last agent turn (restore files to pre-turn state)
/// - `/undo N` — undo the last N turns
/// - `/undo --all` — nuclear option: revert ALL uncommitted changes (old behavior)
/// - `/undo --last-commit` — revert the most recent git commit via `git revert`
///
/// Returns `Some(context)` when files were actually reverted, so the REPL can
/// inject the summary into the agent's next turn for causal consistency.
pub fn handle_undo(input: &str, history: &mut crate::prompt::TurnHistory) -> Option<String> {
    let arg = input.strip_prefix("/undo").unwrap_or("").trim();

    // Nuclear fallback: /undo --all
    if arg == "--all" {
        return handle_undo_all(history);
    }

    // Revert last git commit: /undo --last-commit
    if arg == "--last-commit" {
        return handle_undo_last_commit();
    }

    // Parse optional count: /undo N
    let count: usize = if arg.is_empty() {
        1
    } else if let Ok(n) = arg.parse::<usize>() {
        if n == 0 {
            println!("{DIM}  (nothing to undo — count is 0){RESET}\n");
            return None;
        }
        n
    } else {
        println!("{DIM}  usage: /undo [N] | --all | --last-commit{RESET}\n");
        return None;
    };

    if history.is_empty() {
        // Fallback: check if there are uncommitted changes we could undo with --all
        let has_diff = !run_git(&["diff", "--stat"])
            .unwrap_or_default()
            .trim()
            .is_empty();
        let has_untracked = !run_git(&["ls-files", "--others", "--exclude-standard"])
            .unwrap_or_default()
            .trim()
            .is_empty();

        if has_diff || has_untracked {
            println!("{DIM}  no turn history available, but there are uncommitted changes.{RESET}");
            println!("{DIM}  use /undo --all to revert everything (nuclear option){RESET}\n");
        } else {
            println!("{DIM}  (nothing to undo — no turn history){RESET}\n");
        }
        return None;
    }

    let available = history.len();
    let actual = count.min(available);
    let word = crate::format::pluralize(actual, "turn", "turns");

    // Show what will be undone
    println!("{DIM}  undoing last {actual} {word}...{RESET}");

    let actions = history.undo_last(actual);
    for action in &actions {
        println!("{DIM}    {action}{RESET}");
    }

    if actions.is_empty() {
        println!("{DIM}  (no files were modified in those turns){RESET}\n");
    } else {
        let file_word = crate::format::pluralize(actions.len(), "file", "files");
        println!(
            "{GREEN}  ✓ undid {actual} {word} ({} {file_word} affected){RESET}\n",
            actions.len()
        );
    }

    if count > available {
        println!(
            "{DIM}  (only {available} {} available, undid all){RESET}\n",
            crate::format::pluralize(available, "turn was", "turns were")
        );
    }

    // Return context for agent injection if any files were actually affected
    if !actions.is_empty() {
        Some(build_undo_context(&actions))
    } else {
        None
    }
}

/// Undo the most recent git commit using `git revert`.
///
/// Returns `Some(context)` with causality information so the agent knows
/// that earlier conversation may reference code that no longer exists.
fn handle_undo_last_commit() -> Option<String> {
    // 1. Get the last commit info
    let log = run_git(&["log", "--oneline", "-1"]).unwrap_or_default();
    if log.trim().is_empty() {
        println!("{DIM}  (no commits to undo){RESET}\n");
        return None;
    }

    // 2. Get the files changed in that commit
    let files = run_git(&["diff", "--name-only", "HEAD~1", "HEAD"]).unwrap_or_default();

    // 3. Show what will be undone
    println!("{DIM}  Reverting last commit: {}{RESET}", log.trim());

    // 4. Revert using git revert (keeps history, safer than reset)
    let result = run_git(&["revert", "HEAD", "--no-edit"]);
    match result {
        Ok(output) => {
            println!("{GREEN}  ✓ Reverted last commit{RESET}");
            if !output.trim().is_empty() {
                println!("{DIM}  {}{RESET}", output.trim());
            }
            println!();

            // Build context for agent
            let mut actions = Vec::new();
            for f in files.lines().filter(|l| !l.is_empty()) {
                actions.push(format!("reverted changes to {f} (commit undone)"));
            }

            // Enhanced context note that mentions journal/conversation inconsistency
            let mut note =
                String::from("[System note: /undo --last-commit reverted a git commit.\n");
            note.push_str(&format!("Reverted commit: {}\n", log.trim()));
            note.push_str("Files affected:\n");
            for action in &actions {
                note.push_str(&format!("- {action}\n"));
            }
            note.push_str(
                "⚠️ Earlier messages in this conversation may reference code from this commit \
                 that no longer exists. Verify current file state before continuing.\n",
            );
            note.push_str(
                "Any journal entries about this commit describe work that has been undone.]",
            );

            Some(note)
        }
        Err(e) => {
            eprintln!("{RED}  ✗ Revert failed: {e}{RESET}");
            eprintln!("{DIM}  (the commit may have conflicts — try manual git revert){RESET}\n");
            None
        }
    }
}

/// Nuclear undo: revert ALL uncommitted changes (old behavior).
/// Clears turn history as well.
///
/// Returns `Some(context)` when changes were actually reverted.
fn handle_undo_all(history: &mut crate::prompt::TurnHistory) -> Option<String> {
    let diff_stat = run_git(&["diff", "--stat"]).unwrap_or_default();
    let untracked_text =
        run_git(&["ls-files", "--others", "--exclude-standard"]).unwrap_or_default();

    let has_diff = !diff_stat.is_empty();
    let untracked_files: Vec<String> = untracked_text
        .lines()
        .filter(|l| !l.is_empty())
        .map(|l| l.to_string())
        .collect();
    let has_untracked = !untracked_files.is_empty();

    if !has_diff && !has_untracked {
        println!("{DIM}  (nothing to undo — no uncommitted changes){RESET}\n");
        history.clear();
        return None;
    }

    // Collect action descriptions for the context note
    let mut actions = Vec::new();

    if has_diff {
        println!("{DIM}{diff_stat}{RESET}");
        // Parse which files were modified from the diff stat
        let stat = parse_diff_stat(&diff_stat);
        for entry in &stat.entries {
            actions.push(format!("restored {} (to last committed state)", entry.file));
        }
    }
    if has_untracked {
        println!("{DIM}  untracked files:");
        for f in &untracked_files {
            println!("    {f}");
            actions.push(format!("deleted {f} (was untracked)"));
        }
        println!("{RESET}");
    }

    if has_diff {
        let _ = run_git(&["checkout", "--", "."]);
    }
    if has_untracked {
        let _ = run_git(&["clean", "-fd"]);
    }
    println!("{GREEN}  ✓ reverted all uncommitted changes{RESET}\n");

    // Clear turn history since everything is now reverted
    history.clear();

    if !actions.is_empty() {
        Some(build_undo_context(&actions))
    } else {
        None
    }
}

// ── /commit ──────────────────────────────────────────────────────────────

pub fn handle_commit(input: &str) {
    let arg = input.strip_prefix("/commit").unwrap_or("").trim();
    if !arg.is_empty() {
        let (ok, output) = run_git_commit_with_trailer(arg);
        if ok {
            println!("{GREEN}{}{RESET}\n", output.trim());
        } else {
            eprintln!("{RED}{}{RESET}\n", output.trim());
        }
    } else {
        match get_staged_diff() {
            None => {
                eprintln!("{RED}  error: not in a git repository{RESET}\n");
            }
            Some(diff) if diff.trim().is_empty() => {
                println!("{DIM}  nothing staged — use `git add` first{RESET}\n");
            }
            Some(diff) => {
                let suggested = generate_commit_message(&diff);
                println!("{DIM}  Suggested commit message:{RESET}");
                println!("    {BOLD}{suggested}{RESET}");
                eprint!(
                    "\n  {DIM}({GREEN}y{RESET}{DIM})es / ({RED}n{RESET}{DIM})o / ({CYAN}e{RESET}{DIM})dit: {RESET}"
                );
                io::stderr().flush().ok();
                let mut response = String::new();
                if io::stdin().read_line(&mut response).is_ok() {
                    let response = response.trim().to_lowercase();
                    match response.as_str() {
                        "y" | "yes" | "" => {
                            let (ok, output) = run_git_commit_with_trailer(&suggested);
                            if ok {
                                println!("{GREEN}{}{RESET}\n", output.trim());
                            } else {
                                eprintln!("{RED}{}{RESET}\n", output.trim());
                            }
                        }
                        "e" | "edit" => {
                            println!("{DIM}  Enter your commit message:{RESET}");
                            eprint!("  > ");
                            io::stderr().flush().ok();
                            let mut custom_msg = String::new();
                            if io::stdin().read_line(&mut custom_msg).is_ok() {
                                let custom_msg = custom_msg.trim();
                                if custom_msg.is_empty() {
                                    println!("{DIM}  (commit cancelled — empty message){RESET}\n");
                                } else {
                                    let (ok, output) = run_git_commit_with_trailer(custom_msg);
                                    if ok {
                                        println!("{GREEN}{}{RESET}\n", output.trim());
                                    } else {
                                        eprintln!("{RED}{}{RESET}\n", output.trim());
                                    }
                                }
                            }
                        }
                        _ => {
                            println!("{DIM}  (commit cancelled){RESET}\n");
                        }
                    }
                }
            }
        }
    }
}

// ── /pr ──────────────────────────────────────────────────────────────────

/// Represents a parsed `/pr` subcommand.
#[derive(Debug, PartialEq)]
pub enum PrSubcommand {
    List,
    View(u32),
    Diff(u32),
    Comment(u32, String),
    Checkout(u32),
    Create { draft: bool },
    Help,
}

/// Parse the argument string after `/pr` into a `PrSubcommand`.
pub fn parse_pr_args(arg: &str) -> PrSubcommand {
    let arg = arg.trim();
    if arg.is_empty() {
        return PrSubcommand::List;
    }

    let parts: Vec<&str> = arg.splitn(3, char::is_whitespace).collect();

    // Check for "create" subcommand first (before trying to parse as number)
    if parts[0].eq_ignore_ascii_case("create") {
        let draft = parts
            .get(1)
            .map(|s| s.trim_start_matches('-').eq_ignore_ascii_case("draft"))
            .unwrap_or(false);
        return PrSubcommand::Create { draft };
    }

    let number = match parts[0].parse::<u32>() {
        Ok(n) => n,
        Err(_) => return PrSubcommand::Help,
    };

    if parts.len() == 1 {
        return PrSubcommand::View(number);
    }

    match parts[1].to_lowercase().as_str() {
        "diff" => PrSubcommand::Diff(number),
        "checkout" => PrSubcommand::Checkout(number),
        "comment" => {
            let text = if parts.len() == 3 {
                parts[2].trim().to_string()
            } else {
                String::new()
            };
            if text.is_empty() {
                PrSubcommand::Help
            } else {
                PrSubcommand::Comment(number, text)
            }
        }
        _ => PrSubcommand::Help,
    }
}

pub async fn handle_pr(input: &str, agent: &mut Agent, session_total: &mut Usage, model: &str) {
    let arg = input.strip_prefix("/pr").unwrap_or("").trim();
    match parse_pr_args(arg) {
        PrSubcommand::List => {
            match std::process::Command::new("gh")
                .args(["pr", "list", "--limit", "10"])
                .output()
            {
                Ok(output) if output.status.success() => {
                    let text = String::from_utf8_lossy(&output.stdout);
                    if text.trim().is_empty() {
                        println!("{DIM}  (no open pull requests){RESET}\n");
                    } else {
                        println!("{DIM}  Open pull requests:");
                        for line in text.lines() {
                            println!("    {line}");
                        }
                        println!("{RESET}");
                    }
                }
                Ok(output) => {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("{RED}  error: {}{RESET}\n", stderr.trim());
                }
                Err(_) => {
                    eprintln!("{RED}  error: `gh` CLI not found. Install it from https://cli.github.com{RESET}\n");
                }
            }
        }
        PrSubcommand::View(number) => {
            let num_str = number.to_string();
            match std::process::Command::new("gh")
                .args(["pr", "view", &num_str])
                .output()
            {
                Ok(output) if output.status.success() => {
                    let text = String::from_utf8_lossy(&output.stdout);
                    println!("{DIM}{text}{RESET}");
                }
                Ok(output) => {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("{RED}  error: {}{RESET}\n", stderr.trim());
                }
                Err(_) => {
                    eprintln!("{RED}  error: `gh` CLI not found. Install it from https://cli.github.com{RESET}\n");
                }
            }
        }
        PrSubcommand::Diff(number) => {
            let num_str = number.to_string();
            match std::process::Command::new("gh")
                .args(["pr", "diff", &num_str])
                .output()
            {
                Ok(output) if output.status.success() => {
                    let text = String::from_utf8_lossy(&output.stdout);
                    if text.trim().is_empty() {
                        println!("{DIM}  (no diff for PR #{number}){RESET}\n");
                    } else {
                        println!("{DIM}{text}{RESET}");
                    }
                }
                Ok(output) => {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("{RED}  error: {}{RESET}\n", stderr.trim());
                }
                Err(_) => {
                    eprintln!("{RED}  error: `gh` CLI not found. Install it from https://cli.github.com{RESET}\n");
                }
            }
        }
        PrSubcommand::Comment(number, text) => {
            let num_str = number.to_string();
            match std::process::Command::new("gh")
                .args(["pr", "comment", &num_str, "--body", &text])
                .output()
            {
                Ok(output) if output.status.success() => {
                    println!("{GREEN}  ✓ comment added to PR #{number}{RESET}\n");
                }
                Ok(output) => {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("{RED}  error: {}{RESET}\n", stderr.trim());
                }
                Err(_) => {
                    eprintln!("{RED}  error: `gh` CLI not found. Install it from https://cli.github.com{RESET}\n");
                }
            }
        }
        PrSubcommand::Checkout(number) => {
            let num_str = number.to_string();
            match std::process::Command::new("gh")
                .args(["pr", "checkout", &num_str])
                .output()
            {
                Ok(output) if output.status.success() => {
                    println!("{GREEN}  ✓ checked out PR #{number}{RESET}\n");
                }
                Ok(output) => {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("{RED}  error: {}{RESET}\n", stderr.trim());
                }
                Err(_) => {
                    eprintln!("{RED}  error: `gh` CLI not found. Install it from https://cli.github.com{RESET}\n");
                }
            }
        }
        PrSubcommand::Create { draft } => {
            // 1. Detect current branch
            let branch = match git_branch() {
                Some(b) => b,
                None => {
                    eprintln!("{RED}  error: not in a git repository{RESET}\n");
                    return;
                }
            };
            let base = detect_base_branch();

            if branch == base {
                eprintln!(
                    "{RED}  error: already on {base} — switch to a feature branch first{RESET}\n"
                );
                return;
            }

            // 2. Get diff and commits
            let diff = get_branch_diff(&base).unwrap_or_default();
            let commits = get_branch_commits(&base).unwrap_or_default();

            if diff.trim().is_empty() && commits.trim().is_empty() {
                println!(
                    "{DIM}  (no changes between {branch} and {base} — nothing to create a PR for){RESET}\n"
                );
                return;
            }

            // 3. Show what we found
            let commit_count = commits.lines().filter(|l| !l.is_empty()).count();
            println!(
                "{DIM}  Branch: {branch}{base} ({commit_count} commit{s}){RESET}",
                s = if commit_count == 1 { "" } else { "s" }
            );
            println!("{DIM}  Generating PR description with AI...{RESET}");

            // 4. Ask AI to generate title + description
            let prompt = build_pr_description_prompt(&branch, &base, &commits, &diff);
            let response = run_prompt(agent, &prompt, session_total, model).await.text;

            // 5. Parse the AI's response
            let (title, body) = match parse_pr_description(&response) {
                Some(parsed) => parsed,
                None => {
                    eprintln!(
                        "{RED}  error: could not parse AI response into PR title/description{RESET}"
                    );
                    eprintln!("{DIM}  (try again or create manually with `gh pr create`){RESET}\n");
                    return;
                }
            };

            println!("{DIM}  Title: {BOLD}{title}{RESET}");
            println!("{DIM}  Draft: {}{RESET}", if draft { "yes" } else { "no" });

            // 6. Create the PR via gh CLI
            let mut gh_args = vec![
                "pr".to_string(),
                "create".to_string(),
                "--title".to_string(),
                title.clone(),
                "--body".to_string(),
                body,
                "--base".to_string(),
                base.clone(),
            ];
            if draft {
                gh_args.push("--draft".to_string());
            }

            let gh_str_args: Vec<&str> = gh_args.iter().map(|s| s.as_str()).collect();
            match std::process::Command::new("gh").args(&gh_str_args).output() {
                Ok(output) if output.status.success() => {
                    let url = String::from_utf8_lossy(&output.stdout);
                    let url = url.trim();
                    if url.is_empty() {
                        println!("{GREEN}  ✓ PR created: {title}{RESET}\n");
                    } else {
                        println!("{GREEN}  ✓ PR created: {url}{RESET}\n");
                    }
                }
                Ok(output) => {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("{RED}  error: {}{RESET}\n", stderr.trim());
                }
                Err(_) => {
                    eprintln!("{RED}  error: `gh` CLI not found. Install it from https://cli.github.com{RESET}\n");
                }
            }
        }
        PrSubcommand::Help => {
            println!("{DIM}  usage: /pr                         List open pull requests");
            println!(
                "         /pr create [--draft]        Create PR with AI-generated description"
            );
            println!("         /pr <number>                View details of a specific PR");
            println!("         /pr <number> diff           Show the diff of a PR");
            println!("         /pr <number> comment <text> Add a comment to a PR");
            println!("         /pr <number> checkout       Checkout a PR locally{RESET}\n");
        }
    }
}

// ── /git ─────────────────────────────────────────────────────────────────

pub fn handle_git(input: &str) {
    let arg = input.strip_prefix("/git").unwrap_or("").trim();
    let subcmd = parse_git_args(arg);
    run_git_subcommand(&subcmd);
}

// ── /review ──────────────────────────────────────────────────────────────

/// Build a review prompt for either staged changes or a specific file.
/// Returns None if there's nothing to review, Some(prompt) otherwise.
pub fn build_review_content(arg: &str) -> Option<(String, String)> {
    let arg = arg.trim();
    if arg.is_empty() {
        // Review staged changes
        match get_staged_diff() {
            None => {
                eprintln!("{RED}  error: not in a git repository{RESET}\n");
                None
            }
            Some(diff) if diff.trim().is_empty() => {
                // Fall back to unstaged diff if nothing staged
                let unstaged = run_git(&["diff"]).unwrap_or_default();
                if unstaged.trim().is_empty() {
                    println!("{DIM}  nothing to review — no staged or unstaged changes{RESET}\n");
                    None
                } else {
                    println!("{DIM}  reviewing unstaged changes...{RESET}");
                    Some(("unstaged changes".to_string(), unstaged))
                }
            }
            Some(diff) => {
                println!("{DIM}  reviewing staged changes...{RESET}");
                Some(("staged changes".to_string(), diff))
            }
        }
    } else {
        // Review a specific file
        let path = std::path::Path::new(arg);
        if !path.exists() {
            eprintln!("{RED}  error: file not found: {arg}{RESET}\n");
            return None;
        }
        match std::fs::read_to_string(path) {
            Ok(content) => {
                if content.trim().is_empty() {
                    println!("{DIM}  file is empty — nothing to review{RESET}\n");
                    None
                } else {
                    println!("{DIM}  reviewing {arg}...{RESET}");
                    Some((arg.to_string(), content))
                }
            }
            Err(e) => {
                eprintln!("{RED}  error reading {arg}: {e}{RESET}\n");
                None
            }
        }
    }
}

/// Build the review prompt to send to the AI.
pub fn build_review_prompt(label: &str, content: &str) -> String {
    // Truncate if very large
    let max_chars = 30_000;
    let content_preview = if content.len() > max_chars {
        let truncated = safe_truncate(content, max_chars);
        format!(
            "{truncated}\n\n... (truncated, {} more chars)",
            content.len() - max_chars
        )
    } else {
        content.to_string()
    };

    format!(
        r#"Review the following code ({label}). Look for:

1. **Bugs** — logic errors, off-by-one errors, null/None handling, race conditions
2. **Security** — injection vulnerabilities, unsafe operations, credential exposure
3. **Style** — naming, idiomatic patterns, unnecessary complexity, dead code
4. **Performance** — obvious inefficiencies, unnecessary allocations, N+1 patterns
5. **Suggestions** — improvements, missing error handling, better approaches

Be specific: reference line numbers or code snippets. Be concise — skip things that look fine.
If the code looks good overall, say so briefly and note any minor suggestions.

```
{content_preview}
```"#
    )
}

/// Handle the /review command: review staged changes or a specific file.
/// Returns the review prompt if sent to AI, None otherwise.
pub async fn handle_review(
    input: &str,
    agent: &mut Agent,
    session_total: &mut Usage,
    model: &str,
) -> Option<String> {
    let arg = input.strip_prefix("/review").unwrap_or("").trim();

    match build_review_content(arg) {
        Some((label, content)) => {
            let prompt = build_review_prompt(&label, &content);
            run_prompt(agent, &prompt, session_total, model).await;
            auto_compact_if_needed(agent);
            Some(prompt)
        }
        None => None,
    }
}

// ── /blame ───────────────────────────────────────────────────────────────

/// Parsed arguments for `/blame`.
#[derive(Debug, PartialEq)]
pub struct BlameArgs {
    pub file: String,
    pub range: Option<(usize, usize)>,
}

/// Parse `/blame <file>` or `/blame <file>:<start>-<end>`.
pub fn parse_blame_args(input: &str) -> Result<BlameArgs, String> {
    let arg = input.strip_prefix("/blame").unwrap_or(input).trim();

    if arg.is_empty() {
        return Err("Usage: /blame <file> or /blame <file>:<start>-<end>".to_string());
    }

    // Check for <file>:<start>-<end> pattern
    if let Some(colon_pos) = arg.rfind(':') {
        let file_part = &arg[..colon_pos];
        let range_part = &arg[colon_pos + 1..];

        if let Some(dash_pos) = range_part.find('-') {
            let start_str = &range_part[..dash_pos];
            let end_str = &range_part[dash_pos + 1..];

            if let (Ok(start), Ok(end)) = (start_str.parse::<usize>(), end_str.parse::<usize>()) {
                if start == 0 || end == 0 {
                    return Err("Line numbers must be >= 1".to_string());
                }
                if start > end {
                    return Err(format!("Invalid range: start ({start}) > end ({end})"));
                }
                if !file_part.is_empty() {
                    return Ok(BlameArgs {
                        file: file_part.to_string(),
                        range: Some((start, end)),
                    });
                }
            }
        }
    }

    // No valid range found — treat entire input as file path
    Ok(BlameArgs {
        file: arg.to_string(),
        range: None,
    })
}

/// Colorize a single line of `git blame` output.
///
/// Typical git blame line format:
/// `abc1234f (Author Name  2024-01-15 10:30:00 +0000  42) line content`
///
/// We colorize:
/// - Commit hash → DIM
/// - Author name → CYAN
/// - Date/time → DIM
/// - Line number → YELLOW
/// - Code content → default
pub fn colorize_blame_line(line: &str) -> String {
    // git blame output: <hash> (<author> <date> <time> <tz> <lineno>) <code>
    // Find the opening paren that starts the author section
    let Some(paren_open) = line.find('(') else {
        return line.to_string();
    };
    let Some(paren_close) = line.find(')') else {
        return line.to_string();
    };
    if paren_close <= paren_open {
        return line.to_string();
    }

    let hash = &line[..paren_open];
    let annotation = &line[paren_open + 1..paren_close];
    let code = if paren_close + 1 < line.len() {
        &line[paren_close + 1..]
    } else {
        ""
    };

    // Inside the annotation: "Author Name  2024-01-15 10:30:00 +0000  42"
    // Try to find the date pattern (YYYY-MM-DD) to split author from date+lineno
    let mut author = annotation;
    let mut date_and_lineno = "";

    // Look for a date pattern: 4-digit year followed by -
    for (i, _) in annotation.char_indices() {
        if i + 10 <= annotation.len() {
            let slice = &annotation[i..];
            if slice.len() >= 10
                && slice.as_bytes()[4] == b'-'
                && slice.as_bytes()[7] == b'-'
                && slice[..4].chars().all(|c| c.is_ascii_digit())
                && slice[5..7].chars().all(|c| c.is_ascii_digit())
                && slice[8..10].chars().all(|c| c.is_ascii_digit())
            {
                author = annotation[..i].trim_end();
                date_and_lineno = &annotation[i..];
                break;
            }
        }
    }

    // Try to split the lineno from date portion
    // The lineno is typically the last whitespace-separated token
    let (date_part, lineno_part) =
        if let Some(last_space) = date_and_lineno.rfind(char::is_whitespace) {
            let candidate = date_and_lineno[last_space..].trim();
            if candidate.chars().all(|c| c.is_ascii_digit()) && !candidate.is_empty() {
                (&date_and_lineno[..last_space], candidate)
            } else {
                (date_and_lineno, "")
            }
        } else {
            (date_and_lineno, "")
        };

    format!(
        "{DIM}{hash}{RESET}({CYAN}{author}{RESET} {DIM}{date_part}{RESET} {YELLOW}{lineno_part}{RESET}){code}"
    )
}

/// Colorize full `git blame` output (multiple lines).
pub fn colorize_blame(output: &str) -> String {
    output
        .lines()
        .map(colorize_blame_line)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Handle the `/blame` command.
pub fn handle_blame(input: &str) {
    let args = match parse_blame_args(input) {
        Ok(a) => a,
        Err(e) => {
            println!("  {RED}{RESET} {e}");
            return;
        }
    };

    let mut cmd = vec!["blame".to_string()];
    if let Some((start, end)) = args.range {
        cmd.push(format!("-L{start},{end}"));
    }
    cmd.push(args.file.clone());

    let cmd_refs: Vec<&str> = cmd.iter().map(|s| s.as_str()).collect();
    match run_git(&cmd_refs) {
        Ok(output) => {
            if output.trim().is_empty() {
                println!("  {DIM}(no blame output){RESET}");
            } else {
                println!();
                println!("{}", colorize_blame(&output));
            }
        }
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("no such path") || msg.contains("No such file") {
                println!("  {RED}{RESET} File not found: {DIM}{}{RESET}", args.file);
            } else if msg.contains("not a git repository") || msg.contains("fatal: not a git") {
                println!("  {RED}{RESET} Not in a git repository");
            } else {
                println!("  {RED}{RESET} {msg}");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::{is_unknown_command, KNOWN_COMMANDS};

    // ── parse_diff_stat tests ───────────────────────────────────────────

    #[test]
    fn parse_diff_stat_single_file() {
        let input =
            " src/main.rs | 10 +++++++---\n 1 file changed, 7 insertions(+), 3 deletions(-)\n";
        let summary = parse_diff_stat(input);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "src/main.rs");
        assert_eq!(summary.entries[0].insertions, 7);
        assert_eq!(summary.entries[0].deletions, 3);
        assert_eq!(summary.total_insertions, 7);
        assert_eq!(summary.total_deletions, 3);
    }

    #[test]
    fn parse_diff_stat_multiple_files() {
        let input = "\
 src/commands.rs | 42 +++++++++++++++++++++---------------------
 src/main.rs     |  5 ++---
 src/cli.rs      | 12 ++++++++++++
 3 files changed, 25 insertions(+), 10 deletions(-)
";
        let summary = parse_diff_stat(input);
        assert_eq!(summary.entries.len(), 3);

        assert_eq!(summary.entries[0].file, "src/commands.rs");
        assert_eq!(summary.entries[1].file, "src/main.rs");
        assert_eq!(summary.entries[2].file, "src/cli.rs");

        // The visual bar has + and - characters, so counts come from those
        assert!(summary.entries[0].insertions > 0);
        assert!(summary.entries[0].deletions > 0);
        assert!(
            summary.entries[2].deletions == 0,
            "cli.rs is insertions only"
        );

        // Summary line totals
        assert_eq!(summary.total_insertions, 25);
        assert_eq!(summary.total_deletions, 10);
    }

    #[test]
    fn parse_diff_stat_insertions_only() {
        let input = " new_file.rs | 20 ++++++++++++++++++++\n 1 file changed, 20 insertions(+)\n";
        let summary = parse_diff_stat(input);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "new_file.rs");
        assert_eq!(summary.entries[0].insertions, 20);
        assert_eq!(summary.entries[0].deletions, 0);
        assert_eq!(summary.total_insertions, 20);
        assert_eq!(summary.total_deletions, 0);
    }

    #[test]
    fn parse_diff_stat_deletions_only() {
        let input = " old_file.rs | 8 --------\n 1 file changed, 8 deletions(-)\n";
        let summary = parse_diff_stat(input);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "old_file.rs");
        assert_eq!(summary.entries[0].insertions, 0);
        assert_eq!(summary.entries[0].deletions, 8);
        assert_eq!(summary.total_insertions, 0);
        assert_eq!(summary.total_deletions, 8);
    }

    #[test]
    fn parse_diff_stat_empty_input() {
        let summary = parse_diff_stat("");
        assert_eq!(summary.entries.len(), 0);
        assert_eq!(summary.total_insertions, 0);
        assert_eq!(summary.total_deletions, 0);
    }

    #[test]
    fn parse_diff_stat_whitespace_only() {
        let summary = parse_diff_stat("   \n  \n\n");
        assert_eq!(summary.entries.len(), 0);
        assert_eq!(summary.total_insertions, 0);
        assert_eq!(summary.total_deletions, 0);
    }

    #[test]
    fn parse_diff_stat_no_summary_line() {
        // Sometimes git output might not include the summary line
        let input = " src/lib.rs | 3 +++\n";
        let summary = parse_diff_stat(input);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].insertions, 3);
        assert_eq!(summary.entries[0].deletions, 0);
        // Without a summary line, totals are computed from entries
        assert_eq!(summary.total_insertions, 3);
        assert_eq!(summary.total_deletions, 0);
    }

    #[test]
    fn parse_diff_stat_binary_file() {
        let input = " assets/logo.png | Bin 0 -> 1234 bytes\n 1 file changed, 0 insertions(+), 0 deletions(-)\n";
        let summary = parse_diff_stat(input);
        // Binary file lines still have a pipe, so they're parsed as entries
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "assets/logo.png");
        // "Bin 0 -> 1234 bytes" — the parser counts literal + and - chars
        // The "->" contains one '-', so deletions=1
        assert_eq!(summary.entries[0].insertions, 0);
        assert_eq!(summary.entries[0].deletions, 1);
        // Summary line says 0/0, but the fallback path recomputes from entries
        // when both summary totals are zero, so total_deletions picks up the entry's 1
        assert_eq!(summary.total_insertions, 0);
        assert_eq!(summary.total_deletions, 1);
    }

    // ── format_diff_stat tests ──────────────────────────────────────────

    #[test]
    fn format_diff_stat_empty_entries() {
        let summary = DiffStatSummary {
            entries: vec![],
            total_insertions: 0,
            total_deletions: 0,
        };
        let output = format_diff_stat(&summary);
        assert!(
            output.is_empty(),
            "Empty entries should produce empty output"
        );
    }

    #[test]
    fn format_diff_stat_single_entry_insertions_only() {
        let summary = DiffStatSummary {
            entries: vec![DiffStatEntry {
                file: "src/main.rs".to_string(),
                insertions: 10,
                deletions: 0,
            }],
            total_insertions: 10,
            total_deletions: 0,
        };
        let output = format_diff_stat(&summary);
        assert!(output.contains("src/main.rs"), "Should contain filename");
        assert!(output.contains("+10"), "Should show insertions count");
        assert!(!output.contains("-0"), "Should not show zero deletions");
        assert!(output.contains("1 file changed"), "Should show summary");
        assert!(output.contains("+10"), "Summary should show insertions");
    }

    #[test]
    fn format_diff_stat_single_entry_deletions_only() {
        let summary = DiffStatSummary {
            entries: vec![DiffStatEntry {
                file: "old.rs".to_string(),
                insertions: 0,
                deletions: 5,
            }],
            total_insertions: 0,
            total_deletions: 5,
        };
        let output = format_diff_stat(&summary);
        assert!(output.contains("old.rs"), "Should contain filename");
        assert!(output.contains("-5"), "Should show deletions count");
        assert!(!output.contains("+0"), "Should not show zero insertions");
    }

    #[test]
    fn format_diff_stat_mixed_changes() {
        let summary = DiffStatSummary {
            entries: vec![
                DiffStatEntry {
                    file: "src/a.rs".to_string(),
                    insertions: 20,
                    deletions: 5,
                },
                DiffStatEntry {
                    file: "src/b.rs".to_string(),
                    insertions: 3,
                    deletions: 0,
                },
            ],
            total_insertions: 23,
            total_deletions: 5,
        };
        let output = format_diff_stat(&summary);
        assert!(output.contains("src/a.rs"), "Should contain first file");
        assert!(output.contains("src/b.rs"), "Should contain second file");
        assert!(
            output.contains("2 files changed"),
            "Should pluralize 'files'"
        );
        assert!(
            output.contains("+23"),
            "Summary should show total insertions"
        );
        assert!(output.contains("-5"), "Summary should show total deletions");
    }

    #[test]
    fn format_diff_stat_singular_file() {
        let summary = DiffStatSummary {
            entries: vec![DiffStatEntry {
                file: "f.rs".to_string(),
                insertions: 1,
                deletions: 1,
            }],
            total_insertions: 1,
            total_deletions: 1,
        };
        let output = format_diff_stat(&summary);
        assert!(
            output.contains("1 file changed"),
            "Should use singular 'file' not 'files'"
        );
    }

    // ── parse_pr_args tests ─────────────────────────────────────────────

    #[test]
    fn parse_pr_args_empty_is_list() {
        assert_eq!(parse_pr_args(""), PrSubcommand::List);
        assert_eq!(parse_pr_args("  "), PrSubcommand::List);
    }

    #[test]
    fn parse_pr_args_number_is_view() {
        assert_eq!(parse_pr_args("42"), PrSubcommand::View(42));
        assert_eq!(parse_pr_args("1"), PrSubcommand::View(1));
        assert_eq!(parse_pr_args("  99  "), PrSubcommand::View(99));
    }

    #[test]
    fn parse_pr_args_number_diff() {
        assert_eq!(parse_pr_args("42 diff"), PrSubcommand::Diff(42));
    }

    #[test]
    fn parse_pr_args_number_checkout() {
        assert_eq!(parse_pr_args("7 checkout"), PrSubcommand::Checkout(7));
    }

    #[test]
    fn parse_pr_args_number_comment() {
        assert_eq!(
            parse_pr_args("5 comment looks good!"),
            PrSubcommand::Comment(5, "looks good!".to_string())
        );
    }

    #[test]
    fn parse_pr_args_comment_without_text_is_help() {
        assert_eq!(parse_pr_args("5 comment"), PrSubcommand::Help);
    }

    #[test]
    fn parse_pr_args_create() {
        assert_eq!(
            parse_pr_args("create"),
            PrSubcommand::Create { draft: false }
        );
    }

    #[test]
    fn parse_pr_args_create_draft() {
        assert_eq!(
            parse_pr_args("create --draft"),
            PrSubcommand::Create { draft: true }
        );
    }

    #[test]
    fn parse_pr_args_create_case_insensitive() {
        assert_eq!(
            parse_pr_args("CREATE"),
            PrSubcommand::Create { draft: false }
        );
        // --Draft with capital D: trim_start_matches('-') → "Draft", eq_ignore_ascii_case("draft") → true
        assert_eq!(
            parse_pr_args("Create --Draft"),
            PrSubcommand::Create { draft: true }
        );
        assert_eq!(
            parse_pr_args("create -draft"),
            PrSubcommand::Create { draft: true }
        );
    }

    #[test]
    fn parse_pr_args_invalid_is_help() {
        assert_eq!(parse_pr_args("foobar"), PrSubcommand::Help);
        assert_eq!(parse_pr_args("abc 123"), PrSubcommand::Help);
    }

    #[test]
    fn parse_pr_args_unknown_subcommand_is_help() {
        assert_eq!(parse_pr_args("42 merge"), PrSubcommand::Help);
        assert_eq!(parse_pr_args("42 close"), PrSubcommand::Help);
    }

    // ── build_review_prompt tests ───────────────────────────────────────

    #[test]
    fn build_review_prompt_contains_label() {
        let prompt = build_review_prompt("staged changes", "fn main() {}");
        assert!(
            prompt.contains("staged changes"),
            "Prompt should include the label"
        );
    }

    #[test]
    fn build_review_prompt_contains_content() {
        let code = "fn add(a: i32, b: i32) -> i32 { a + b }";
        let prompt = build_review_prompt("test.rs", code);
        assert!(prompt.contains(code), "Prompt should include the code");
    }

    #[test]
    fn build_review_prompt_contains_review_criteria() {
        let prompt = build_review_prompt("file.rs", "let x = 1;");
        assert!(prompt.contains("Bugs"), "Should mention bugs");
        assert!(prompt.contains("Security"), "Should mention security");
        assert!(prompt.contains("Style"), "Should mention style");
        assert!(prompt.contains("Performance"), "Should mention performance");
        assert!(prompt.contains("Suggestions"), "Should mention suggestions");
    }

    #[test]
    fn build_review_prompt_truncates_large_content() {
        let large_content = "x".repeat(50_000);
        let prompt = build_review_prompt("big.rs", &large_content);
        assert!(
            prompt.contains("truncated"),
            "Large content should be truncated"
        );
        assert!(
            prompt.contains("20000 more chars"),
            "Should show remaining char count"
        );
        // The prompt should be shorter than the original content
        assert!(
            prompt.len() < large_content.len(),
            "Prompt should be shorter than 50k"
        );
    }

    #[test]
    fn build_review_prompt_does_not_truncate_small_content() {
        let small_content = "fn hello() { println!(\"hi\"); }";
        let prompt = build_review_prompt("small.rs", small_content);
        assert!(
            !prompt.contains("truncated"),
            "Small content should not be truncated"
        );
        assert!(
            prompt.contains(small_content),
            "Full content should be present"
        );
    }

    #[test]
    fn build_review_prompt_wraps_in_code_block() {
        let prompt = build_review_prompt("test.rs", "let x = 42;");
        assert!(prompt.contains("```"), "Content should be in a code block");
    }

    // ── DiffStatEntry / DiffStatSummary equality ────────────────────────

    #[test]
    fn diff_stat_entry_equality() {
        let a = DiffStatEntry {
            file: "a.rs".to_string(),
            insertions: 5,
            deletions: 3,
        };
        let b = DiffStatEntry {
            file: "a.rs".to_string(),
            insertions: 5,
            deletions: 3,
        };
        assert_eq!(a, b);
    }

    #[test]
    fn diff_stat_summary_round_trip() {
        // Parse real git output, format it, verify structure
        let input = "\
 src/main.rs | 15 +++++++++------
 Cargo.toml  |  2 +-
 2 files changed, 10 insertions(+), 5 deletions(-)
";
        let summary = parse_diff_stat(input);
        let formatted = format_diff_stat(&summary);

        // Formatted output should contain both filenames
        assert!(formatted.contains("src/main.rs"));
        assert!(formatted.contains("Cargo.toml"));
        // Should contain "2 files changed"
        assert!(formatted.contains("2 files changed"));
    }

    // ── parse_diff_args tests ────────────────────────────────────────────

    #[test]
    fn test_parse_diff_args_empty() {
        let opts = parse_diff_args("/diff");
        assert!(!opts.staged_only);
        assert!(!opts.name_only);
        assert_eq!(opts.file, None);
    }

    #[test]
    fn test_parse_diff_args_staged() {
        let opts = parse_diff_args("/diff --staged");
        assert!(opts.staged_only);
        assert!(!opts.name_only);
        assert_eq!(opts.file, None);
    }

    #[test]
    fn test_parse_diff_args_cached() {
        let opts = parse_diff_args("/diff --cached");
        assert!(opts.staged_only, "--cached should be an alias for --staged");
        assert!(!opts.name_only);
        assert_eq!(opts.file, None);
    }

    #[test]
    fn test_parse_diff_args_name_only() {
        let opts = parse_diff_args("/diff --name-only");
        assert!(!opts.staged_only);
        assert!(opts.name_only);
        assert_eq!(opts.file, None);
    }

    #[test]
    fn test_parse_diff_args_file() {
        let opts = parse_diff_args("/diff src/main.rs");
        assert!(!opts.staged_only);
        assert!(!opts.name_only);
        assert_eq!(opts.file, Some("src/main.rs".to_string()));
    }

    #[test]
    fn test_parse_diff_args_staged_and_file() {
        let opts = parse_diff_args("/diff --staged src/main.rs");
        assert!(opts.staged_only);
        assert!(!opts.name_only);
        assert_eq!(opts.file, Some("src/main.rs".to_string()));
    }

    #[test]
    fn test_parse_diff_args_all_flags() {
        let opts = parse_diff_args("/diff --staged --name-only src/main.rs");
        assert!(opts.staged_only);
        assert!(opts.name_only);
        assert_eq!(opts.file, Some("src/main.rs".to_string()));
    }

    // ── PR tests (moved from commands.rs) ───────────────────────────────

    #[test]
    fn test_pr_command_recognized() {
        assert!(!is_unknown_command("/pr"));
        assert!(!is_unknown_command("/pr 42"));
        assert!(!is_unknown_command("/pr 123"));
    }

    #[test]
    fn test_pr_command_matching() {
        // /pr should match exact or with space separator, not /print etc.
        let pr_matches = |s: &str| s == "/pr" || s.starts_with("/pr ");
        assert!(pr_matches("/pr"));
        assert!(pr_matches("/pr 42"));
        assert!(pr_matches("/pr 123"));
        assert!(!pr_matches("/print"));
        assert!(!pr_matches("/process"));
    }

    #[test]
    fn test_pr_number_parsing() {
        // Verify we can parse a PR number from /pr <number>
        let input = "/pr 42";
        let arg = input.strip_prefix("/pr").unwrap_or("").trim();
        assert_eq!(arg, "42");
        assert!(arg.parse::<u32>().is_ok());
        assert_eq!(arg.parse::<u32>().unwrap(), 42);

        // Bare /pr has empty arg
        let input_bare = "/pr";
        let arg_bare = input_bare.strip_prefix("/pr").unwrap_or("").trim();
        assert!(arg_bare.is_empty());
    }

    #[test]
    fn test_pr_subcommand_list() {
        assert_eq!(parse_pr_args(""), PrSubcommand::List);
        assert_eq!(parse_pr_args("  "), PrSubcommand::List);
    }

    #[test]
    fn test_pr_subcommand_view() {
        assert_eq!(parse_pr_args("42"), PrSubcommand::View(42));
        assert_eq!(parse_pr_args("123"), PrSubcommand::View(123));
        assert_eq!(parse_pr_args("1"), PrSubcommand::View(1));
    }

    #[test]
    fn test_pr_subcommand_diff() {
        assert_eq!(parse_pr_args("42 diff"), PrSubcommand::Diff(42));
        assert_eq!(parse_pr_args("7 diff"), PrSubcommand::Diff(7));
    }

    #[test]
    fn test_pr_subcommand_checkout() {
        assert_eq!(parse_pr_args("42 checkout"), PrSubcommand::Checkout(42));
        assert_eq!(parse_pr_args("99 checkout"), PrSubcommand::Checkout(99));
    }

    #[test]
    fn test_pr_subcommand_comment() {
        assert_eq!(
            parse_pr_args("42 comment looks good!"),
            PrSubcommand::Comment(42, "looks good!".to_string())
        );
        assert_eq!(
            parse_pr_args("10 comment LGTM, merging now"),
            PrSubcommand::Comment(10, "LGTM, merging now".to_string())
        );
    }

    #[test]
    fn test_pr_subcommand_comment_requires_text() {
        // comment without text should show help
        assert_eq!(parse_pr_args("42 comment"), PrSubcommand::Help);
        assert_eq!(parse_pr_args("42 comment  "), PrSubcommand::Help);
    }

    #[test]
    fn test_pr_subcommand_invalid() {
        assert_eq!(parse_pr_args("abc"), PrSubcommand::Help);
        assert_eq!(parse_pr_args("42 unknown"), PrSubcommand::Help);
        assert_eq!(parse_pr_args("42 merge"), PrSubcommand::Help);
    }

    #[test]
    fn test_pr_subcommand_case_insensitive() {
        assert_eq!(parse_pr_args("42 DIFF"), PrSubcommand::Diff(42));
        assert_eq!(parse_pr_args("42 Checkout"), PrSubcommand::Checkout(42));
        assert_eq!(
            parse_pr_args("42 Comment nice work"),
            PrSubcommand::Comment(42, "nice work".to_string())
        );
    }

    #[test]
    fn test_pr_subcommand_create() {
        assert_eq!(
            parse_pr_args("create"),
            PrSubcommand::Create { draft: false }
        );
        assert_eq!(
            parse_pr_args("CREATE"),
            PrSubcommand::Create { draft: false }
        );
        assert_eq!(
            parse_pr_args("Create"),
            PrSubcommand::Create { draft: false }
        );
    }

    #[test]
    fn test_pr_subcommand_create_draft() {
        assert_eq!(
            parse_pr_args("create --draft"),
            PrSubcommand::Create { draft: true }
        );
        assert_eq!(
            parse_pr_args("create draft"),
            PrSubcommand::Create { draft: true }
        );
        assert_eq!(
            parse_pr_args("CREATE --DRAFT"),
            PrSubcommand::Create { draft: true }
        );
    }

    #[test]
    fn test_pr_subcommand_create_no_flag() {
        // "create somethingelse" should still create but not be draft
        assert_eq!(
            parse_pr_args("create --nodraft"),
            PrSubcommand::Create { draft: false }
        );
    }

    #[test]
    fn test_pr_subcommand_recognized() {
        // Subcommands should not be flagged as unknown commands
        assert!(!is_unknown_command("/pr 42 diff"));
        assert!(!is_unknown_command("/pr 42 comment hello"));
        assert!(!is_unknown_command("/pr 42 checkout"));
    }

    // ── Review + diff_stat tests (moved from commands.rs) ───────────────

    #[test]
    fn test_review_command_recognized() {
        assert!(!is_unknown_command("/review"));
        assert!(!is_unknown_command("/review src/main.rs"));
        assert!(
            KNOWN_COMMANDS.contains(&"/review"),
            "/review should be in KNOWN_COMMANDS"
        );
    }

    #[test]
    fn test_review_command_matching() {
        // /review should match exact or with space separator, not /reviewing
        let review_matches = |s: &str| s == "/review" || s.starts_with("/review ");
        assert!(review_matches("/review"));
        assert!(review_matches("/review src/main.rs"));
        assert!(review_matches("/review Cargo.toml"));
        assert!(!review_matches("/reviewing"));
        assert!(!review_matches("/reviewer"));
    }

    #[test]
    fn test_build_review_prompt_contains_content() {
        let prompt =
            build_review_prompt("staged changes", "fn main() {\n    println!(\"hello\");\n}");
        assert!(
            prompt.contains("staged changes"),
            "Should mention the label"
        );
        assert!(prompt.contains("fn main()"), "Should contain the code");
        assert!(prompt.contains("Bugs"), "Should ask for bug review");
        assert!(
            prompt.contains("Security"),
            "Should ask for security review"
        );
        assert!(prompt.contains("Style"), "Should ask for style review");
        assert!(
            prompt.contains("Performance"),
            "Should ask for performance review"
        );
        assert!(prompt.contains("Suggestions"), "Should ask for suggestions");
    }

    #[test]
    fn test_build_review_prompt_truncates_large_content() {
        let large_content = "x".repeat(40_000);
        let prompt = build_review_prompt("big file", &large_content);
        assert!(
            prompt.contains("truncated"),
            "Large content should be truncated"
        );
        assert!(
            prompt.len() < 40_000,
            "Prompt should be truncated, got {} chars",
            prompt.len()
        );
    }

    #[test]
    fn test_build_review_content_nonexistent_file() {
        let result = build_review_content("nonexistent_file_xyz_12345.rs");
        assert!(result.is_none(), "Nonexistent file should return None");
    }

    #[test]
    fn test_build_review_content_existing_file() {
        // Use CARGO_MANIFEST_DIR for an absolute path to avoid CWD races
        // with other tests that call set_current_dir
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let cargo_toml = format!("{manifest_dir}/Cargo.toml");
        let result = build_review_content(&cargo_toml);
        assert!(result.is_some(), "Existing file should return Some");
        let (label, content) = result.unwrap();
        assert_eq!(label, cargo_toml);
        assert!(!content.is_empty(), "Content should not be empty");
    }

    #[test]
    fn test_build_review_content_empty_arg_in_git_repo() {
        // Empty arg reviews staged/unstaged changes
        // In CI, this may or may not have changes — just verify it doesn't panic
        let result = build_review_content("");
        // Result depends on git state — either Some or None is valid
        if let Some((label, _content)) = result {
            assert!(
                label.contains("changes"),
                "Label should describe what's being reviewed: {label}"
            );
        }
    }

    #[test]
    fn test_review_help_text_present() {
        // Verify /review appears in the help output by checking the handle_help function output
        // We can't easily capture stdout, but we can verify the command is in KNOWN_COMMANDS
        // and that the help text format is correct
        assert!(KNOWN_COMMANDS.contains(&"/review"));
    }

    #[test]
    fn test_init_command_recognized() {
        assert!(!is_unknown_command("/init"));
        assert!(
            KNOWN_COMMANDS.contains(&"/init"),
            "/init should be in KNOWN_COMMANDS"
        );
    }

    #[test]
    fn test_parse_diff_stat_basic() {
        let stat_output = " src/commands.rs | 42 ++++++++++++++++++++++++++++--------------
 src/main.rs     |  8 +++++---
 2 files changed, 30 insertions(+), 20 deletions(-)
";
        let summary = parse_diff_stat(stat_output);
        assert_eq!(summary.entries.len(), 2);
        assert_eq!(summary.entries[0].file, "src/commands.rs");
        assert_eq!(summary.entries[1].file, "src/main.rs");
        assert_eq!(summary.total_insertions, 30);
        assert_eq!(summary.total_deletions, 20);
    }

    #[test]
    fn test_parse_diff_stat_single_file() {
        let stat_output = " src/format.rs | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
";
        let summary = parse_diff_stat(stat_output);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "src/format.rs");
        assert_eq!(summary.total_insertions, 7);
        assert_eq!(summary.total_deletions, 3);
    }

    #[test]
    fn test_parse_diff_stat_insertions_only() {
        let stat_output = " new_file.rs | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
";
        let summary = parse_diff_stat(stat_output);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "new_file.rs");
        assert!(summary.entries[0].insertions > 0);
        assert_eq!(summary.entries[0].deletions, 0);
        assert_eq!(summary.total_insertions, 25);
        assert_eq!(summary.total_deletions, 0);
    }

    #[test]
    fn test_parse_diff_stat_deletions_only() {
        let stat_output = " old_file.rs | 15 ---------------
 1 file changed, 15 deletions(-)
";
        let summary = parse_diff_stat(stat_output);
        assert_eq!(summary.entries.len(), 1);
        assert_eq!(summary.entries[0].file, "old_file.rs");
        assert_eq!(summary.entries[0].insertions, 0);
        assert!(summary.entries[0].deletions > 0);
        assert_eq!(summary.total_insertions, 0);
        assert_eq!(summary.total_deletions, 15);
    }

    #[test]
    fn test_parse_diff_stat_empty() {
        let summary = parse_diff_stat("");
        assert!(summary.entries.is_empty());
        assert_eq!(summary.total_insertions, 0);
        assert_eq!(summary.total_deletions, 0);
    }

    #[test]
    fn test_parse_diff_stat_no_summary_line() {
        // Sometimes stat output has no summary — compute from entries
        let stat_output = " src/main.rs | 5 +++--
";
        let summary = parse_diff_stat(stat_output);
        assert_eq!(summary.entries.len(), 1);
        // Totals computed from entry counts
        assert_eq!(summary.total_insertions, summary.entries[0].insertions);
        assert_eq!(summary.total_deletions, summary.entries[0].deletions);
    }

    #[test]
    fn test_parse_diff_stat_multiple_files() {
        let stat_output = " Cargo.toml       |  2 +-
 src/cli.rs       | 15 ++++++++-------
 src/commands.rs  | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++---
 src/format.rs    |  3 ++-
 4 files changed, 78 insertions(+), 30 deletions(-)
";
        let summary = parse_diff_stat(stat_output);
        assert_eq!(summary.entries.len(), 4);
        assert_eq!(summary.entries[0].file, "Cargo.toml");
        assert_eq!(summary.entries[2].file, "src/commands.rs");
        assert_eq!(summary.total_insertions, 78);
        assert_eq!(summary.total_deletions, 30);
    }

    #[test]
    fn test_format_diff_stat_empty() {
        let summary = DiffStatSummary {
            entries: vec![],
            total_insertions: 0,
            total_deletions: 0,
        };
        let formatted = format_diff_stat(&summary);
        assert!(
            formatted.is_empty(),
            "Empty summary should produce empty output"
        );
    }

    #[test]
    fn test_format_diff_stat_single_entry() {
        let summary = DiffStatSummary {
            entries: vec![DiffStatEntry {
                file: "src/main.rs".to_string(),
                insertions: 5,
                deletions: 2,
            }],
            total_insertions: 5,
            total_deletions: 2,
        };
        let formatted = format_diff_stat(&summary);
        assert!(formatted.contains("src/main.rs"), "Should contain filename");
        assert!(
            formatted.contains("1 file changed"),
            "Should show file count"
        );
        assert!(formatted.contains("+5"), "Should show insertions");
        assert!(formatted.contains("-2"), "Should show deletions");
    }

    #[test]
    fn test_format_diff_stat_multiple_entries() {
        let summary = DiffStatSummary {
            entries: vec![
                DiffStatEntry {
                    file: "src/a.rs".to_string(),
                    insertions: 10,
                    deletions: 0,
                },
                DiffStatEntry {
                    file: "src/b.rs".to_string(),
                    insertions: 0,
                    deletions: 5,
                },
            ],
            total_insertions: 10,
            total_deletions: 5,
        };
        let formatted = format_diff_stat(&summary);
        assert!(formatted.contains("src/a.rs"));
        assert!(formatted.contains("src/b.rs"));
        assert!(formatted.contains("2 files changed"));
    }

    #[test]
    fn test_format_diff_stat_insertions_only_no_deletions_shown() {
        let summary = DiffStatSummary {
            entries: vec![DiffStatEntry {
                file: "new.rs".to_string(),
                insertions: 10,
                deletions: 0,
            }],
            total_insertions: 10,
            total_deletions: 0,
        };
        let formatted = format_diff_stat(&summary);
        assert!(formatted.contains("+10"), "Should show insertions");
        // "-0" should not appear
        assert!(!formatted.contains("-0"), "Should not show zero deletions");
    }

    // ── build_undo_context tests ────────────────────────────────────────

    #[test]
    fn build_undo_context_includes_all_actions() {
        let actions = vec![
            "restored src/main.rs".to_string(),
            "deleted src/new_file.rs".to_string(),
        ];
        let ctx = build_undo_context(&actions);
        assert!(ctx.contains("restored src/main.rs"));
        assert!(ctx.contains("deleted src/new_file.rs"));
        assert!(ctx.contains("[System note:"));
        assert!(ctx.contains("may no longer exist"));
        // File count included
        assert!(ctx.contains("2 files"), "Context should include file count");
    }

    #[test]
    fn build_undo_context_single_action() {
        let actions = vec!["restored src/foo.rs".to_string()];
        let ctx = build_undo_context(&actions);
        assert!(ctx.contains("- restored src/foo.rs"));
        assert!(ctx.contains("Verify current file state"));
        // Singular "file" for count of 1
        assert!(
            ctx.contains("1 file"),
            "Context should use singular 'file' for single action"
        );
    }

    #[test]
    fn build_undo_context_warns_about_stale_references() {
        let actions = vec!["restored src/lib.rs".to_string()];
        let ctx = build_undo_context(&actions);
        assert!(
            ctx.contains("⚠️"),
            "Context should contain ⚠️ warning about stale references"
        );
        assert!(
            ctx.contains("may no longer exist"),
            "Context should warn that referenced code may no longer exist"
        );
    }

    #[test]
    fn build_undo_context_recommends_rereading_files() {
        let actions = vec![
            "restored src/a.rs".to_string(),
            "restored src/b.rs".to_string(),
        ];
        let ctx = build_undo_context(&actions);
        assert!(
            ctx.contains("Re-read affected files"),
            "Context should recommend re-reading affected files before new changes"
        );
    }

    // ── handle_undo return value tests ──────────────────────────────────

    #[test]
    fn handle_undo_returns_none_on_empty_history() {
        let mut history = crate::prompt::TurnHistory::new();
        let result = handle_undo("/undo", &mut history);
        assert!(result.is_none(), "Should return None when history is empty");
    }

    #[test]
    fn handle_undo_returns_some_when_files_reverted() {
        use crate::prompt::{TurnHistory, TurnSnapshot};
        use std::fs;

        // Create a temp file to snapshot
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("test_undo.txt");
        fs::write(&file_path, "original content").unwrap();
        let path_str = file_path.to_str().unwrap();

        // Build a snapshot with the original file
        let mut snap = TurnSnapshot::new();
        snap.snapshot_file(path_str);

        // Modify the file (simulating agent changes)
        fs::write(&file_path, "modified content").unwrap();

        // Push the snapshot into history
        let mut history = TurnHistory::new();
        history.push(snap);

        let result = handle_undo("/undo", &mut history);
        assert!(
            result.is_some(),
            "Should return Some when files were reverted"
        );

        let ctx = result.unwrap();
        assert!(
            ctx.contains(path_str),
            "Context should mention the reverted file path"
        );
        assert!(ctx.contains("[System note:"));
        // Verify causality harness content
        assert!(
            ctx.contains("⚠️"),
            "Context should contain ⚠️ stale-reference warning"
        );
        assert!(
            ctx.contains("1 file"),
            "Context should include the affected file count"
        );
        assert!(
            ctx.contains("Re-read affected files"),
            "Context should recommend re-reading files"
        );

        // Verify the file was actually restored
        let restored = fs::read_to_string(&file_path).unwrap();
        assert_eq!(restored, "original content");
    }

    #[test]
    fn handle_undo_returns_none_on_zero_count() {
        let mut history = crate::prompt::TurnHistory::new();
        let result = handle_undo("/undo 0", &mut history);
        assert!(result.is_none());
    }

    #[test]
    fn handle_undo_returns_none_on_bad_arg() {
        let mut history = crate::prompt::TurnHistory::new();
        let result = handle_undo("/undo xyz", &mut history);
        assert!(result.is_none());
    }

    // ── handle_undo --last-commit tests ─────────────────────────────────

    #[test]
    fn handle_undo_dispatches_last_commit() {
        // Verify that "--last-commit" is recognized as a valid argument
        // (not rejected as a bad arg). We only test the parse/dispatch logic
        // here — NOT the actual git revert, because run_git() inherits the
        // process CWD, and `cargo test` runs in the real project directory.
        // Calling handle_undo_last_commit() here would run `git revert HEAD`
        // against real project commits, creating revert commits every time
        // the test suite runs. The actual revert logic is tested in
        // undo_last_commit_in_real_repo() which uses a temp dir.
        let arg = "/undo --last-commit";
        let trimmed = arg.trim_start_matches("/undo").trim();
        assert_eq!(trimmed, "--last-commit", "should parse --last-commit arg");
    }

    #[test]
    fn undo_last_commit_context_format() {
        // Test the context note format that handle_undo_last_commit builds.
        // We replicate the context-building logic to verify the format
        // without needing a real git repo (avoids cwd races).
        let log_line = "abc1234 fix: something important";
        let files = "src/main.rs\nsrc/tools.rs\n";

        let mut actions = Vec::new();
        for f in files.lines().filter(|l| !l.is_empty()) {
            actions.push(format!("reverted changes to {f} (commit undone)"));
        }

        let mut note = String::from("[System note: /undo --last-commit reverted a git commit.\n");
        note.push_str(&format!("Reverted commit: {}\n", log_line.trim()));
        note.push_str("Files affected:\n");
        for action in &actions {
            note.push_str(&format!("- {action}\n"));
        }
        note.push_str(
            "⚠️ Earlier messages in this conversation may reference code from this commit \
             that no longer exists. Verify current file state before continuing.\n",
        );
        note.push_str("Any journal entries about this commit describe work that has been undone.]");

        assert!(note.contains("abc1234 fix: something important"));
        assert!(note.contains("reverted changes to src/main.rs"));
        assert!(note.contains("reverted changes to src/tools.rs"));
        assert!(note.contains("⚠️"));
        assert!(note.contains("journal entries"));
        assert!(note.contains("[System note: /undo --last-commit"));
        assert!(note.contains("has been undone.]"));
    }

    #[test]
    fn undo_last_commit_in_real_repo() {
        use std::fs;

        // Create a temp dir with a git repo
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();

        // Initialize git repo
        let init = std::process::Command::new("git")
            .args(["init"])
            .current_dir(repo)
            .output()
            .unwrap();
        assert!(init.status.success(), "git init failed");

        // Configure git user for the test repo
        let _ = std::process::Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(repo)
            .output();
        let _ = std::process::Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(repo)
            .output();

        // Create initial commit
        let file_path = repo.join("hello.txt");
        fs::write(&file_path, "initial").unwrap();
        let _ = std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(repo)
            .output();
        let _ = std::process::Command::new("git")
            .args(["commit", "-m", "initial commit"])
            .current_dir(repo)
            .output();

        // Create a second commit to revert
        fs::write(&file_path, "changed").unwrap();
        let _ = std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(repo)
            .output();
        let _ = std::process::Command::new("git")
            .args(["commit", "-m", "change hello"])
            .current_dir(repo)
            .output();

        assert_eq!(fs::read_to_string(&file_path).unwrap(), "changed");

        // Capture the commit hash before reverting so we can verify it in context
        let hash_output = std::process::Command::new("git")
            .args(["rev-parse", "--short", "HEAD"])
            .current_dir(repo)
            .output()
            .unwrap();
        let commit_hash = String::from_utf8_lossy(&hash_output.stdout)
            .trim()
            .to_string();

        // Use a static mutex to serialize tests that change cwd,
        // preventing races with other tests that depend on cwd.
        use std::sync::Mutex;
        static CWD_MUTEX: Mutex<()> = Mutex::new(());
        let _lock = CWD_MUTEX.lock().unwrap();

        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(repo).unwrap();

        let result = handle_undo_last_commit();

        std::env::set_current_dir(&original_dir).unwrap();
        // Release lock after cwd is restored (drop happens at end of scope)

        // The revert should succeed
        assert!(
            result.is_some(),
            "handle_undo_last_commit should return Some"
        );
        let ctx = result.unwrap();
        assert!(
            ctx.contains("hello.txt"),
            "Context should mention the reverted file"
        );
        assert!(ctx.contains("⚠️"), "Context should contain the warning");
        assert!(
            ctx.contains("journal entries"),
            "Context should mention journal entries"
        );
        assert!(
            ctx.contains("Reverted commit:"),
            "Context should show the reverted commit"
        );
        // Verify the context includes the actual commit hash
        assert!(
            ctx.contains(&commit_hash),
            "Context should include the commit hash '{commit_hash}'"
        );
        // Verify the context mentions the commit message
        assert!(
            ctx.contains("change hello"),
            "Context should include the commit message"
        );
        // Verify the --last-commit specific system note format
        assert!(
            ctx.contains("[System note: /undo --last-commit"),
            "Context should use --last-commit specific system note"
        );

        // Verify file was reverted to initial content
        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(
            content, "initial",
            "File should be reverted to initial content"
        );
    }

    // ── /blame tests ─────────────────────────────────────────────────────

    #[test]
    fn test_parse_blame_args_file_only() {
        let result = parse_blame_args("/blame src/main.rs").unwrap();
        assert_eq!(result.file, "src/main.rs");
        assert_eq!(result.range, None);
    }

    #[test]
    fn test_parse_blame_args_with_range() {
        let result = parse_blame_args("/blame src/main.rs:10-20").unwrap();
        assert_eq!(result.file, "src/main.rs");
        assert_eq!(result.range, Some((10, 20)));
    }

    #[test]
    fn test_parse_blame_args_single_line_range() {
        let result = parse_blame_args("/blame foo.rs:5-5").unwrap();
        assert_eq!(result.file, "foo.rs");
        assert_eq!(result.range, Some((5, 5)));
    }

    #[test]
    fn test_parse_blame_args_no_args() {
        let result = parse_blame_args("/blame");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Usage"));
    }

    #[test]
    fn test_parse_blame_args_no_args_with_spaces() {
        let result = parse_blame_args("/blame   ");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_blame_args_invalid_range_reversed() {
        let result = parse_blame_args("/blame foo.rs:20-10");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("start"));
    }

    #[test]
    fn test_parse_blame_args_zero_start() {
        let result = parse_blame_args("/blame foo.rs:0-10");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains(">= 1"));
    }

    #[test]
    fn test_parse_blame_args_non_numeric_range_treated_as_file() {
        // If the range part doesn't parse as numbers, treat entire input as filename
        let result = parse_blame_args("/blame some:file:thing").unwrap();
        assert_eq!(result.file, "some:file:thing");
        assert_eq!(result.range, None);
    }

    #[test]
    fn test_colorize_blame_line_typical() {
        let line = "abc1234f (John Doe  2024-01-15 10:30:00 +0000  42) fn main() {";
        let colored = colorize_blame_line(line);
        // Should contain ANSI codes
        assert!(colored.contains("\x1b["));
        // Should still contain the original content
        assert!(colored.contains("John Doe"));
        assert!(colored.contains("fn main()"));
        assert!(colored.contains("abc1234f"));
    }

    #[test]
    fn test_colorize_blame_line_no_paren() {
        // Lines without parens should be returned unchanged
        let line = "some weird line without parens";
        assert_eq!(colorize_blame_line(line), line);
    }

    #[test]
    fn test_colorize_blame_multiple_lines() {
        let input = "abc123 (Alice 2024-01-15 10:00:00 +0000 1) line1\ndef456 (Bob   2024-01-15 10:00:00 +0000 2) line2";
        let colored = colorize_blame(input);
        let lines: Vec<&str> = colored.lines().collect();
        assert_eq!(lines.len(), 2);
        // Both lines should have ANSI codes
        assert!(lines[0].contains("\x1b["));
        assert!(lines[1].contains("\x1b["));
    }
}