branchdiff 0.62.2

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

use anyhow::{Context, Result};

use super::shared::{assemble_results, process_files_parallel, run_vcs_with_retry, FileProcessResult};

/// Detect transient jj errors worth retrying.
/// "stale" matches "The working copy is stale" (exit code 1), which resolves
/// after jj finishes its working copy update.
fn is_transient_jj_error(stderr: &str) -> bool {
    stderr.contains("stale")
}

/// Prepend `--ignore-working-copy` to skip jj's auto-snapshot.
/// Only the first command per refresh cycle needs to snapshot; subsequent
/// commands reuse the snapshot and avoid writing to op_store/working_copy.
fn no_snapshot<'a>(args: &[&'a str]) -> Vec<&'a str> {
    let mut full = Vec::with_capacity(args.len() + 1);
    full.push("--ignore-working-copy");
    full.extend_from_slice(args);
    full
}

use crate::diff::{compute_four_way_diff, DiffInput, FileDiff};
use crate::image_diff::is_image_file;
use crate::limits::DiffMetrics;
use crate::vcs::{ComparisonContext, DiffBase, RefreshResult, StackPosition, UpstreamDivergence, VcsBackend, VcsEventType, VcsWatchPaths};

/// Jujutsu (jj) backend for branchdiff.
pub struct JjVcs {
    repo_path: PathBuf,
    /// Revset for the base of comparison: `trunk()` when available, `@-` otherwise.
    from_rev: String,
    /// Whether to diff from the fork point or the trunk tip.
    /// Stored as AtomicU8 for interior mutability (Vcs trait uses &self).
    /// 0 = ForkPoint, 1 = TrunkTip.
    diff_base: AtomicU8,
}

/// Probe whether `trunk()` points to a real remote-tracking bookmark.
/// `trunk()` falls back to `root()` when no remote exists, which would diff
/// the entire repo history — so only use it when it resolves to an actual branch.
fn resolve_base_rev(repo_path: &Path) -> String {
    let output = Command::new("jj")
        .args([
            "log", "-r", "trunk() ~ root()", "--no-graph",
            "--limit", "1", "-T", "change_id.short(12)",
        ])
        .current_dir(repo_path)
        .output();
    match output {
        Ok(o) if o.status.success() => {
            if String::from_utf8_lossy(&o.stdout).trim().is_empty() {
                "@-".to_string()
            } else {
                "trunk()".to_string()
            }
        }
        _ => "@-".to_string(),
    }
}

/// Find the fork point: the most recent common ancestor of trunk() and @.
/// Returns None if @ is already on top of trunk (no divergence) or if
/// from_rev isn't trunk().
fn resolve_fork_point(repo_path: &Path, from_rev: &str) -> Option<String> {
    if from_rev != "trunk()" {
        return None;
    }

    let args = no_snapshot(&[
        "log", "-r", "heads(::trunk() & ::@)", "--no-graph",
        "--limit", "1", "-T", "commit_id.short(12)",
    ]);
    let output = Command::new("jj")
        .args(&args)
        .current_dir(repo_path)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let fork_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if fork_id.is_empty() {
        return None;
    }

    // Check if fork point equals trunk tip — if so, no divergence
    let trunk_commit = {
        let args = no_snapshot(&[
            "log", "-r", "trunk()", "--no-graph", "--limit", "1",
            "-T", "commit_id.short(12)",
        ]);
        let out = Command::new("jj").args(&args).current_dir(repo_path).output().ok()?;
        if !out.status.success() { return None; }
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };

    if fork_id == trunk_commit {
        // @ is already on top of trunk — no divergence
        return None;
    }

    Some(fork_id)
}

/// Compute upstream divergence for jj: how many commits and which files
/// changed between the fork point and trunk().
fn compute_jj_divergence(
    repo_path: &Path,
    fork_point: &str,
) -> Option<UpstreamDivergence> {
    // Count commits between fork point and trunk
    let revset = format!("\"{}\"..trunk()", fork_point);
    let count_args = no_snapshot(&[
        "log", "-r", &revset,
        "--no-graph", "-T", r#""\n""#,
    ]);
    let count_output = Command::new("jj")
        .args(&count_args)
        .current_dir(repo_path)
        .output()
        .ok()?;
    let behind_count = if count_output.status.success() {
        String::from_utf8_lossy(&count_output.stdout)
            .lines()
            .filter(|l| !l.is_empty())
            .count()
    } else {
        0
    };

    if behind_count == 0 {
        return None;
    }

    // Get files changed between fork point and trunk
    let diff_args = no_snapshot(&[
        "diff", "--from", fork_point, "--to", "trunk()", "--summary",
    ]);
    let diff_output = Command::new("jj")
        .args(&diff_args)
        .current_dir(repo_path)
        .output()
        .ok()?;
    let upstream_files = if diff_output.status.success() {
        parse_jj_summary(&String::from_utf8_lossy(&diff_output.stdout))
            .into_iter()
            .map(|f| f.path)
            .collect()
    } else {
        HashSet::new()
    };

    Some(UpstreamDivergence {
        behind_count,
        upstream_files,
    })
}

/// Info about the stack tip when @ is not at the top.
struct StackTip {
    /// Short change_id of the chosen tip commit.
    change_id: String,
    /// How many independent heads descend from @ (1 = linear stack).
    head_count: usize,
}

/// Find the tip(s) of the mutable stack above @.
/// Returns None when @ is already the tip or from_rev isn't trunk().
fn resolve_stack_tip(repo_path: &Path, from_rev: &str) -> Option<StackTip> {
    if from_rev != "trunk()" {
        return None;
    }

    let args = no_snapshot(&[
        "log", "-r", "heads(trunk()..(@::))", "--no-graph",
        "-T", r#"change_id.short(12) ++ "\n""#,
    ]);
    let output = Command::new("jj")
        .args(&args)
        .current_dir(repo_path)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let heads: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();

    if heads.is_empty() {
        return None;
    }

    // Check if the only head IS @ (meaning @ is already at the tip)
    let at_id = get_change_id_static(repo_path, "@")?;
    if heads.len() == 1 && heads[0].trim() == at_id.trim() {
        return None;
    }

    Some(StackTip {
        change_id: heads[0].trim().to_string(),
        head_count: heads.len(),
    })
}

/// Info about the bookmark boundary for the current stack position.
struct BookmarkBoundary {
    /// Name of the current bookmark.
    bookmark_name: String,
    /// Files changed between the boundary and @, used to filter which files
    /// belong to the current bookmark vs earlier bookmarks.
    changed_files: HashSet<String>,
}

/// Find the bookmark boundary: the nearest ancestor bookmark below the current
/// bookmark's scope. Returns the boundary revision and current bookmark name.
///
/// Strategy:
/// 1. Find the bookmark at or above @ (the bookmark @ belongs to).
/// 2. Find the nearest ancestor bookmark below that one.
fn resolve_bookmark_boundary(repo_path: &Path, from_rev: &str) -> Option<BookmarkBoundary> {
    if from_rev != "trunk()" {
        return None;
    }

    // Step 1: Find the current bookmark — at @ or the nearest descendant with a bookmark
    let template = r#"bookmarks.join(",") ++ "\0" ++ change_id.short(12)"#;
    let args = no_snapshot(&[
        "log", "-r", "latest((@:: | @) & bookmarks())", "--no-graph", "--limit", "1",
        "-T", template,
    ]);
    let output = Command::new("jj")
        .args(&args)
        .current_dir(repo_path)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        return None;
    }

    let parts: Vec<&str> = trimmed.splitn(2, '\0').collect();
    if parts.len() < 2 {
        return None;
    }
    let bookmark_name = parts[0].trim().trim_end_matches('*').to_string();
    let current_bm_id = parts[1].trim().to_string();

    if bookmark_name.is_empty() {
        return None;
    }

    // Step 2: Find the previous bookmark (nearest ancestor bookmark below the current one)
    // Use both local and remote bookmarks — stacks often have only remote-tracking bookmarks
    // for already-pushed segments.
    let revset = format!(
        "latest((trunk()..\"{}\"-) & (bookmarks() | remote_bookmarks()))",
        current_bm_id
    );
    let prev_args = no_snapshot(&[
        "log", "-r", &revset, "--no-graph", "--limit", "1",
        "-T", "change_id.short(12)",
    ]);
    let prev_output = Command::new("jj")
        .args(&prev_args)
        .current_dir(repo_path)
        .output()
        .ok()?;

    let boundary_id = if prev_output.status.success() {
        let prev_id = String::from_utf8_lossy(&prev_output.stdout).trim().to_string();
        if prev_id.is_empty() {
            // No previous bookmark — boundary is trunk
            from_rev.to_string()
        } else {
            prev_id
        }
    } else {
        from_rev.to_string()
    };

    // Step 3: Get the list of files changed between boundary and @
    let range = format!("\"{}\"..@", boundary_id);
    let diff_args = no_snapshot(&[
        "diff", "-r", &range, "--name-only",
    ]);
    let diff_output = Command::new("jj")
        .args(&diff_args)
        .current_dir(repo_path)
        .output()
        .ok()?;

    let changed_files: HashSet<String> = if diff_output.status.success() {
        String::from_utf8_lossy(&diff_output.stdout)
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty())
            .collect()
    } else {
        HashSet::new()
    };

    Some(BookmarkBoundary {
        bookmark_name,
        changed_files,
    })
}

/// Mark each DiffLine in a FileDiff with bookmark provenance.
///
/// Uses the file content at the bookmark boundary revision to determine which
/// lines were introduced before vs. after the boundary.
/// Mark each line's bookmark provenance based on whether the file was changed
/// in the current bookmark's scope (between the previous bookmark and @).
fn mark_bookmark_provenance(file_diff: &mut crate::diff::FileDiff, file_in_current_bookmark: bool) {
    use crate::diff::LineSource;

    for line in &mut file_diff.lines {
        line.in_current_bookmark = Some(match line.source {
            // Change lines: belong to the current bookmark only if the file was
            // modified between the previous bookmark boundary and @.
            LineSource::Committed | LineSource::CanceledCommitted
            | LineSource::DeletedBase | LineSource::Staged
            | LineSource::DeletedCommitted | LineSource::CanceledStaged
            | LineSource::Unstaged | LineSource::DeletedStaged => file_in_current_bookmark,

            LineSource::Base if line.change_source.is_some() => file_in_current_bookmark,

            LineSource::Base | LineSource::FileHeader | LineSource::Elided => false,
        });
    }
}

/// Get a change_id without requiring a JjVcs instance.
fn get_change_id_static(repo_path: &Path, rev: &str) -> Option<String> {
    let args = no_snapshot(&[
        "log", "-r", rev, "--no-graph", "--limit", "1",
        "-T", "change_id.short(12)",
    ]);
    let output = Command::new("jj")
        .args(&args)
        .current_dir(repo_path)
        .output()
        .ok()?;
    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// Compute @'s position in the stack from trunk to tip.
/// Returns (1-based position of @, total commits in stack).
fn compute_stack_position(repo_path: &Path, tip_id: &str) -> Option<(usize, usize)> {
    let revset = format!("trunk()..\"{}\"", tip_id);
    let args = no_snapshot(&[
        "log", "-r", &revset, "--no-graph",
        "-T", r#"if(self.contained_in("@"), "@", ".") ++ "\n""#,
    ]);
    let output = Command::new("jj")
        .args(&args)
        .current_dir(repo_path)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
    let total = entries.len();
    if total == 0 {
        return None;
    }

    // jj log outputs newest-first; @ marker tells us position
    // Position from bottom: total - index_from_top
    let index_from_top = entries.iter().position(|e| e.trim() == "@")?;
    let current = total - index_from_top;

    Some((current, total))
}

impl JjVcs {
    pub fn new(repo_path: PathBuf) -> Result<Self> {
        let from_rev = resolve_base_rev(&repo_path);
        Ok(Self {
            repo_path,
            from_rev,
            diff_base: AtomicU8::new(0),
        })
    }

    fn load_diff_base(&self) -> DiffBase {
        match self.diff_base.load(Ordering::Relaxed) {
            0 => DiffBase::ForkPoint,
            _ => DiffBase::TrunkTip,
        }
    }

    fn run_jj(&self, args: &[&str]) -> Result<String> {
        let output = Command::new("jj")
            .args(args)
            .current_dir(&self.repo_path)
            .output()
            .context("failed to run jj")?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).into_owned())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("jj {} failed: {}", args.join(" "), stderr.trim())
        }
    }

    fn run_jj_bytes(&self, args: &[&str]) -> Result<Option<Vec<u8>>> {
        let output = Command::new("jj")
            .args(args)
            .current_dir(&self.repo_path)
            .output()
            .context("failed to run jj")?;

        if output.status.success() {
            Ok(Some(output.stdout))
        } else {
            Ok(None)
        }
    }

    /// Get changed files between a from revision and effective_to.
    /// The first call per refresh triggers the working copy auto-snapshot;
    /// all subsequent commands use `--ignore-working-copy`.
    fn get_changed_files_with_from(&self, from: &str, effective_to: &str) -> Result<Vec<ChangedFile>> {
        let output = run_vcs_with_retry(
            "jj", &self.repo_path,
            &["diff", "--from", from, "--to", effective_to, "--summary"],
            is_transient_jj_error,
        )?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("jj diff --summary failed: {}", stderr.trim());
        }
        Ok(parse_jj_summary(&String::from_utf8_lossy(&output.stdout)))
    }

    /// Detect binary files by checking --stat output for "(binary)" markers.
    /// Uses `--ignore-working-copy` since the snapshot is already fresh from
    /// `get_changed_files`.
    fn get_binary_files_set(&self, from: &str, effective_to: &str) -> HashSet<String> {
        let args = no_snapshot(&[
            "diff", "--from", from, "--to", effective_to, "--stat",
        ]);
        let Ok(output) = run_vcs_with_retry("jj", &self.repo_path, &args, is_transient_jj_error) else {
            return HashSet::new();
        };
        if !output.status.success() {
            return HashSet::new();
        }
        parse_binary_from_stat(&String::from_utf8_lossy(&output.stdout))
    }

    fn get_file_bytes_at_rev(&self, file_path: &str, rev: &str) -> Result<Option<Vec<u8>>> {
        self.run_jj_bytes(&["file", "show", "-r", rev, file_path])
    }

    /// Get the current change ID for a revision.
    fn get_change_id(&self, rev: &str) -> Result<String> {
        let output = self.run_jj(&["log", "-r", rev, "-T", "change_id.short(12)", "--no-graph", "--limit", "1"])?;
        Ok(output.trim().to_string())
    }

    #[cfg(test)]
    fn get_bookmarks(&self, rev: &str) -> Option<String> {
        let output = self.run_jj(&["log", "-r", rev, "-T", "bookmarks", "--no-graph", "--limit", "1"]).ok()?;
        let trimmed = output.trim().trim_end_matches('*');
        if trimmed.is_empty() { None } else { Some(trimmed.to_string()) }
    }

    #[cfg(test)]
    fn rev_label(&self, rev: &str) -> String {
        self.get_bookmarks(rev)
            .unwrap_or_else(|| self.get_change_id(rev).unwrap_or_else(|_| rev.to_string()))
    }

    /// Fetch bookmarks and change_id for a revision in a single command,
    /// using `--ignore-working-copy` to avoid redundant auto-snapshots.
    /// Returns (change_id, display_label).
    fn rev_metadata_no_snapshot(&self, rev: &str) -> (String, String) {
        let template = r#"bookmarks ++ "\0" ++ change_id.short(12) ++ "\0" ++ change_id.shortest(4)"#;
        let args = no_snapshot(&[
            "log", "-r", rev, "-T", template, "--no-graph", "--limit", "1",
        ]);
        match self.run_jj(&args) {
            Ok(raw) => parse_rev_metadata(&raw),
            Err(_) => (rev.to_string(), rev.to_string()),
        }
    }

    /// Check if repo is colocated (has .git directory alongside .jj).
    fn is_colocated(&self) -> bool {
        self.repo_path.join(".git").exists()
    }
}

/// Parse combined `bookmarks ++ "\0" ++ change_id ++ "\0" ++ shortest_id` template output.
/// Returns (change_id, display_label) where label annotates bookmarks with the shortest
/// unique change ID prefix: `"main (knmq)"`.
fn parse_rev_metadata(raw: &str) -> (String, String) {
    let raw = raw.trim();
    let parts: Vec<&str> = raw.splitn(3, '\0').collect();
    if parts.len() >= 2 {
        let bookmarks = parts[0].trim().trim_end_matches('*');
        let change_id = parts[1].trim().to_string();
        let shortest_id = parts.get(2).map(|s| s.trim()).unwrap_or("");
        let label = if bookmarks.is_empty() {
            if shortest_id.is_empty() { change_id.clone() } else { shortest_id.to_string() }
        } else if shortest_id.is_empty() {
            bookmarks.to_string()
        } else {
            format!("{shortest_id} ({bookmarks})")
        };
        (change_id, label)
    } else {
        (raw.to_string(), raw.to_string())
    }
}

/// Read file content at a revision without triggering auto-snapshot.
/// Free function for use in parallel contexts (rayon).
fn file_content_no_snapshot(repo_path: &Path, file_path: &str, rev: &str) -> Option<String> {
    let args = no_snapshot(&["file", "show", "-r", rev, file_path]);
    let output = Command::new("jj")
        .args(&args)
        .current_dir(repo_path)
        .output()
        .ok()?;
    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).into_owned())
    } else {
        None
    }
}

fn process_jj_file(
    repo_path: &Path,
    from_rev: &str,
    changed: &ChangedFile,
    binary_files: &HashSet<String>,
    tip_rev: Option<&str>,
    bookmark_changed_files: Option<&HashSet<String>>,
) -> FileProcessResult {
    if binary_files.contains(&changed.path) {
        if is_image_file(&changed.path) {
            return FileProcessResult::Image { path: changed.path.clone() };
        }
        return FileProcessResult::Binary { path: changed.path.clone() };
    }

    let base_path = changed.old_path.as_deref().unwrap_or(&changed.path);
    let base = file_content_no_snapshot(repo_path, base_path, from_rev);

    // @- content for the committed/staged boundary — try current path first,
    // fall back to old_path for files renamed in the current commit
    let parent = file_content_no_snapshot(repo_path, &changed.path, "@-")
        .or_else(|| {
            changed.old_path.as_deref()
                .and_then(|old| file_content_no_snapshot(repo_path, old, "@-"))
        });

    let index = file_content_no_snapshot(repo_path, &changed.path, "@");
    let tip_content = tip_rev
        .and_then(|tip| file_content_no_snapshot(repo_path, &changed.path, tip));

    // When tip_rev is None (@ is at tip), working == index.
    // When tip_rev is Some, working is the tip content — even if None (file
    // deleted above @). TODO: algorithm.rs check_file_deletion collapses the
    // per-commit coloring into a flat DeletedStaged block. A proper fix needs
    // a new code path that preserves base/head/index provenance while marking
    // the file as eventually-deleted.
    let working = match tip_rev {
        Some(_) => tip_content.as_deref(),
        None => index.as_deref(),
    };

    let mut file_diff = compute_four_way_diff(DiffInput {
        path: &changed.path,
        base: base.as_deref(),
        head: parent.as_deref(),
        index: index.as_deref(),
        working,
        old_path: changed.old_path.as_deref(),
    });

    if let Some(bm_files) = bookmark_changed_files {
        let in_bookmark = bm_files.contains(&changed.path);
        mark_bookmark_provenance(&mut file_diff, in_bookmark);
    }

    FileProcessResult::Diff(file_diff)
}

/// Get the jj repo root from a path.
pub fn get_repo_root(path: &Path) -> Result<PathBuf> {
    let output = Command::new("jj")
        .args(["root"])
        .current_dir(path)
        .output()
        .context("failed to run jj root")?;

    if output.status.success() {
        let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
        Ok(PathBuf::from(root))
    } else {
        anyhow::bail!("not a jj repository")
    }
}

impl crate::vcs::Vcs for JjVcs {
    fn repo_path(&self) -> &Path {
        &self.repo_path
    }

    fn comparison_context(&self) -> Result<ComparisonContext> {
        let template = r#"bookmarks ++ "\0" ++ change_id.short(12) ++ "\0" ++ change_id.shortest(4)"#;
        // First call triggers auto-snapshot to capture current working copy
        let from_output = run_vcs_with_retry(
            "jj", &self.repo_path,
            &["log", "-r", &self.from_rev, "-T", template, "--no-graph", "--limit", "1"],
            is_transient_jj_error,
        )?;
        let from_label = if from_output.status.success() {
            parse_rev_metadata(&String::from_utf8_lossy(&from_output.stdout)).1
        } else {
            self.from_rev.clone()
        };

        // Second call skips snapshot (already fresh)
        let to_args = no_snapshot(&[
            "log", "-r", "@", "-T", template, "--no-graph", "--limit", "1",
        ]);
        let to_output = run_vcs_with_retry("jj", &self.repo_path, &to_args, is_transient_jj_error)?;
        let to_label = if to_output.status.success() {
            parse_rev_metadata(&String::from_utf8_lossy(&to_output.stdout)).1
        } else {
            "@".to_string()
        };

        // stack_position is computed by refresh() and applied via
        // apply_refresh_result — no need to resolve it here too.
        Ok(ComparisonContext { from_label, to_label, stack_position: None, vcs_backend: VcsBackend::Jj, bookmark_name: None, divergence: None })
    }

    fn refresh(&self, cancel_flag: &Arc<AtomicBool>) -> Result<RefreshResult> {
        // Resolve fork point for divergence detection and fork-point mode
        let fork_point = resolve_fork_point(&self.repo_path, &self.from_rev);
        let divergence = fork_point.as_deref()
            .and_then(|fp| compute_jj_divergence(&self.repo_path, fp));

        // Determine the effective --from rev based on diff_base mode
        let effective_from = match self.load_diff_base() {
            DiffBase::ForkPoint => fork_point.as_deref().unwrap_or(&self.from_rev),
            DiffBase::TrunkTip => &self.from_rev,
        };

        // Resolve stack tip — determines if @ is mid-stack
        let stack_tip = resolve_stack_tip(&self.repo_path, &self.from_rev);
        let effective_to = stack_tip
            .as_ref()
            .map(|t| t.change_id.as_str())
            .unwrap_or("@");
        let tip_rev = stack_tip.as_ref().map(|t| t.change_id.as_str());

        // Resolve bookmark boundary for BookmarkOnly view mode
        let bookmark_boundary = resolve_bookmark_boundary(&self.repo_path, &self.from_rev);
        let bookmark_changed_files = bookmark_boundary.as_ref().map(|b| &b.changed_files);

        // First command — triggers working copy auto-snapshot
        let changed_files = self.get_changed_files_with_from(effective_from, effective_to)?;

        if cancel_flag.load(Ordering::Relaxed) {
            anyhow::bail!("refresh cancelled");
        }

        // All subsequent commands use --ignore-working-copy
        let binary_files = self.get_binary_files_set(effective_from, effective_to);

        if cancel_flag.load(Ordering::Relaxed) {
            anyhow::bail!("refresh cancelled");
        }

        let results = process_files_parallel(&changed_files, |changed| {
            process_jj_file(
                &self.repo_path,
                effective_from,
                changed,
                &binary_files,
                tip_rev,
                bookmark_changed_files,
            )
        });

        if cancel_flag.load(Ordering::Relaxed) {
            anyhow::bail!("refresh cancelled");
        }

        let assembled = assemble_results(results);
        let files = assembled.files;
        let all_lines = assembled.lines;

        let stack_position = stack_tip.as_ref().and_then(|tip| {
            let (current, total) = compute_stack_position(&self.repo_path, &tip.change_id)?;
            Some(StackPosition {
                current,
                total,
                head_count: tip.head_count,
            })
        });

        let metrics = DiffMetrics {
            total_lines: all_lines.len(),
            file_count: files.len(),
        };
        let (base_identifier, base_label_str) =
            self.rev_metadata_no_snapshot(effective_from);
        let (_, current_branch_str) = self.rev_metadata_no_snapshot("@");

        let file_paths: Vec<&str> = files
            .iter()
            .filter_map(|f| f.lines.first())
            .filter_map(|l| l.file_path.as_deref())
            .collect();
        let file_links = crate::file_links::compute_file_links(&file_paths);

        Ok(RefreshResult {
            files,
            lines: all_lines,
            base_identifier,
            base_label: Some(base_label_str),
            current_branch: Some(current_branch_str),
            metrics,
            file_links,
            stack_position,
            bookmark_name: bookmark_boundary.map(|b| b.bookmark_name),
            revision_id: None,
            divergence,
        })
    }

    fn single_file_diff(&self, file_path: &str) -> Option<FileDiff> {
        let fork_point = resolve_fork_point(&self.repo_path, &self.from_rev);
        let effective_from = match self.load_diff_base() {
            DiffBase::ForkPoint => fork_point.as_deref().unwrap_or(&self.from_rev),
            DiffBase::TrunkTip => &self.from_rev,
        };

        let stack_tip = resolve_stack_tip(&self.repo_path, &self.from_rev);
        let effective_to = stack_tip
            .as_ref()
            .map(|t| t.change_id.as_str())
            .unwrap_or("@");

        // First command triggers auto-snapshot
        let changed_files = self.get_changed_files_with_from(effective_from, effective_to).ok()?;
        let changed = changed_files.iter().find(|f| f.path == file_path);
        let old_path = changed.and_then(|f| f.old_path.as_deref());

        // Subsequent commands skip snapshot
        let base_path = old_path.unwrap_or(file_path);
        let base = file_content_no_snapshot(&self.repo_path, base_path, effective_from);

        let parent = file_content_no_snapshot(&self.repo_path, file_path, "@-")
            .or_else(|| {
                old_path.and_then(|old| file_content_no_snapshot(&self.repo_path, old, "@-"))
            });

        let index = file_content_no_snapshot(&self.repo_path, file_path, "@");
        let tip_content = stack_tip
            .as_ref()
            .and_then(|t| file_content_no_snapshot(&self.repo_path, file_path, &t.change_id));
        let has_tip = stack_tip.is_some();

        if base.is_none() && index.is_none() && tip_content.is_none() {
            return None;
        }

        let binary_files = self.get_binary_files_set(effective_from, effective_to);
        if binary_files.contains(file_path) {
            return None;
        }

        let working = if has_tip { tip_content.as_deref() } else { index.as_deref() };

        let mut file_diff = compute_four_way_diff(DiffInput {
            path: file_path,
            base: base.as_deref(),
            head: parent.as_deref(),
            index: index.as_deref(),
            working,
            old_path,
        });

        // Mark bookmark provenance for BookmarkOnly view mode
        if let Some(boundary) = resolve_bookmark_boundary(&self.repo_path, &self.from_rev) {
            let in_bookmark = boundary.changed_files.contains(file_path);
            mark_bookmark_provenance(&mut file_diff, in_bookmark);
        }

        Some(file_diff)
    }

    fn base_identifier(&self) -> Result<String> {
        self.get_change_id(&self.from_rev)
    }

    fn current_revision_id(&self) -> Result<String> {
        self.run_jj(&[
            "--ignore-working-copy",
            "log", "-r", "@", "--no-graph", "--limit", "1",
            "-T", "change_id.short(12)",
        ])
        .map(|s| s.trim().to_string())
    }

    fn base_file_bytes(&self, file_path: &str) -> Result<Option<Vec<u8>>> {
        self.get_file_bytes_at_rev(file_path, &self.from_rev)
    }

    fn working_file_bytes(&self, file_path: &str) -> Result<Option<Vec<u8>>> {
        self.get_file_bytes_at_rev(file_path, "@")
    }

    fn binary_files(&self) -> HashSet<String> {
        self.get_binary_files_set(&self.from_rev, "@")
    }

    fn fetch(&self) -> Result<()> {
        if self.is_colocated() {
            self.run_jj(&["git", "fetch"])?;
        }
        Ok(())
    }

    fn has_conflicts(&self) -> Result<bool> {
        // jj conflict detection is a future enhancement
        Ok(false)
    }

    fn is_locked(&self) -> bool {
        // jj doesn't use lock files the same way git does
        false
    }

    fn watch_paths(&self) -> VcsWatchPaths {
        let jj_dir = self.repo_path.join(".jj");
        VcsWatchPaths {
            files: vec![jj_dir.join("working_copy/checkout")],
            recursive_dirs: vec![jj_dir.join("repo/op_store")],
        }
    }

    fn classify_event(&self, path: &Path) -> VcsEventType {
        let relative = path.strip_prefix(&self.repo_path).unwrap_or(path);
        let first = relative.components().next().map(|c| c.as_os_str());

        if first.is_some_and(|c| c == ".jj") {
            let path_str = relative.to_string_lossy();
            return if path_str.contains("working_copy/") {
                VcsEventType::RevisionChange
            } else {
                VcsEventType::Internal
            };
        }

        if first.is_some_and(|c| c == ".git") && self.is_colocated() {
            return VcsEventType::Internal;
        }

        VcsEventType::Source
    }

    fn backend(&self) -> VcsBackend {
        VcsBackend::Jj
    }

    fn set_diff_base(&self, base: DiffBase) {
        let val = match base {
            DiffBase::ForkPoint => 0,
            DiffBase::TrunkTip => 1,
        };
        self.diff_base.store(val, Ordering::Relaxed);
    }
}

/// Changed file from jj diff --summary output.
#[derive(Debug, Clone)]
struct ChangedFile {
    path: String,
    old_path: Option<String>,
}

/// Parse `jj diff --summary` output into changed files.
///
/// Renames use the format `R {old_path => new_path}`.
fn parse_jj_summary(output: &str) -> Vec<ChangedFile> {
    output
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            if line.is_empty() {
                return None;
            }
            let first = line.chars().next()?;
            if !matches!(first, 'M' | 'A' | 'D' | 'R' | 'C') {
                return None;
            }
            let rest = line[1..].trim();
            if rest.is_empty() {
                return None;
            }
            if first == 'R' {
                parse_rename(rest)
            } else {
                Some(ChangedFile { path: rest.to_string(), old_path: None })
            }
        })
        .collect()
}

/// Parse jj rename format: `{old_path => new_path}`
fn parse_rename(s: &str) -> Option<ChangedFile> {
    let s = s.strip_prefix('{')?.strip_suffix('}')?;
    let (old, new) = s.split_once(" => ")?;
    let old = old.trim();
    let new = new.trim();
    if new.is_empty() {
        return None;
    }
    Some(ChangedFile {
        path: new.to_string(),
        old_path: Some(old.to_string()),
    })
}

/// Parse `jj diff --stat` output to find binary files (marked with "(binary)").
///
/// Handles renamed files: `{old => new} | (binary)` extracts just the new name.
fn parse_binary_from_stat(output: &str) -> HashSet<String> {
    output
        .lines()
        .filter(|line| line.contains("(binary)"))
        .filter_map(|line| {
            let raw_path = line.split('|').next()?.trim();
            if raw_path.is_empty() {
                return None;
            }
            // Renames show as "{old => new}" — extract the new name
            let path = if let Some(inner) = raw_path.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
                inner.split(" => ").last().unwrap_or(inner).trim()
            } else if raw_path.contains(" => ") {
                raw_path.split(" => ").last().unwrap_or(raw_path).trim()
            } else {
                raw_path
            };
            if path.is_empty() { None } else { Some(path.to_string()) }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::LineSource;
    use crate::vcs::Vcs;

    // === parse_jj_summary tests ===

    #[test]
    fn test_parse_summary_modified() {
        let files = parse_jj_summary("M file.txt\n");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "file.txt");
        assert!(files[0].old_path.is_none());
    }

    #[test]
    fn test_parse_summary_added() {
        let files = parse_jj_summary("A new_file.txt\n");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "new_file.txt");
        assert!(files[0].old_path.is_none());
    }

    #[test]
    fn test_parse_summary_deleted() {
        let files = parse_jj_summary("D old_file.txt\n");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "old_file.txt");
    }

    #[test]
    fn test_parse_summary_renamed() {
        let files = parse_jj_summary("R {old_name.txt => new_name.txt}\n");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "new_name.txt");
        assert_eq!(files[0].old_path.as_deref(), Some("old_name.txt"));
    }

    #[test]
    fn test_parse_summary_renamed_with_directory() {
        let files = parse_jj_summary("R {src/old.rs => src/new.rs}\n");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/new.rs");
        assert_eq!(files[0].old_path.as_deref(), Some("src/old.rs"));
    }

    #[test]
    fn test_parse_summary_multiple() {
        let output = "M file1.txt\nA file2.txt\nD file3.txt\n";
        let files = parse_jj_summary(output);
        assert_eq!(files.len(), 3);
        assert_eq!(files[0].path, "file1.txt");
        assert_eq!(files[1].path, "file2.txt");
        assert_eq!(files[2].path, "file3.txt");
    }

    #[test]
    fn test_parse_summary_mixed_with_rename() {
        let output = "M file.txt\nR {old.rs => new.rs}\nA added.txt\n";
        let files = parse_jj_summary(output);
        assert_eq!(files.len(), 3);
        assert_eq!(files[0].path, "file.txt");
        assert!(files[0].old_path.is_none());
        assert_eq!(files[1].path, "new.rs");
        assert_eq!(files[1].old_path.as_deref(), Some("old.rs"));
        assert_eq!(files[2].path, "added.txt");
        assert!(files[2].old_path.is_none());
    }

    #[test]
    fn test_parse_summary_empty() {
        let files = parse_jj_summary("");
        assert!(files.is_empty());
    }

    #[test]
    fn test_parse_summary_skips_blank_lines() {
        let output = "M file.txt\n\nA other.txt\n";
        let files = parse_jj_summary(output);
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_parse_summary_path_with_spaces() {
        let files = parse_jj_summary("M path with spaces.txt\n");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "path with spaces.txt");
    }

    #[test]
    fn test_parse_rename_malformed_no_braces() {
        let files = parse_jj_summary("R old.txt => new.txt\n");
        assert!(files.is_empty(), "rename without braces should be skipped");
    }

    #[test]
    fn test_parse_rename_malformed_no_arrow() {
        let files = parse_jj_summary("R {old.txt new.txt}\n");
        assert!(files.is_empty(), "rename without => should be skipped");
    }

    // === parse_binary_from_stat tests ===

    #[test]
    fn test_parse_binary_from_stat_detects_binary() {
        let output = "image.png | (binary)\nfile.txt  | 2 +-\n1 file changed\n";
        let binaries = parse_binary_from_stat(output);
        assert!(binaries.contains("image.png"));
        assert!(!binaries.contains("file.txt"));
    }

    #[test]
    fn test_parse_binary_from_stat_empty() {
        let binaries = parse_binary_from_stat("file.txt | 2 +-\n");
        assert!(binaries.is_empty());
    }

    #[test]
    fn test_parse_binary_from_stat_multiple() {
        let output = "a.png | (binary)\nb.jpg | (binary)\nc.txt | 1 +\n";
        let binaries = parse_binary_from_stat(output);
        assert_eq!(binaries.len(), 2);
        assert!(binaries.contains("a.png"));
        assert!(binaries.contains("b.jpg"));
    }

    #[test]
    fn test_parse_binary_from_stat_renamed_with_braces() {
        let output = "{original.bin => renamed.bin} | (binary)\n";
        let binaries = parse_binary_from_stat(output);
        assert!(binaries.contains("renamed.bin"), "should extract new name from rename");
        assert!(!binaries.contains("{original.bin => renamed.bin}"), "should not store raw rename format");
    }

    #[test]
    fn test_parse_binary_from_stat_renamed_without_braces() {
        let output = "original.bin => renamed.bin | (binary)\n";
        let binaries = parse_binary_from_stat(output);
        assert!(binaries.contains("renamed.bin"), "should extract new name from arrow format");
    }

    // === parse_rev_metadata tests ===

    #[test]
    fn test_parse_rev_metadata_with_bookmark() {
        let (change_id, label) = parse_rev_metadata("my-feature\0abcdef123456\n");
        assert_eq!(change_id, "abcdef123456");
        assert_eq!(label, "my-feature");
    }

    #[test]
    fn test_parse_rev_metadata_without_bookmark() {
        let (change_id, label) = parse_rev_metadata("\0abcdef123456\n");
        assert_eq!(change_id, "abcdef123456");
        assert_eq!(label, "abcdef123456");
    }

    #[test]
    fn test_parse_rev_metadata_strips_tracking_marker() {
        let (change_id, label) = parse_rev_metadata("main*\0abcdef123456\n");
        assert_eq!(change_id, "abcdef123456");
        assert_eq!(label, "main");
    }

    #[test]
    fn test_parse_rev_metadata_empty_string() {
        let (change_id, label) = parse_rev_metadata("");
        assert_eq!(change_id, "");
        assert_eq!(label, "");
    }

    #[test]
    fn test_parse_rev_metadata_no_separator() {
        let (change_id, label) = parse_rev_metadata("fallback_text");
        assert_eq!(change_id, "fallback_text");
        assert_eq!(label, "fallback_text");
    }

    // === no_snapshot helper tests ===

    #[test]
    fn test_no_snapshot_prepends_flag() {
        let args = no_snapshot(&["diff", "--from", "@-", "--to", "@"]);
        assert_eq!(args[0], "--ignore-working-copy");
        assert_eq!(args[1], "diff");
        assert_eq!(args.len(), 6);
    }

    // === classify_event tests ===

    #[test]
    fn test_classify_source_file() {
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        assert_eq!(
            vcs.classify_event(Path::new("/repo/src/main.rs")),
            VcsEventType::Source
        );
    }

    #[test]
    fn test_classify_jj_op_store_as_internal() {
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        assert_eq!(
            vcs.classify_event(Path::new("/repo/.jj/repo/op_store/heads")),
            VcsEventType::Internal
        );
    }

    #[test]
    fn test_classify_jj_working_copy() {
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        assert_eq!(
            vcs.classify_event(Path::new("/repo/.jj/working_copy/checkout")),
            VcsEventType::RevisionChange
        );
    }

    #[test]
    fn test_classify_jj_internal() {
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        assert_eq!(
            vcs.classify_event(Path::new("/repo/.jj/repo/store/something")),
            VcsEventType::Internal
        );
    }

    #[test]
    fn test_classify_path_outside_repo() {
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        assert_eq!(
            vcs.classify_event(Path::new("/other/file.rs")),
            VcsEventType::Source
        );
    }

    #[test]
    fn test_classify_git_index_as_internal_in_colocated_repo() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join(".jj")).unwrap();
        std::fs::create_dir_all(temp.path().join(".git")).unwrap();
        let vcs = JjVcs::new(temp.path().to_path_buf()).unwrap();
        assert_eq!(
            vcs.classify_event(&temp.path().join(".git/index")),
            VcsEventType::Internal
        );
    }

    #[test]
    fn test_classify_git_objects_as_internal_in_colocated_repo() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join(".jj")).unwrap();
        std::fs::create_dir_all(temp.path().join(".git")).unwrap();
        let vcs = JjVcs::new(temp.path().to_path_buf()).unwrap();
        assert_eq!(
            vcs.classify_event(&temp.path().join(".git/objects/ab/cd1234")),
            VcsEventType::Internal
        );
    }

    #[test]
    fn test_classify_git_refs_as_internal_in_colocated_repo() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join(".jj")).unwrap();
        std::fs::create_dir_all(temp.path().join(".git")).unwrap();
        let vcs = JjVcs::new(temp.path().to_path_buf()).unwrap();
        assert_eq!(
            vcs.classify_event(&temp.path().join(".git/refs/jj/keep/abc123")),
            VcsEventType::Internal
        );
    }

    #[test]
    fn test_classify_git_head_as_internal_in_colocated_repo() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join(".jj")).unwrap();
        std::fs::create_dir_all(temp.path().join(".git")).unwrap();
        let vcs = JjVcs::new(temp.path().to_path_buf()).unwrap();
        assert_eq!(
            vcs.classify_event(&temp.path().join(".git/HEAD")),
            VcsEventType::Internal
        );
    }

    #[test]
    fn test_classify_git_path_as_source_in_non_colocated_repo() {
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        assert_eq!(
            vcs.classify_event(Path::new("/repo/.git/index")),
            VcsEventType::Source
        );
    }

    #[test]
    fn test_classify_source_file_in_colocated_repo() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join(".jj")).unwrap();
        std::fs::create_dir_all(temp.path().join(".git")).unwrap();
        let vcs = JjVcs::new(temp.path().to_path_buf()).unwrap();
        assert_eq!(
            vcs.classify_event(&temp.path().join("src/main.rs")),
            VcsEventType::Source
        );
    }

    // === watch_paths tests ===

    #[test]
    fn test_watch_paths() {
        use crate::vcs::Vcs;
        let vcs = JjVcs::new(PathBuf::from("/repo")).unwrap();
        let paths = vcs.watch_paths();
        assert!(paths.files.contains(&PathBuf::from("/repo/.jj/working_copy/checkout")));
        assert!(paths.recursive_dirs.contains(&PathBuf::from("/repo/.jj/repo/op_store")));
    }

    // === is_transient_jj_error tests ===

    #[test]
    fn test_transient_error_stale() {
        assert!(is_transient_jj_error("The working copy is stale"));
    }

    #[test]
    fn test_not_transient_error() {
        assert!(!is_transient_jj_error("fatal: not a jj repository"));
        assert!(!is_transient_jj_error("Error: revision not found"));
        assert!(!is_transient_jj_error(""));
    }

    // === run_vcs_with_retry tests (jj) ===

    #[test]
    fn test_run_vcs_with_retry_jj_succeeds_on_first_attempt() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        Command::new("jj").args(["git", "init"]).current_dir(temp.path()).output().unwrap();

        let output = run_vcs_with_retry("jj", temp.path(), &["log", "--limit", "1"], is_transient_jj_error).unwrap();
        assert!(output.status.success());
    }

    #[test]
    fn test_run_vcs_with_retry_jj_returns_failure_for_permanent_error() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        Command::new("jj").args(["git", "init"]).current_dir(temp.path()).output().unwrap();

        let output = run_vcs_with_retry("jj", temp.path(), &["log", "-r", "nonexistent_rev_xyz"], is_transient_jj_error).unwrap();
        assert!(!output.status.success());
    }

    // === Integration tests (require jj installed) ===

    fn jj_available() -> bool {
        Command::new("jj").arg("--version").output().is_ok_and(|o| o.status.success())
    }

    #[test]
    fn test_jj_refresh_detects_modified_file() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "initial\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "modified\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert!(!result.files.is_empty(), "should detect changed file");
        assert!(!result.lines.is_empty(), "should produce diff lines");

        // With from_rev=@- (no remote), base==head so all @→@ changes are Staged
        let has_staged = result.lines.iter().any(|l| l.source == LineSource::Staged);
        assert!(has_staged, "modified lines should have Staged source (current commit)");
        let header = &result.lines[0];
        assert_eq!(header.source, LineSource::FileHeader, "first line should be file header");
        assert!(!header.content.contains("(deleted)"),
            "modified file should not have deletion header, got: {}", header.content);
    }

    #[test]
    fn test_jj_refresh_detects_new_file() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("existing.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("new_file.txt"), "new content\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert!(!result.files.is_empty(), "should detect new file");
        let has_new_content = result.lines.iter().any(|l| l.content.contains("new content"));
        assert!(has_new_content, "should contain new file content in diff lines");
    }

    #[test]
    fn test_jj_comparison_context() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let ctx = vcs.comparison_context().unwrap();

        assert!(!ctx.to_label.is_empty(), "should have a to label");
        assert!(!ctx.from_label.is_empty(), "should have a from label");

        let base_id = vcs.base_identifier().unwrap();
        assert!(!base_id.is_empty(), "should have a base identifier");
    }

    #[test]
    fn test_jj_base_file_bytes() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "original\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "changed\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let base = vcs.base_file_bytes("file.txt").unwrap();
        assert_eq!(base.unwrap(), b"original\n");

        let working = vcs.working_file_bytes("file.txt").unwrap();
        assert_eq!(working.unwrap(), b"changed\n");
    }

    #[test]
    fn test_jj_refresh_detects_deleted_file() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("doomed.txt"), "goodbye\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        std::fs::remove_file(repo.join("doomed.txt")).unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert!(!result.files.is_empty(), "should detect deleted file");
        let header = &result.lines[0];
        assert!(header.content.contains("(deleted)"),
            "deleted file should have deletion header, got: {}", header.content);
        // With from_rev=@- (no remote), base==head so deletions in @ are DeletedCommitted
        let has_deleted_source = result.lines.iter().any(|l| l.source == LineSource::DeletedCommitted);
        assert!(has_deleted_source, "deleted file lines should have DeletedCommitted source");
    }

    #[test]
    fn test_jj_single_file_diff_handles_rename() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("original.txt"), "line1\nline2\nline3\nline4\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        std::fs::rename(repo.join("original.txt"), repo.join("renamed.txt")).unwrap();
        std::fs::write(repo.join("renamed.txt"), "line1\nline2\nline3\nmodified\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let diff = vcs.single_file_diff("renamed.txt");
        assert!(diff.is_some(), "should produce a diff for renamed file");

        let diff = diff.unwrap();
        let header = &diff.lines[0];
        assert!(
            header.content.contains("original.txt"),
            "rename header should reference old filename, got: {}",
            header.content
        );
    }

    #[test]
    fn test_jj_get_repo_root() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();

        let root = get_repo_root(repo).unwrap();
        // Canonicalize both to handle /tmp vs /private/tmp on macOS
        let expected = repo.canonicalize().unwrap();
        let actual = root.canonicalize().unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_jj_refresh_returns_base_label_with_bookmark() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["bookmark", "set", "my-base", "-r", "@-"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "changed\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        let base_label = result.base_label.expect("should have base_label");
        assert!(base_label.contains("(my-base)"),
            "label should contain bookmark in parens, got: {base_label}");
        assert!(base_label.ends_with(')'),
            "label should end with ), got: {base_label}");
    }

    #[test]
    fn test_jj_refresh_returns_base_label_as_change_id_without_bookmark() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "changed\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        let base_label = result.base_label.expect("should have base_label");
        assert!(!base_label.is_empty());
        assert!(result.base_identifier.starts_with(&base_label),
            "without bookmark, base_label should be a prefix of base_identifier: label={base_label}, id={}", result.base_identifier);
    }

    #[test]
    fn test_jj_bookmark_strips_tracking_marker() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["bookmark", "set", "my-branch"]).current_dir(repo).output().unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let label = vcs.rev_label("@");
        assert_eq!(label, "my-branch", "should strip trailing * from bookmark name");
    }

    #[test]
    fn test_jj_refresh_parallel_with_multiple_files() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        for i in 0..6 {
            std::fs::write(repo.join(format!("file{i}.txt")), "initial\n").unwrap();
        }
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        for i in 0..6 {
            std::fs::write(repo.join(format!("file{i}.txt")), format!("modified {i}\n")).unwrap();
        }

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert_eq!(result.files.len(), 6, "should detect all 6 changed files");
        assert!(!result.base_identifier.is_empty());
    }

    #[test]
    fn test_jj_rev_metadata_no_snapshot_with_bookmark() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["bookmark", "set", "test-bm", "-r", "@-"]).current_dir(repo).output().unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let (change_id, label) = vcs.rev_metadata_no_snapshot("@-");

        assert!(!change_id.is_empty());
        assert!(label.contains("(test-bm)"),
            "label should contain bookmark in parens, got: {label}");
        assert!(label.ends_with(')'),
            "label should end with ), got: {label}");
    }

    #[test]
    fn test_jj_rev_metadata_no_snapshot_without_bookmark() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();

        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let (change_id, label) = vcs.rev_metadata_no_snapshot("@-");

        assert!(!change_id.is_empty());
        assert!(change_id.starts_with(&label),
            "without bookmark, label should be shortest prefix of change_id: label={label}, id={change_id}");
        assert!(label.len() >= 4, "shortest ID should be at least 4 chars, got: {label}");
    }

    // === resolve_base_rev tests ===

    #[test]
    fn test_resolve_base_rev_fallback_without_remote() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();
        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();

        let rev = resolve_base_rev(repo);
        assert_eq!(rev, "@-", "should fall back to @- when no remote tracking bookmarks");
    }

    #[test]
    fn test_resolve_base_rev_uses_trunk_with_remote() {
        if !jj_available() { return; }

        // Create a bare git repo as the "remote"
        let remote_dir = tempfile::TempDir::new().unwrap();
        Command::new("git").args(["init", "--bare"]).current_dir(remote_dir.path()).output().unwrap();

        // Create a jj repo and add the remote
        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();
        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "initial"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["bookmark", "set", "main", "-r", "@-"]).current_dir(repo).output().unwrap();
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        Command::new("jj").args(["git", "remote", "add", "origin", &remote_path]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["git", "push", "--bookmark", "main"]).current_dir(repo).output().unwrap();

        let rev = resolve_base_rev(repo);
        assert_eq!(rev, "trunk()", "should use trunk() when remote tracking bookmarks exist");
    }

    // === Stack coloring tests ===

    /// Helper: create a jj repo with a remote "origin" and push main.
    /// Returns (repo_tempdir, remote_tempdir) — keep both alive.
    fn setup_repo_with_remote() -> (tempfile::TempDir, tempfile::TempDir) {
        let remote_dir = tempfile::TempDir::new().unwrap();
        Command::new("git").args(["init", "--bare"]).current_dir(remote_dir.path()).output().unwrap();

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();
        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("base.txt"), "trunk content\n").unwrap();
        Command::new("jj").args(["commit", "-m", "base"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["bookmark", "set", "main", "-r", "@-"]).current_dir(repo).output().unwrap();
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        Command::new("jj").args(["git", "remote", "add", "origin", &remote_path]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["git", "push", "--bookmark", "main"]).current_dir(repo).output().unwrap();

        (temp, remote_dir)
    }

    #[test]
    fn test_jj_stack_coloring_two_commits() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // First stack commit: add a file
        std::fs::write(repo.join("stack.txt"), "from earlier commit\n").unwrap();
        Command::new("jj").args(["commit", "-m", "stack commit 1"]).current_dir(repo).output().unwrap();

        // Current commit (@): modify the file
        std::fs::write(repo.join("stack.txt"), "from earlier commit\nfrom current commit\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        assert_eq!(vcs.from_rev, "trunk()");

        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        let has_committed = result.lines.iter().any(|l| l.source == LineSource::Committed);
        let has_staged = result.lines.iter().any(|l| l.source == LineSource::Staged);
        assert!(has_committed, "earlier stack commit lines should be Committed (teal)");
        assert!(has_staged, "current commit lines should be Staged (green)");
    }

    #[test]
    fn test_jj_single_commit_above_trunk_all_staged() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Only one commit above trunk — everything should be Staged
        std::fs::write(repo.join("feature.txt"), "new feature\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        assert_eq!(vcs.from_rev, "trunk()");

        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert!(!result.files.is_empty(), "should detect the new file");
        let has_staged = result.lines.iter().any(|l| l.source == LineSource::Staged);
        let has_committed = result.lines.iter().any(|l| l.source == LineSource::Committed);
        assert!(has_staged, "single commit above trunk: all additions should be Staged");
        assert!(!has_committed, "single commit above trunk: no lines should be Committed");
    }

    // === Stack tip resolution tests ===

    #[test]
    fn test_resolve_stack_tip_at_tip() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // @ is the tip — one commit above trunk, nothing above @
        std::fs::write(repo.join("feature.txt"), "content\n").unwrap();

        let tip = resolve_stack_tip(repo, "trunk()");
        assert!(tip.is_none(), "should return None when @ is already the tip");
    }

    #[test]
    fn test_resolve_stack_tip_mid_stack() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Build 3-commit stack: commit1 → commit2 → commit3 (tip)
        std::fs::write(repo.join("file.txt"), "commit1\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit1"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "commit2\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit2"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "commit3\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit3"]).current_dir(repo).output().unwrap();

        // Move @ back to commit2 (mid-stack)
        Command::new("jj").args(["edit", "@---"]).current_dir(repo).output().unwrap();

        let tip = resolve_stack_tip(repo, "trunk()");
        assert!(tip.is_some(), "should return a tip when @ is mid-stack");
        let tip = tip.unwrap();
        assert_eq!(tip.head_count, 1, "linear stack should have 1 head");
        assert!(!tip.change_id.is_empty());
    }

    #[test]
    fn test_resolve_stack_tip_without_trunk() {
        if !jj_available() { return; }

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();
        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();

        let tip = resolve_stack_tip(repo, "@-");
        assert!(tip.is_none(), "should return None when from_rev is not trunk()");
    }

    #[test]
    fn test_resolve_stack_tip_branching() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Linear base: commit1
        std::fs::write(repo.join("file.txt"), "commit1\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit1"]).current_dir(repo).output().unwrap();

        // Branch: create commit2a on one branch
        std::fs::write(repo.join("branch_a.txt"), "branch a\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit2a"]).current_dir(repo).output().unwrap();

        // Go back to commit1 and create commit2b (a second head)
        // After commit2a: @=empty, @-=commit2a, @--=commit1
        Command::new("jj").args(["edit", "@--"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["new"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("branch_b.txt"), "branch b\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit2b"]).current_dir(repo).output().unwrap();

        // Move @ to commit1 (below the fork)
        // After commit2b: @=empty, @-=commit2b, @--=commit1
        Command::new("jj").args(["edit", "@--"]).current_dir(repo).output().unwrap();

        let tip = resolve_stack_tip(repo, "trunk()");
        assert!(tip.is_some(), "should detect stack tip when @ is below a fork");
        let tip = tip.unwrap();
        assert_eq!(tip.head_count, 2, "branching stack should have 2 heads");
    }

    #[test]
    fn test_stack_position_mid_stack() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Build 3-commit stack
        std::fs::write(repo.join("file.txt"), "commit1\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit1"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "commit2\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit2"]).current_dir(repo).output().unwrap();
        std::fs::write(repo.join("file.txt"), "commit3\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit3"]).current_dir(repo).output().unwrap();

        // Move @ to commit2 (position 2 of 3 mutable commits, plus the empty @)
        Command::new("jj").args(["edit", "@---"]).current_dir(repo).output().unwrap();

        let tip = resolve_stack_tip(repo, "trunk()").expect("should have a tip");
        let (current, total) = compute_stack_position(repo, &tip.change_id)
            .expect("should compute position");

        assert!(current >= 1 && current <= total,
            "current ({current}) should be within 1..={total}");
        assert!(total >= 3, "total ({total}) should be at least 3 commits");
    }

    #[test]
    fn test_jj_midstack_coloring() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Commit 1: add file
        std::fs::write(repo.join("file.txt"), "line1\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit1"]).current_dir(repo).output().unwrap();

        // Commit 2: modify file
        std::fs::write(repo.join("file.txt"), "line1\nline2\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit2"]).current_dir(repo).output().unwrap();

        // Commit 3: modify file further
        std::fs::write(repo.join("file.txt"), "line1\nline2\nline3\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit3"]).current_dir(repo).output().unwrap();

        // Move @ to commit2 (mid-stack): @=empty, @-=commit3, @--=commit2
        Command::new("jj").args(["edit", "@--"]).current_dir(repo).output().unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        let has_committed = result.lines.iter().any(|l| l.source == LineSource::Committed);
        let has_staged = result.lines.iter().any(|l| l.source == LineSource::Staged);
        let has_unstaged = result.lines.iter().any(|l| l.source == LineSource::Unstaged);

        assert!(has_committed, "earlier stack commits should produce Committed (teal)");
        assert!(has_staged, "current commit should produce Staged (green)");
        assert!(has_unstaged, "later stack commits should produce Unstaged (yellow)");

        assert!(result.stack_position.is_some(), "mid-stack should have stack_position");
        let pos = result.stack_position.unwrap();
        assert_eq!(pos.head_count, 1, "linear stack should have 1 head");
    }

    #[test]
    fn test_jj_midstack_later_only_file() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Commit 1: add base file
        std::fs::write(repo.join("base.txt"), "base stuff\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit1"]).current_dir(repo).output().unwrap();

        // Commit 2 (will be @): add something
        std::fs::write(repo.join("current.txt"), "current\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit2"]).current_dir(repo).output().unwrap();

        // Commit 3: add a file only in the later commit
        std::fs::write(repo.join("later.txt"), "later only\n").unwrap();
        Command::new("jj").args(["commit", "-m", "commit3"]).current_dir(repo).output().unwrap();

        // Move @ to commit2
        Command::new("jj").args(["edit", "@---"]).current_dir(repo).output().unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        // later.txt should appear with Unstaged lines (only changed above @)
        let later_file = result.files.iter().find(|f| {
            f.lines.first().is_some_and(|l| l.content.contains("later.txt"))
        });
        assert!(later_file.is_some(), "later.txt should be in diff (file only in later commit)");

        let later_lines: Vec<_> = later_file.unwrap().lines.iter()
            .filter(|l| l.source == LineSource::Unstaged)
            .collect();
        assert!(!later_lines.is_empty(),
            "later.txt content should be Unstaged (only changed in later commit)");
    }

    #[test]
    fn test_jj_at_tip_no_stack_position() {
        if !jj_available() { return; }

        let (temp, _remote) = setup_repo_with_remote();
        let repo = temp.path();

        // Single commit above trunk — @ is at the tip
        std::fs::write(repo.join("feature.txt"), "content\n").unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert!(result.stack_position.is_none(),
            "stack_position should be None when @ is at the tip");
    }

    #[test]
    fn test_jj_trunk_deletion_coloring() {
        if !jj_available() { return; }

        let remote_dir = tempfile::TempDir::new().unwrap();
        Command::new("git").args(["init", "--bare"]).current_dir(remote_dir.path()).output().unwrap();

        let temp = tempfile::TempDir::new().unwrap();
        let repo = temp.path();
        Command::new("jj").args(["git", "init"]).current_dir(repo).output().unwrap();

        // File exists at trunk
        std::fs::write(repo.join("doomed.txt"), "will be deleted\n").unwrap();
        Command::new("jj").args(["commit", "-m", "base"]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["bookmark", "set", "main", "-r", "@-"]).current_dir(repo).output().unwrap();
        let remote_path = remote_dir.path().to_string_lossy().to_string();
        Command::new("jj").args(["git", "remote", "add", "origin", &remote_path]).current_dir(repo).output().unwrap();
        Command::new("jj").args(["git", "push", "--bookmark", "main"]).current_dir(repo).output().unwrap();

        // Current commit (@): delete the file
        std::fs::remove_file(repo.join("doomed.txt")).unwrap();

        let vcs = JjVcs::new(repo.to_path_buf()).unwrap();
        assert_eq!(vcs.from_rev, "trunk()");

        let cancel = Arc::new(AtomicBool::new(false));
        let result = vcs.refresh(&cancel).unwrap();

        assert!(!result.files.is_empty(), "should detect deleted file");
        let header = &result.lines[0];
        assert!(header.content.contains("(deleted)"),
            "deleted file should have deletion header, got: {}", header.content);
        let has_deleted = result.lines.iter().any(|l| l.source == LineSource::DeletedCommitted);
        assert!(has_deleted, "file deleted in current commit should have DeletedCommitted source");
    }

    // === parse_rev_metadata unit tests ===

    #[test]
    fn test_parse_rev_metadata_bookmark_with_shortest_id() {
        let (id, label) = parse_rev_metadata("main\0knmqypts1234\0knmq");
        assert_eq!(id, "knmqypts1234");
        assert_eq!(label, "knmq (main)");
    }

    #[test]
    fn test_parse_rev_metadata_no_bookmark() {
        let (id, label) = parse_rev_metadata("\0knmqypts1234\0knmq");
        assert_eq!(id, "knmqypts1234");
        assert_eq!(label, "knmq", "no bookmark → shortest change_id");
    }

    #[test]
    fn test_parse_rev_metadata_tracking_marker_with_shortest_id() {
        let (id, label) = parse_rev_metadata("feat*\0abcd1234efgh\0abcd");
        assert_eq!(id, "abcd1234efgh");
        assert_eq!(label, "abcd (feat)");
    }

    #[test]
    fn test_parse_rev_metadata_two_field_fallback() {
        let (id, label) = parse_rev_metadata("main\0knmqypts1234");
        assert_eq!(id, "knmqypts1234");
        assert_eq!(label, "main", "2-field format falls back to bookmark only");
    }

    #[test]
    fn test_parse_rev_metadata_multiple_bookmarks() {
        let (id, label) = parse_rev_metadata("b1 b2\0xvryypywztmm\0xvry");
        assert_eq!(id, "xvryypywztmm");
        assert_eq!(label, "xvry (b1 b2)");
    }

    #[test]
    fn test_parse_rev_metadata_no_delimiter() {
        let (id, label) = parse_rev_metadata("rawvalue");
        assert_eq!(id, "rawvalue");
        assert_eq!(label, "rawvalue");
    }

    // === mark_bookmark_provenance tests ===

    fn make_file_diff(lines: Vec<crate::diff::DiffLine>) -> crate::diff::FileDiff {
        crate::diff::FileDiff::new(lines)
    }

    #[test]
    fn test_mark_bookmark_provenance_file_in_bookmark() {
        let lines = vec![
            crate::diff::DiffLine::new(LineSource::Committed, "added".to_string(), '+', None),
            crate::diff::DiffLine::new(LineSource::DeletedBase, "removed".to_string(), '-', None),
            crate::diff::DiffLine::new(LineSource::Staged, "staged".to_string(), '+', None),
            crate::diff::DiffLine::new(LineSource::Base, "context".to_string(), ' ', None),
        ];
        let mut fd = make_file_diff(lines);

        mark_bookmark_provenance(&mut fd, true);

        assert_eq!(fd.lines[0].in_current_bookmark, Some(true),
            "Committed lines in a bookmark file should be marked true");
        assert_eq!(fd.lines[1].in_current_bookmark, Some(true),
            "DeletedBase lines in a bookmark file should be marked true");
        assert_eq!(fd.lines[2].in_current_bookmark, Some(true),
            "Staged lines in a bookmark file should be marked true");
        assert_eq!(fd.lines[3].in_current_bookmark, Some(false),
            "Base context lines are never in current bookmark");
    }

    #[test]
    fn test_mark_bookmark_provenance_file_not_in_bookmark() {
        let lines = vec![
            crate::diff::DiffLine::new(LineSource::Committed, "added".to_string(), '+', None),
            crate::diff::DiffLine::new(LineSource::DeletedBase, "removed".to_string(), '-', None),
            crate::diff::DiffLine::new(LineSource::Staged, "staged".to_string(), '+', None),
            crate::diff::DiffLine::new(LineSource::Base, "context".to_string(), ' ', None),
        ];
        let mut fd = make_file_diff(lines);

        mark_bookmark_provenance(&mut fd, false);

        assert_eq!(fd.lines[0].in_current_bookmark, Some(false),
            "Committed lines NOT in bookmark file should be marked false");
        assert_eq!(fd.lines[1].in_current_bookmark, Some(false),
            "DeletedBase lines NOT in bookmark file should be marked false");
        assert_eq!(fd.lines[2].in_current_bookmark, Some(false),
            "Staged lines NOT in bookmark file should be marked false");
        assert_eq!(fd.lines[3].in_current_bookmark, Some(false),
            "Base context lines are never in current bookmark");
    }

    #[test]
    fn test_mark_bookmark_provenance_base_with_change_source() {
        let mut line = crate::diff::DiffLine::new(LineSource::Base, "modified".to_string(), ' ', None);
        line.change_source = Some(LineSource::Committed);
        let mut fd = make_file_diff(vec![line]);

        mark_bookmark_provenance(&mut fd, true);
        assert_eq!(fd.lines[0].in_current_bookmark, Some(true),
            "Base with change_source in bookmark file should be marked true");

        let mut line2 = crate::diff::DiffLine::new(LineSource::Base, "modified".to_string(), ' ', None);
        line2.change_source = Some(LineSource::Committed);
        let mut fd2 = make_file_diff(vec![line2]);

        mark_bookmark_provenance(&mut fd2, false);
        assert_eq!(fd2.lines[0].in_current_bookmark, Some(false),
            "Base with change_source NOT in bookmark file should be marked false");
    }

    /// Verify the boundary revset format includes remote_bookmarks() so that
    /// stacks with only remote-tracking bookmarks for pushed segments are handled.
    #[test]
    fn test_boundary_revset_includes_remote_bookmarks() {
        let change_id = "abc123def456";
        let revset = format!(
            "latest((trunk()..\"{}\"-) & (bookmarks() | remote_bookmarks()))",
            change_id
        );
        assert!(revset.contains("remote_bookmarks()"),
            "Boundary revset must include remote_bookmarks() for pushed bookmark segments");
        assert!(revset.contains(&format!("\"{}\"", change_id)),
            "Boundary revset must reference the current bookmark's change ID");
    }
}