vcs-jj 0.5.0

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

use std::future::Future;
use std::path::{Path, PathBuf};
use std::time::Duration;

use processkit::ProcessRunner;
// Re-export the processkit types in this crate's public API (also brings
// `Error`/`Result`/`ProcessResult` into scope here).
pub use processkit::{Error, ProcessResult, Result};
// Re-exported under the `cancellation` feature so a consumer can name the token
// for `default_cancel_on` without taking a direct `processkit` dependency.
#[cfg(feature = "cancellation")]
#[cfg_attr(docsrs, doc(cfg(feature = "cancellation")))]
pub use processkit::CancellationToken;

pub mod conflict;
mod parse;
pub use parse::{AnnotationLine, Bookmark, BookmarkRef, Change, ChangedPath, Operation, Workspace};
// The git-format diff model + parser and the version type are shared with
// `vcs-git` (identical output) — re-exported so `vcs_jj::FileDiff`,
// `vcs_jj::parse_diff`, `vcs_jj::JjVersion`, … still resolve.
pub use vcs_diff::{
    ChangeKind, DiffLine, DiffStat, FileDiff, Hunk, Version as JjVersion, parse_diff,
};
// The transient-fetch classifier lives in the shared plumbing crate — re-exported
// so `vcs_jj::is_transient_fetch_error` still resolves.
pub use vcs_cli_support::is_transient_fetch_error;

/// Name of the underlying CLI binary this crate drives.
pub const BINARY: &str = "jj";

/// What a [`JjApi::diff`] / [`JjApi::diff_text`] call compares.
///
/// `#[non_exhaustive]` so more comparison shapes can be added later.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DiffSpec {
    /// The working-copy change's diff (`jj diff -r @`).
    WorkingTree,
    /// A specific revset, e.g. `@-` or `main..@` (`jj diff -r <revset>`).
    Rev(String),
}

/// How a new workspace inherits sparse patterns (`jj workspace add
/// --sparse-patterns <mode>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SparseMode {
    /// Copy all sparse patterns from the current workspace (jj's default).
    Copy,
    /// Include every file in the new workspace.
    Full,
    /// Start with no files — the caller sets patterns afterwards (CoW flow).
    Empty,
}

impl SparseMode {
    /// The `--sparse-patterns` value jj expects.
    fn as_arg(self) -> &'static str {
        match self {
            SparseMode::Copy => "copy",
            SparseMode::Full => "full",
            SparseMode::Empty => "empty",
        }
    }
}

/// An exact-path jj fileset (`file:"<path>"`), so path metacharacters like `(`,
/// `)`, `|`, `*` are treated literally rather than as fileset operators.
///
/// Build it with [`JjFileset::path`]; the path is repo-root-relative.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JjFileset(String);

impl JjFileset {
    /// Wrap a repo-relative `path` as an exact-path fileset. Backslash separators
    /// are normalised to `/` first — jj filesets are forward-slash and
    /// repo-root-relative, so a Windows caller's `src\a.rs` would otherwise become
    /// a literal-backslash filename that matches nothing — then `"` is escaped for
    /// the `file:"…"` string literal.
    pub fn path(path: impl AsRef<str>) -> Self {
        let escaped = path.as_ref().replace('\\', "/").replace('"', "\\\"");
        JjFileset(format!("file:\"{escaped}\""))
    }

    /// The rendered `file:"…"` expression.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Options for [`JjApi::workspace_add`] (`jj workspace add`).
///
/// `#[non_exhaustive]`, so build it through [`WorkspaceAdd::new`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct WorkspaceAdd {
    /// Name for the new workspace.
    pub name: String,
    /// Revision the workspace's working copy starts at (`-r <base>`).
    pub base: String,
    /// Filesystem path for the new workspace.
    pub path: PathBuf,
    /// How to seed the new workspace's sparse patterns (`--sparse-patterns`);
    /// `None` leaves jj's default (inherit from the current workspace).
    pub sparse_patterns: Option<SparseMode>,
}

impl WorkspaceAdd {
    /// A workspace named `name`, based at `base`, materialised at `path`.
    pub fn new(name: impl Into<String>, base: impl Into<String>, path: impl Into<PathBuf>) -> Self {
        Self {
            name: name.into(),
            base: base.into(),
            path: path.into(),
            sparse_patterns: None,
        }
    }

    /// Seed the new workspace's sparse patterns with `mode` (`--sparse-patterns`).
    pub fn sparse(mut self, mode: SparseMode) -> Self {
        self.sparse_patterns = Some(mode);
        self
    }
}

/// Options for [`JjApi::squash_paths`] (`jj squash --from <from> --into <into>
/// [--use-destination-message] <filesets>`).
///
/// `#[non_exhaustive]`, so build it through [`SquashPaths::new`] and the chained
/// setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SquashPaths {
    /// Source revision the filesets are squashed out of (`--from`).
    pub from: String,
    /// Destination revision the filesets are squashed into (`--into`).
    pub into: String,
    /// The exact filesets to move; empty squashes the whole `from` change.
    pub filesets: Vec<JjFileset>,
    /// Keep the destination's description rather than combining the two
    /// (`--use-destination-message`).
    pub use_destination_message: bool,
}

impl SquashPaths {
    /// Squash from `from` into `into`, with no filesets selected yet.
    pub fn new(from: impl Into<String>, into: impl Into<String>) -> Self {
        Self {
            from: from.into(),
            into: into.into(),
            filesets: Vec::new(),
            use_destination_message: false,
        }
    }

    /// Set the filesets to move (replacing any already added).
    pub fn filesets(mut self, filesets: impl IntoIterator<Item = JjFileset>) -> Self {
        self.filesets = filesets.into_iter().collect();
        self
    }

    /// Keep the destination's description (`--use-destination-message`) instead
    /// of combining the two.
    pub fn use_destination_message(mut self) -> Self {
        self.use_destination_message = true;
        self
    }
}

/// The first bookmark name from a comma-joined [`BOOKMARKS_TEMPLATE`](parse::BOOKMARKS_TEMPLATE)
/// render; `None` when the commit carries no local bookmark.
fn first_bookmark(rendered: &str) -> Option<String> {
    let rendered = rendered.trim();
    (!rendered.is_empty()).then(|| rendered.split(',').next().unwrap_or(rendered).to_string())
}

/// Injection guard for bare positional argv slots: a caller-supplied value
/// with a leading `-` is parsed by jj's CLI as a *flag* (verified: `jj edit
/// -evil` → "unexpected argument"), and an empty value changes a command's
/// meaning. Refuse both before anything spawns. Flag-VALUE positions
/// (`-r <revset>`, `-m <msg>`) need no guard — jj itself rejects dash-values
/// there with a clear error rather than misparsing them.
fn reject_flag_like(what: &str, value: &str) -> Result<()> {
    vcs_cli_support::reject_flag_like(BINARY, what, value)
}

/// A pre-validated revset expression, for callers that accept revsets from
/// untrusted input (UIs, bots, agents) and want to fail early. Deliberately
/// *minimal* — jj's revset grammar is too rich to validate here — it only
/// guarantees the expression is non-empty and cannot be parsed as a flag
/// (no leading `-`), matching the internal guard the positional-revset
/// methods apply anyway. The dir-taking methods stay `&str`; this type is
/// **optional** up-front validation, not a required wrapper.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RevsetExpr(String);

impl RevsetExpr {
    /// Validate `revset` (non-empty, no leading `-`).
    pub fn new(revset: impl Into<String>) -> Result<Self> {
        let revset = revset.into();
        reject_flag_like("revset", &revset)?;
        Ok(RevsetExpr(revset))
    }

    /// The validated expression.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for RevsetExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// What the installed `jj` binary supports, probed via
/// [`JjApi::capabilities`]. A value type — the client holds no state, so probe
/// once and keep the result (callers cache it).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct JjCapabilities {
    /// The binary's parsed version.
    pub version: JjVersion,
}

/// The validated jj floor: every parser and flag in this crate was verified
/// empirically against this release. jj's CLI moves fast, so unlike vcs-git's
/// major-only gate the jj floor is precise.
const MIN_SUPPORTED: JjVersion = JjVersion {
    major: 0,
    minor: 38,
    patch: 0,
};

impl JjCapabilities {
    /// Whether the binary meets the validated floor (jj ≥ 0.38).
    pub fn is_supported(&self) -> bool {
        self.version >= MIN_SUPPORTED
    }

    /// Error unless [`is_supported`](Self::is_supported) — a clear "needs jj
    /// ≥ 0.38, found 0.35.0" instead of a cryptic argv/template failure later.
    pub fn ensure_supported(&self) -> Result<()> {
        if self.is_supported() {
            return Ok(());
        }
        Err(Error::Spawn {
            program: BINARY.to_string(),
            source: std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                format!(
                    "vcs-jj requires jj >= {MIN_SUPPORTED} (the validated floor), found {}",
                    self.version
                ),
            ),
        })
    }
}

/// The jj operations this crate exposes — the interface consumers code against
/// and mock in tests.
///
/// **Injection safety:** every method that places a caller-supplied bookmark
/// name, revset, or operation id in a positional argv slot rejects a value
/// that is empty or begins with `-` (jj would parse it as a flag) with an
/// [`Error::Spawn`] *before* spawning. Flag-value slots (`-r <revset>`,
/// `-m <msg>`) and the `run`/`run_raw` escape hatches are not guarded. For
/// eager validation at an input boundary, see [`RevsetExpr`].
#[cfg_attr(feature = "mock", mockall::automock)]
#[async_trait::async_trait]
pub trait JjApi: Send + Sync {
    /// Run `jj <args>`, returning trimmed stdout (throws on a non-zero exit).
    async fn run(&self, args: &[String]) -> Result<String>;
    /// Like [`JjApi::run`] but never errors on a non-zero exit — returns the
    /// captured [`ProcessResult`].
    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>>;
    /// Installed Jujutsu version (`jj --version`).
    async fn version(&self) -> Result<String>;
    /// The installed binary's parsed version, as [`JjCapabilities`]
    /// (`jj --version`). A value type — probe once and keep it; an
    /// unrecognisable version string is an [`Error::Parse`].
    async fn capabilities(&self) -> Result<JjCapabilities>;
    /// Parsed working-copy changes — the files changed in `@`
    /// (`jj diff -r @ --summary`), mirroring `vcs_git` `status`.
    async fn status(&self, dir: &Path) -> Result<Vec<ChangedPath>>;
    /// Raw `jj status` text (human-readable) — the unparsed counterpart of
    /// [`status`](JjApi::status), mirroring `vcs_git` `status_text`.
    async fn status_text(&self, dir: &Path) -> Result<String>;
    /// Changes matching `revset`, newest first, up to `max` (`jj log`).
    async fn log(&self, dir: &Path, revset: &str, max: usize) -> Result<Vec<Change>>;
    /// The working-copy change (`jj log -r @`).
    async fn current_change(&self, dir: &Path) -> Result<Change>;
    /// Set the working-copy change's description (`jj describe -m`).
    async fn describe(&self, dir: &Path, message: &str) -> Result<()>;
    /// Set the description of an arbitrary revision (`jj describe -r <revset> -m`).
    async fn describe_rev(&self, dir: &Path, revset: &str, message: &str) -> Result<()>;
    /// Start a new change on top of the working copy (`jj new -m`).
    async fn new_change(&self, dir: &Path, message: &str) -> Result<()>;
    /// Local bookmarks (`jj bookmark list`).
    async fn bookmarks(&self, dir: &Path) -> Result<Vec<Bookmark>>;
    /// Local *and* remote-tracking bookmarks (`jj bookmark list -a`).
    async fn bookmarks_all(&self, dir: &Path) -> Result<Vec<BookmarkRef>>;
    /// Local bookmarks on the nearest commits reachable from `@`
    /// (`log -r 'heads(::@ & bookmarks())'`) — the candidate targets a commit
    /// "belongs to". A commit carrying several bookmarks yields one entry each.
    async fn reachable_bookmarks(&self, dir: &Path) -> Result<Vec<Bookmark>>;
    /// Track a remote bookmark (`jj bookmark track <name>@<remote>`).
    async fn bookmark_track(&self, dir: &Path, name: &str, remote: &str) -> Result<()>;
    /// Point a bookmark at `revision` (`jj bookmark set <name> -r <revision>`).
    async fn bookmark_set(&self, dir: &Path, name: &str, revision: &str) -> Result<()>;
    /// Fetch from the git remote (`jj git fetch`); transient (network) failures
    /// are retried (3 attempts, 500 ms backoff).
    async fn git_fetch(&self, dir: &Path) -> Result<()>;
    /// Fetch from a *named* git remote (`jj git fetch --remote <remote>`);
    /// transient failures are retried like [`git_fetch`](JjApi::git_fetch).
    async fn git_fetch_from(&self, dir: &Path, remote: &str) -> Result<()>;
    /// Push to the git remote (`jj git push`, optionally `-b <bookmark>`). The
    /// bookmark is owned (`Option<String>`) to keep the trait `mockall`-friendly.
    async fn git_push(&self, dir: &Path, bookmark: Option<String>) -> Result<()>;

    // --- Discovery / identity ------------------------------------------------

    /// Working-copy root of the current workspace (`jj root`).
    async fn root(&self, dir: &Path) -> Result<PathBuf>;
    /// The local bookmark on the working-copy change `@`, if exactly one (or the
    /// first of several); `None` when `@` carries no bookmark. `ws` enforces the
    /// one-bookmark policy on top.
    async fn current_bookmark(&self, dir: &Path) -> Result<Option<String>>;
    /// The trunk bookmark (`jj log -r 'trunk()'`); `None` when unresolved.
    async fn trunk(&self, dir: &Path) -> Result<Option<String>>;

    // --- Bookmarks -----------------------------------------------------------

    /// Create a bookmark at a revision (`bookmark create <name> -r <rev>`).
    async fn bookmark_create(&self, dir: &Path, name: &str, revision: &str) -> Result<()>;
    /// Rename a bookmark (`bookmark rename <old> <new>`).
    async fn bookmark_rename(&self, dir: &Path, old: &str, new: &str) -> Result<()>;
    /// Delete a bookmark (`bookmark delete <name>`).
    async fn bookmark_delete(&self, dir: &Path, name: &str) -> Result<()>;
    /// Move a bookmark to a revision (`bookmark move <name> --to <rev>
    /// [--allow-backwards]`).
    async fn bookmark_move(
        &self,
        dir: &Path,
        name: &str,
        to: &str,
        allow_backwards: bool,
    ) -> Result<()>;

    // --- Diff / query / state ------------------------------------------------

    /// Per-file change summary for a range (`diff -r <from>..<to> --summary`).
    async fn diff_summary(&self, dir: &Path, from: &str, to: &str) -> Result<Vec<ChangedPath>>;
    /// Aggregate change stats for a revset (`diff -r <revset> --stat`).
    async fn diff_stat(&self, dir: &Path, revset: &str) -> Result<DiffStat>;
    /// Raw git-format unified diff text for `spec` (`diff -r <spec> --git`) —
    /// stable machine output.
    async fn diff_text(&self, dir: &Path, spec: DiffSpec) -> Result<String>;
    /// Parsed per-file unified diff for `spec`, layered on [`diff_text`](JjApi::diff_text).
    async fn diff(&self, dir: &Path, spec: DiffSpec) -> Result<Vec<FileDiff>>;
    /// Count commits in a revset (`log -r <revset> --no-graph`, one id per line).
    async fn commit_count(&self, dir: &Path, revset: &str) -> Result<usize>;
    /// Whether the commit a revset resolves to has a conflict.
    async fn is_conflicted(&self, dir: &Path, revset: &str) -> Result<bool>;
    /// Whether the working copy has unresolved conflicts (`jj status`).
    async fn has_workingcopy_conflict(&self, dir: &Path) -> Result<bool>;
    /// Paths with unresolved conflicts in `revset` (`jj resolve --list -r <revset>`).
    /// Empty when there are none.
    async fn resolve_list(&self, dir: &Path, revset: &str) -> Result<Vec<String>>;
    /// Run an arbitrary templated `jj log` query and return raw stdout
    /// (`log -r <revset> --no-graph [--limit n] -T <template>`).
    async fn template_query(
        &self,
        dir: &Path,
        revset: &str,
        template: &str,
        limit: Option<usize>,
    ) -> Result<String>;
    /// The full (possibly multiline) description of the commit `revset` resolves
    /// to, trailing whitespace trimmed; empty for an undescribed change — or for
    /// a revset matching no commit (an *invalid* revset still errors). A
    /// multi-commit revset yields only the newest commit's description
    /// (`jj log` order, `--limit 1`).
    async fn description(&self, dir: &Path, revset: &str) -> Result<String>;
    /// How the commit a revset resolves to evolved, newest snapshot first, up
    /// to `max` (`jj evolog -r <revset>`) — one [`Change`] row per recorded
    /// predecessor.
    async fn evolog(&self, dir: &Path, revset: &str, max: usize) -> Result<Vec<Change>>;
    /// Per-line authorship of `path` (`jj file annotate <path> [-r <revset>]`;
    /// `None` = `@`): which change introduced each line.
    async fn file_annotate(
        &self,
        dir: &Path,
        path: &str,
        revset: Option<String>,
    ) -> Result<Vec<AnnotationLine>>;
    /// A file's content at a revision (`jj file show -r <revset>
    /// file:"<path>"` — the path is wrapped as an exact-path fileset, so
    /// fileset metacharacters in the name stay literal). Content is decoded
    /// lossily — a binary file comes back mangled rather than erroring.
    async fn file_show(&self, dir: &Path, revset: &str, path: &str) -> Result<String>;

    // --- Mutations -----------------------------------------------------------

    /// Rebase the working copy onto a destination (`rebase -d <onto>`).
    async fn rebase(&self, dir: &Path, onto: &str) -> Result<()>;
    /// Rebase a whole branch onto a destination (`rebase -b <branch> -d <dest>`).
    async fn rebase_branch(&self, dir: &Path, branch: &str, dest: &str) -> Result<()>;
    /// Move the working copy to a revision (`edit <rev>`).
    async fn edit(&self, dir: &Path, revset: &str) -> Result<()>;
    /// Squash the working copy into a revision (`squash --into <rev>`). When
    /// `use_destination_message`, keep the destination's description
    /// (`--use-destination-message`) instead of combining the two.
    async fn squash_into(
        &self,
        dir: &Path,
        into: &str,
        use_destination_message: bool,
    ) -> Result<()>;
    /// Finalise a commit from exactly these filesets (`commit -m <message>
    /// <filesets>`); the rest stay in the new working-copy change.
    async fn commit_paths(&self, dir: &Path, filesets: &[JjFileset], message: &str) -> Result<()>;
    /// Squash exactly these filesets from one revision into another
    /// (`squash --from <from> --into <into> [--use-destination-message] <filesets>`).
    async fn squash_paths(&self, dir: &Path, spec: SquashPaths) -> Result<()>;
    /// Set the working copy's sparse patterns to exactly `patterns`
    /// (`sparse set --clear --add <p>…`); an empty list clears the working copy.
    async fn sparse_set(&self, dir: &Path, patterns: &[String]) -> Result<()>;
    /// Create a new change with the given parents (`new -m <msg> <p1> <p2> …`).
    async fn new_merge(&self, dir: &Path, message: &str, parents: Vec<String>) -> Result<()>;
    /// Abandon a revision (`abandon <rev>`).
    async fn abandon(&self, dir: &Path, revset: &str) -> Result<()>;
    /// Fetch a single bookmark from origin (`git fetch --remote origin -b <branch>`);
    /// transient failures are retried (3×, 500 ms).
    async fn git_fetch_branch(&self, dir: &Path, branch: &str) -> Result<()>;
    /// Import git refs into jj (`jj git import`) — colocated-repo sync.
    async fn git_import(&self, dir: &Path) -> Result<()>;
    /// Clone a git repository into `dest` (`jj git clone <url> <dest>
    /// --colocate|--no-colocate`). Runs without a working directory — pass an
    /// **absolute** `dest`. The flag is always passed explicitly: whether
    /// colocation (a visible `.git` alongside `.jj`) is jj's default depends
    /// on the jj version *and* the user's `git.colocate` config, so `colocate`
    /// decides deterministically.
    async fn git_clone(&self, url: &str, dest: &Path, colocate: bool) -> Result<()>;
    /// Fold working-copy edits into the mutable ancestors that introduced the
    /// touched lines (`absorb [--from <revset>] [<filesets>…]`); empty
    /// `filesets` absorbs everything.
    async fn absorb(&self, dir: &Path, from: Option<String>, filesets: &[JjFileset]) -> Result<()>;
    /// Split exactly these filesets out of `@` into their own commit described
    /// by `message` (`split -m <message> <filesets>…`); the remainder stays
    /// behind. `filesets` must be non-empty — a fileset-less split opens jj's
    /// interactive diff editor (a headless hang), so it is refused with an
    /// error before spawning.
    async fn split_paths(&self, dir: &Path, filesets: &[JjFileset], message: &str) -> Result<()>;
    /// Duplicate the commits a revset resolves to (`duplicate <revset>`).
    async fn duplicate(&self, dir: &Path, revset: &str) -> Result<()>;

    // --- Operation log -------------------------------------------------------

    /// The current operation id (`op log --no-graph --limit 1`) — capture before
    /// a risky sequence to roll back to.
    async fn op_head(&self, dir: &Path) -> Result<String>;
    /// The newest `limit` operations, newest first (`op log --no-graph
    /// --limit n`).
    async fn op_log(&self, dir: &Path, limit: usize) -> Result<Vec<Operation>>;
    /// Restore the repo to an operation (`op restore <id>`).
    async fn op_restore(&self, dir: &Path, op_id: &str) -> Result<()>;
    /// Undo the latest operation (`op undo`).
    async fn op_undo(&self, dir: &Path) -> Result<()>;

    // --- Workspaces ----------------------------------------------------------

    /// List workspaces (`workspace list`).
    async fn workspace_list(&self, dir: &Path) -> Result<Vec<Workspace>>;
    /// Resolve a workspace's root path (`workspace root [--name <name>]`).
    async fn workspace_root(&self, dir: &Path, name: Option<String>) -> Result<PathBuf>;
    /// Add a workspace (`workspace add --name <name> -r <base> <path>`).
    async fn workspace_add(&self, dir: &Path, spec: WorkspaceAdd) -> Result<()>;
    /// Forget a workspace (`workspace forget <name>`).
    async fn workspace_forget(&self, dir: &Path, name: &str) -> Result<()>;
}

processkit::cli_client!(
    /// The real jj client. Generic over the [`ProcessRunner`] so tests can inject
    /// a fake process executor; `Jj::new()` uses the real job-backed runner.
    pub struct Jj => BINARY
);

impl<R: ProcessRunner> Jj<R> {
    /// A repo-scoped `jj` command with `--color never` forced on. jj honours
    /// `ui.color = "always"` from user config even when its output is piped, which
    /// would wrap our templated output — and the command error text we classify —
    /// in ANSI escapes and break parsing; `--color never` is the only thing that
    /// overrides that config (`NO_COLOR`/`CLICOLOR` do not). It is a global flag,
    /// appended here (no jj subcommand takes a trailing `--`, so this is safe).
    fn cmd_in<I, S>(&self, dir: &Path, args: I) -> processkit::Command
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        self.core.command_in(dir, args).arg("--color").arg("never")
    }
}

#[async_trait::async_trait]
impl<R: ProcessRunner> JjApi for Jj<R> {
    async fn run(&self, args: &[String]) -> Result<String> {
        self.core.run(self.core.command(args)).await
    }

    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>> {
        self.core.output(self.core.command(args)).await
    }

    async fn version(&self) -> Result<String> {
        self.core.run(self.core.command(["--version"])).await
    }

    async fn capabilities(&self) -> Result<JjCapabilities> {
        let raw = self.version().await?;
        let version = parse::parse_jj_version(&raw).ok_or_else(|| Error::Parse {
            program: BINARY.to_string(),
            message: format!("unrecognisable `jj --version` output: {raw:?}"),
        })?;
        Ok(JjCapabilities { version })
    }

    async fn status(&self, dir: &Path) -> Result<Vec<ChangedPath>> {
        // `diff -r @ --summary` is the machine-stable form of the working-copy
        // changes that `jj status` renders for humans: one `<letter> <path>` line.
        self.core
            .parse(
                self.cmd_in(dir, ["diff", "-r", "@", "--summary"]),
                parse::parse_diff_summary,
            )
            .await
    }

    async fn status_text(&self, dir: &Path) -> Result<String> {
        self.core.run(self.cmd_in(dir, ["status"])).await
    }

    async fn log(&self, dir: &Path, revset: &str, max: usize) -> Result<Vec<Change>> {
        let n = format!("-n{max}");
        self.core
            .parse(
                self.cmd_in(
                    dir,
                    [
                        "log",
                        "-r",
                        revset,
                        n.as_str(),
                        "--no-graph",
                        "-T",
                        parse::CHANGE_TEMPLATE,
                    ],
                ),
                parse::parse_changes,
            )
            .await
    }

    async fn current_change(&self, dir: &Path) -> Result<Change> {
        let mut changes = self.log(dir, "@", 1).await?;
        changes.pop().ok_or_else(|| Error::Parse {
            program: BINARY.to_string(),
            message: "no working-copy change found".to_string(),
        })
    }

    async fn describe(&self, dir: &Path, message: &str) -> Result<()> {
        self.core
            .run_unit(self.cmd_in(dir, ["describe", "-m", message]))
            .await
    }

    async fn describe_rev(&self, dir: &Path, revset: &str, message: &str) -> Result<()> {
        self.core
            .run_unit(self.cmd_in(dir, ["describe", "-r", revset, "-m", message]))
            .await
    }

    async fn new_change(&self, dir: &Path, message: &str) -> Result<()> {
        self.core
            .run_unit(self.cmd_in(dir, ["new", "-m", message]))
            .await
    }

    async fn bookmarks(&self, dir: &Path) -> Result<Vec<Bookmark>> {
        self.core
            .parse(
                self.cmd_in(dir, ["bookmark", "list"]),
                parse::parse_bookmarks,
            )
            .await
    }

    async fn bookmarks_all(&self, dir: &Path) -> Result<Vec<BookmarkRef>> {
        self.core
            .parse(
                self.cmd_in(
                    dir,
                    ["bookmark", "list", "-a", "-T", parse::BOOKMARK_ALL_TEMPLATE],
                ),
                parse::parse_bookmarks_all,
            )
            .await
    }

    async fn reachable_bookmarks(&self, dir: &Path) -> Result<Vec<Bookmark>> {
        self.core
            .parse(
                self.cmd_in(
                    dir,
                    [
                        "log",
                        "-r",
                        "heads(::@ & bookmarks())",
                        "--no-graph",
                        "-T",
                        parse::REACHABLE_BOOKMARKS_TEMPLATE,
                    ],
                ),
                parse::parse_reachable_bookmarks,
            )
            .await
    }

    async fn bookmark_track(&self, dir: &Path, name: &str, remote: &str) -> Result<()> {
        // A leading-`-` name makes the whole `{name}@{remote}` token start with
        // `-`, which jj parses as a global flag (e.g. `--config`); guard it.
        reject_flag_like("bookmark name", name)?;
        let target = format!("{name}@{remote}");
        self.core
            .run_unit(self.cmd_in(dir, ["bookmark", "track", target.as_str()]))
            .await
    }

    async fn bookmark_set(&self, dir: &Path, name: &str, revision: &str) -> Result<()> {
        reject_flag_like("bookmark name", name)?;
        self.core
            .run_unit(self.cmd_in(dir, ["bookmark", "set", name, "-r", revision]))
            .await
    }

    async fn git_fetch(&self, dir: &Path) -> Result<()> {
        // Idempotent → `retry` replays it on a transient (network) failure.
        let cmd = self.cmd_in(dir, ["git", "fetch"]).retry(
            FETCH_ATTEMPTS,
            FETCH_BACKOFF,
            is_transient_fetch_error,
        );
        self.core.run_unit(cmd).await
    }

    async fn git_fetch_from(&self, dir: &Path, remote: &str) -> Result<()> {
        // Idempotent → `retry` replays it on a transient (network) failure.
        let cmd = self
            .cmd_in(dir, ["git", "fetch", "--remote", remote])
            .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error);
        self.core.run_unit(cmd).await
    }

    async fn git_push(&self, dir: &Path, bookmark: Option<String>) -> Result<()> {
        let mut args = vec!["git", "push"];
        if let Some(name) = bookmark.as_deref() {
            args.push("-b");
            args.push(name);
        }
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn root(&self, dir: &Path) -> Result<PathBuf> {
        Ok(PathBuf::from(
            self.core.run(self.cmd_in(dir, ["root"])).await?,
        ))
    }

    async fn current_bookmark(&self, dir: &Path) -> Result<Option<String>> {
        let out = self
            .core
            .run(self.cmd_in(
                dir,
                [
                    "log",
                    "-r",
                    "@",
                    "--no-graph",
                    "--limit",
                    "1",
                    "-T",
                    parse::BOOKMARKS_TEMPLATE,
                ],
            ))
            .await?;
        Ok(first_bookmark(&out))
    }

    async fn trunk(&self, dir: &Path) -> Result<Option<String>> {
        let out = self
            .core
            .run(self.cmd_in(
                dir,
                [
                    "log",
                    "-r",
                    "trunk()",
                    "--no-graph",
                    "--limit",
                    "1",
                    "-T",
                    parse::BOOKMARKS_TEMPLATE,
                ],
            ))
            .await?;
        Ok(first_bookmark(&out))
    }

    async fn bookmark_create(&self, dir: &Path, name: &str, revision: &str) -> Result<()> {
        reject_flag_like("bookmark name", name)?;
        self.core
            .run_unit(self.cmd_in(dir, ["bookmark", "create", name, "-r", revision]))
            .await
    }

    async fn bookmark_rename(&self, dir: &Path, old: &str, new: &str) -> Result<()> {
        reject_flag_like("bookmark name", old)?;
        reject_flag_like("bookmark name", new)?;
        self.core
            .run_unit(self.cmd_in(dir, ["bookmark", "rename", old, new]))
            .await
    }

    async fn bookmark_delete(&self, dir: &Path, name: &str) -> Result<()> {
        reject_flag_like("bookmark name", name)?;
        self.core
            .run_unit(self.cmd_in(dir, ["bookmark", "delete", name]))
            .await
    }

    async fn bookmark_move(
        &self,
        dir: &Path,
        name: &str,
        to: &str,
        allow_backwards: bool,
    ) -> Result<()> {
        reject_flag_like("bookmark name", name)?;
        let mut args = vec!["bookmark", "move", name, "--to", to];
        if allow_backwards {
            args.push("--allow-backwards");
        }
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn diff_summary(&self, dir: &Path, from: &str, to: &str) -> Result<Vec<ChangedPath>> {
        // Parenthesise each endpoint so a compound revset (e.g. `x | y`) keeps its
        // meaning inside the `..` range instead of binding by operator precedence.
        let range = format!("({from})..({to})");
        self.core
            .parse(
                self.cmd_in(dir, ["diff", "-r", range.as_str(), "--summary"]),
                parse::parse_diff_summary,
            )
            .await
    }

    async fn diff_stat(&self, dir: &Path, revset: &str) -> Result<DiffStat> {
        self.core
            .parse(
                self.cmd_in(dir, ["diff", "-r", revset, "--stat"]),
                parse::parse_diff_stat,
            )
            .await
    }

    async fn diff_text(&self, dir: &Path, spec: DiffSpec) -> Result<String> {
        // `@` selects the working-copy change; otherwise the caller's revset.
        // `--git` emits stable git-format output the shared parser understands.
        let revset = match spec {
            DiffSpec::WorkingTree => "@".to_string(),
            DiffSpec::Rev(rev) => rev,
        };
        self.core
            .run(self.cmd_in(dir, ["diff", "-r", revset.as_str(), "--git"]))
            .await
    }

    async fn diff(&self, dir: &Path, spec: DiffSpec) -> Result<Vec<FileDiff>> {
        let text = self.diff_text(dir, spec).await?;
        Ok(parse_diff(&text))
    }

    async fn commit_count(&self, dir: &Path, revset: &str) -> Result<usize> {
        self.core
            .parse(
                self.cmd_in(
                    dir,
                    [
                        "log",
                        "-r",
                        revset,
                        "--no-graph",
                        "-T",
                        parse::COUNT_TEMPLATE,
                    ],
                ),
                |s| s.lines().filter(|line| !line.is_empty()).count(),
            )
            .await
    }

    async fn is_conflicted(&self, dir: &Path, revset: &str) -> Result<bool> {
        let out = self
            .core
            .run(self.cmd_in(
                dir,
                [
                    "log",
                    "-r",
                    revset,
                    "--no-graph",
                    "--limit",
                    "1",
                    "-T",
                    parse::CONFLICT_TEMPLATE,
                ],
            ))
            .await?;
        Ok(out.trim() == "1")
    }

    async fn has_workingcopy_conflict(&self, dir: &Path) -> Result<bool> {
        // Ask the template engine directly rather than string-matching localized
        // `jj status` prose: `@` is conflicted iff its `conflict` flag is set.
        self.is_conflicted(dir, "@").await
    }

    async fn resolve_list(&self, dir: &Path, revset: &str) -> Result<Vec<String>> {
        let res = self
            .core
            .output(self.cmd_in(dir, ["resolve", "--list", "-r", revset]))
            .await?;
        match res.code() {
            Some(0) => Ok(parse::parse_resolve_list(res.stdout())),
            // jj exits non-zero with "No conflicts found …" when the revision is
            // conflict-free — the one non-zero we read as an empty list. Any other
            // failure (bad revset, not a repo, …) must surface, not masquerade as
            // "no conflicts".
            _ if res.stderr().contains("No conflicts") => Ok(Vec::new()),
            _ => {
                res.ensure_success()?;
                Ok(Vec::new()) // unreachable: a non-zero exit always errors above.
            }
        }
    }

    async fn template_query(
        &self,
        dir: &Path,
        revset: &str,
        template: &str,
        limit: Option<usize>,
    ) -> Result<String> {
        let mut args: Vec<String> = vec![
            "log".into(),
            "-r".into(),
            revset.into(),
            "--no-graph".into(),
        ];
        if let Some(n) = limit {
            args.push("--limit".into());
            args.push(n.to_string());
        }
        args.push("-T".into());
        args.push(template.into());
        self.core.run(self.cmd_in(dir, args)).await
    }

    async fn description(&self, dir: &Path, revset: &str) -> Result<String> {
        self.template_query(dir, revset, "description", Some(1))
            .await
    }

    async fn evolog(&self, dir: &Path, revset: &str, max: usize) -> Result<Vec<Change>> {
        // Evolog templates render in a *commit* context (bare `change_id`
        // doesn't exist there) — EVOLOG_TEMPLATE uses the `commit.` method
        // form but emits the same columns CHANGE_TEMPLATE does.
        let limit = max.to_string();
        self.core
            .parse(
                self.cmd_in(
                    dir,
                    [
                        "evolog",
                        "-r",
                        revset,
                        "--no-graph",
                        "--limit",
                        limit.as_str(),
                        "-T",
                        parse::EVOLOG_TEMPLATE,
                    ],
                ),
                parse::parse_changes,
            )
            .await
    }

    async fn file_annotate(
        &self,
        dir: &Path,
        path: &str,
        revset: Option<String>,
    ) -> Result<Vec<AnnotationLine>> {
        // `file annotate` takes a plain PATH (not a fileset — the `file:"…"`
        // form is rejected), so a leading-`-` path would be parsed as a flag.
        // The `--` separator before it keeps even a `-dash.txt` literal safe —
        // but global flags (`--color never`) MUST precede `--`, so this builds
        // the command directly instead of via `cmd_in` (which trails them).
        let mut args = vec!["file", "annotate"];
        if let Some(revset) = revset.as_deref() {
            args.push("-r");
            args.push(revset);
        }
        args.extend([
            "-T",
            parse::ANNOTATE_TEMPLATE,
            "--color",
            "never",
            "--",
            path,
        ]);
        self.core
            .parse(self.core.command_in(dir, args), parse::parse_annotate)
            .await
    }

    async fn file_show(&self, dir: &Path, revset: &str, path: &str) -> Result<String> {
        // `file show` takes FILESETS, so a bare path with a fileset
        // metacharacter (`(`, `*`, `~`, …) would be parsed as an expression —
        // wrap it in the exact-path form. (`file annotate` is the opposite: it
        // takes a plain PATH and rejects the `file:"…"` form.)
        let fileset = JjFileset::path(path);
        self.core
            .run(self.cmd_in(dir, ["file", "show", "-r", revset, fileset.as_str()]))
            .await
    }

    async fn rebase(&self, dir: &Path, onto: &str) -> Result<()> {
        self.core
            .run_unit(self.cmd_in(dir, ["rebase", "-d", onto]))
            .await
    }

    async fn rebase_branch(&self, dir: &Path, branch: &str, dest: &str) -> Result<()> {
        self.core
            .run_unit(self.cmd_in(dir, ["rebase", "-b", branch, "-d", dest]))
            .await
    }

    async fn edit(&self, dir: &Path, revset: &str) -> Result<()> {
        reject_flag_like("revset", revset)?;
        self.core.run_unit(self.cmd_in(dir, ["edit", revset])).await
    }

    async fn squash_into(
        &self,
        dir: &Path,
        into: &str,
        use_destination_message: bool,
    ) -> Result<()> {
        let mut command = self.cmd_in(dir, ["squash", "--into", into]);
        if use_destination_message {
            command = command.arg("--use-destination-message");
        }
        self.core.run_unit(command).await
    }

    async fn commit_paths(&self, dir: &Path, filesets: &[JjFileset], message: &str) -> Result<()> {
        let mut args: Vec<String> = vec!["commit".into(), "-m".into(), message.into()];
        args.extend(filesets.iter().map(|f| f.as_str().to_string()));
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn squash_paths(&self, dir: &Path, spec: SquashPaths) -> Result<()> {
        let mut args: Vec<String> = vec![
            "squash".into(),
            "--from".into(),
            spec.from,
            "--into".into(),
            spec.into,
        ];
        if spec.use_destination_message {
            args.push("--use-destination-message".into());
        }
        args.extend(spec.filesets.iter().map(|f| f.as_str().to_string()));
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn sparse_set(&self, dir: &Path, patterns: &[String]) -> Result<()> {
        // `--clear` empties the working copy first, then each `--add` reinstates a
        // pattern — so the working copy ends up holding exactly `patterns`.
        let mut args: Vec<String> = vec!["sparse".into(), "set".into(), "--clear".into()];
        for pattern in patterns {
            args.push("--add".into());
            args.push(pattern.clone());
        }
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn new_merge(&self, dir: &Path, message: &str, parents: Vec<String>) -> Result<()> {
        // Parents are bare positionals — a leading-`-` one (e.g.
        // `--ignore-working-copy`) would be silently consumed as a flag.
        for parent in &parents {
            reject_flag_like("parent", parent)?;
        }
        let mut args: Vec<String> = vec!["new".into(), "-m".into(), message.into()];
        args.extend(parents);
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn abandon(&self, dir: &Path, revset: &str) -> Result<()> {
        reject_flag_like("revset", revset)?;
        self.core
            .run_unit(self.cmd_in(dir, ["abandon", revset]))
            .await
    }

    async fn git_fetch_branch(&self, dir: &Path, branch: &str) -> Result<()> {
        let cmd = self
            .cmd_in(dir, ["git", "fetch", "--remote", "origin", "-b", branch])
            .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error);
        self.core.run_unit(cmd).await
    }

    async fn git_import(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.cmd_in(dir, ["git", "import"]))
            .await
    }

    async fn git_clone(&self, url: &str, dest: &Path, colocate: bool) -> Result<()> {
        // A leading-`-` url is a bare positional — guard it (a real URL never
        // leads with `-`, so no false positives).
        reject_flag_like("url", url)?;
        // No working directory yet (the clone creates `dest`), so this builds
        // on the raw `command` and appends `--color never` at the end — the
        // `workspace_add` precedent for color-after-value-args. The colocate
        // flag is ALWAYS passed: jj's default flipped across versions and is
        // overridable via `git.colocate` config, so an omitted flag would make
        // `colocate: false` a lie on some setups.
        let command = self
            .core
            .command(["git", "clone", url])
            .arg(dest)
            .arg(if colocate {
                "--colocate"
            } else {
                "--no-colocate"
            });
        self.core
            .run_unit(command.arg("--color").arg("never"))
            .await
    }

    async fn absorb(&self, dir: &Path, from: Option<String>, filesets: &[JjFileset]) -> Result<()> {
        let mut args: Vec<String> = vec!["absorb".into()];
        if let Some(from) = from.as_deref() {
            args.push("--from".into());
            args.push(from.into());
        }
        args.extend(filesets.iter().map(|f| f.as_str().to_string()));
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn split_paths(&self, dir: &Path, filesets: &[JjFileset], message: &str) -> Result<()> {
        // A fileset-less `jj split` opens the interactive diff editor — even
        // with `-m` — which would hang a headless run indefinitely. Refuse
        // before spawning anything.
        if filesets.is_empty() {
            return Err(Error::Spawn {
                program: BINARY.to_string(),
                source: std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "split_paths requires at least one fileset — an empty split \
                     opens jj's interactive diff editor",
                ),
            });
        }
        // `-m` doubles as the description-editor suppressor.
        let mut args: Vec<String> = vec!["split".into(), "-m".into(), message.into()];
        args.extend(filesets.iter().map(|f| f.as_str().to_string()));
        self.core.run_unit(self.cmd_in(dir, args)).await
    }

    async fn duplicate(&self, dir: &Path, revset: &str) -> Result<()> {
        reject_flag_like("revset", revset)?;
        self.core
            .run_unit(self.cmd_in(dir, ["duplicate", revset]))
            .await
    }

    async fn op_head(&self, dir: &Path) -> Result<String> {
        self.core
            .run(self.cmd_in(
                dir,
                [
                    "op",
                    "log",
                    "--no-graph",
                    "--limit",
                    "1",
                    "-T",
                    "id.short()",
                ],
            ))
            .await
    }

    async fn op_log(&self, dir: &Path, limit: usize) -> Result<Vec<Operation>> {
        let limit = limit.to_string();
        self.core
            .parse(
                self.cmd_in(
                    dir,
                    [
                        "op",
                        "log",
                        "--no-graph",
                        "--limit",
                        limit.as_str(),
                        "-T",
                        parse::OP_TEMPLATE,
                    ],
                ),
                parse::parse_operations,
            )
            .await
    }

    async fn op_restore(&self, dir: &Path, op_id: &str) -> Result<()> {
        reject_flag_like("operation id", op_id)?;
        self.core
            .run_unit(self.cmd_in(dir, ["op", "restore", op_id]))
            .await
    }

    async fn op_undo(&self, dir: &Path) -> Result<()> {
        self.core.run_unit(self.cmd_in(dir, ["op", "undo"])).await
    }

    async fn workspace_list(&self, dir: &Path) -> Result<Vec<Workspace>> {
        self.core
            .parse(
                self.cmd_in(dir, ["workspace", "list", "-T", parse::WORKSPACE_TEMPLATE]),
                parse::parse_workspaces,
            )
            .await
    }

    async fn workspace_root(&self, dir: &Path, name: Option<String>) -> Result<PathBuf> {
        let mut args: Vec<String> = vec!["workspace".into(), "root".into()];
        if let Some(n) = name.as_deref() {
            args.push("--name".into());
            args.push(n.to_string());
        }
        Ok(PathBuf::from(self.core.run(self.cmd_in(dir, args)).await?))
    }

    async fn workspace_add(&self, dir: &Path, spec: WorkspaceAdd) -> Result<()> {
        // Built directly on `command_in` (not `cmd_in`) because the trailing
        // `--color never` must come after the chained value args, not between
        // `--name` and its value.
        let mut command = self
            .core
            .command_in(dir, ["workspace", "add", "--name"])
            .arg(&spec.name)
            .arg("-r")
            .arg(&spec.base);
        if let Some(mode) = spec.sparse_patterns {
            command = command.arg("--sparse-patterns").arg(mode.as_arg());
        }
        command = command.arg(&spec.path).arg("--color").arg("never");
        self.core.run_unit(command).await
    }

    async fn workspace_forget(&self, dir: &Path, name: &str) -> Result<()> {
        reject_flag_like("workspace name", name)?;
        self.core
            .run_unit(self.cmd_in(dir, ["workspace", "forget", name]))
            .await
    }
}

/// Total attempts / fixed backoff for a transient-retried fetch — the shared
/// policy from `vcs-cli-support`, aliased so the retry call sites read locally.
const FETCH_ATTEMPTS: u32 = vcs_cli_support::FETCH_ATTEMPTS;
const FETCH_BACKOFF: Duration = vcs_cli_support::FETCH_BACKOFF;

/// How many `jj workspace root` lookups [`Jj::workspace_roots`] keeps in flight at
/// once — a cap so a repo with many workspaces doesn't spawn an unbounded burst of
/// processes, while still overlapping the (fast, network-free) calls.
const WORKSPACE_ROOTS_CONCURRENCY: usize = 8;

impl<R: ProcessRunner> Jj<R> {
    /// Run `jj <args>` over string slices — `jj.run_args(&["log", "-r", "@"])`
    /// without allocating a `Vec<String>`. Inherent (not on the object-safe
    /// trait), so it can take `&[&str]`; forwards to the same path as
    /// [`JjApi::run`].
    pub async fn run_args(&self, args: &[&str]) -> Result<String> {
        self.core.run(self.core.command(args)).await
    }

    /// Resolve several workspaces' root paths in one **bounded fan-out** — one
    /// `jj workspace root --name <n>` per name, at most
    /// `WORKSPACE_ROOTS_CONCURRENCY` (8) live at a time — instead of awaiting each in
    /// turn. Per-name `Ok`/`Err` mirrors [`workspace_root`](JjApi::workspace_root)
    /// (a non-zero exit or spawn failure → `Err`); results come back in `names`
    /// order. Runs through this client's own runner, so a `ScriptedRunner` test
    /// drives it hermetically. Inherent (not on the object-safe trait): it's a
    /// throughput shape over the trait method, and the batch primitive isn't a
    /// mockable per-call seam.
    pub async fn workspace_roots(&self, dir: &Path, names: &[String]) -> Vec<Result<PathBuf>> {
        let commands = names
            .iter()
            .map(|n| self.cmd_in(dir, ["workspace", "root", "--name", n.as_str()]));
        processkit::output_all(commands, WORKSPACE_ROOTS_CONCURRENCY, self.core.runner())
            .await
            .into_iter()
            .map(|r| {
                r.and_then(|pr| pr.ensure_success())
                    // `trim_end` (not `trim`) for exact parity with the single
                    // `workspace_root`, which trims via `core.run`'s `trim_end`.
                    .map(|pr| PathBuf::from(pr.stdout().trim_end()))
            })
            .collect()
    }

    /// Like [`run_args`](Jj::run_args) but never errors on a non-zero exit
    /// (mirrors [`JjApi::run_raw`]).
    pub async fn run_raw_args(&self, args: &[&str]) -> Result<ProcessResult<String>> {
        self.core.output(self.core.command(args)).await
    }

    /// Bind this client to `dir`, returning a [`JjAt`] handle whose methods omit
    /// the `dir` argument: `jj.at(dir).status()` runs [`status`](JjApi::status)
    /// against `dir`. The dir-taking [`JjApi`] methods stay on [`Jj`] for driving
    /// many directories (e.g. workspaces) from one client.
    pub fn at<'a>(&'a self, dir: &'a Path) -> JjAt<'a, R> {
        JjAt { jj: self, dir }
    }

    /// Run a mutation sequence with op-log rollback: capture the current
    /// operation ([`op_head`](JjApi::op_head)), run `f` with a [`JjAt`] bound to
    /// `dir`, and on `Err` restore the repo to the captured operation
    /// ([`op_restore`](JjApi::op_restore)) before returning the error.
    ///
    /// ```no_run
    /// # async fn demo(jj: &vcs_jj::Jj) -> Result<(), processkit::Error> {
    /// jj.transaction(std::path::Path::new("."), |tx| async move {
    ///     tx.describe("wip").await?;
    ///     tx.new_change("next").await // an Err here rolls back the describe
    /// })
    /// .await?;
    /// # Ok(()) }
    /// ```
    ///
    /// Inherent (not on the object-safe trait): the closure parameter is
    /// generic, which `mockall` / trait objects can't express.
    ///
    /// Caveats:
    /// - Rollback runs on `Err` only — **not** on panic or cancellation (a
    ///   dropped future); there is no async `Drop`. Convert panics to `Err`
    ///   inside `f` if you need that safety.
    /// - If the restore itself fails, the *original* error from `f` is returned
    ///   and the repo may be left mid-transaction; re-probe
    ///   [`op_head`](JjApi::op_head) to detect that.
    pub async fn transaction<'a, T, F, Fut>(&'a self, dir: &'a Path, f: F) -> Result<T>
    where
        F: FnOnce(JjAt<'a, R>) -> Fut,
        Fut: Future<Output = Result<T>> + 'a,
    {
        let pre = self.op_head(dir).await?;
        match f(self.at(dir)).await {
            Ok(value) => Ok(value),
            Err(err) => {
                // Best-effort restore; the closure's error is the cause and is
                // what the caller must see even when the restore also fails.
                let _ = self.op_restore(dir, &pre).await;
                Err(err)
            }
        }
    }
}

/// A [`Jj`] client with a working directory bound, so calls drop the leading
/// `dir` argument — `jj.at(dir).status()` is `jj.status(dir)`. Construct one with
/// [`Jj::at`] (or, through the facade, `vcs_core::Repo::jj_at`). Cheap to copy: it
/// only borrows the client and the path.
pub struct JjAt<'a, R: ProcessRunner = processkit::JobRunner> {
    jj: &'a Jj<R>,
    dir: &'a Path,
}

// Hand-written rather than derived: holding only references, the view is `Copy`
// for *every* runner. `#[derive(Copy)]` would add a spurious `R: Copy` bound the
// default `JobRunner` doesn't satisfy, silently dropping `Copy` on the production
// handle.
impl<R: ProcessRunner> Clone for JjAt<'_, R> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<R: ProcessRunner> Copy for JjAt<'_, R> {}

/// Generate [`JjAt`] forwarders from a method list: `bare` methods forward
/// verbatim, `dir` methods inject `self.dir` as the first argument.
macro_rules! jj_at_forwarders {
    (
        bare { $( fn $bn:ident( $($ba:ident: $bt:ty),* $(,)? ) -> $br:ty; )* }
        dir  { $( fn $dn:ident( $($da:ident: $dt:ty),* $(,)? ) -> $dr:ty; )* }
    ) => {
        impl<'a, R: ProcessRunner> JjAt<'a, R> {
            $(
                #[doc = concat!("Bound form of [`Jj`]'s `", stringify!($bn), "`.")]
                pub async fn $bn(&self, $($ba: $bt),*) -> $br {
                    self.jj.$bn($($ba),*).await
                }
            )*
            $(
                #[doc = concat!("Bound form of [`Jj`]'s `", stringify!($dn), "` (with `dir` pre-bound).")]
                pub async fn $dn(&self, $($da: $dt),*) -> $dr {
                    self.jj.$dn(self.dir, $($da),*).await
                }
            )*
        }
    };
}

jj_at_forwarders! {
    bare {
        fn run(args: &[String]) -> Result<String>;
        fn run_raw(args: &[String]) -> Result<ProcessResult<String>>;
        fn run_args(args: &[&str]) -> Result<String>;
        fn run_raw_args(args: &[&str]) -> Result<ProcessResult<String>>;
        fn version() -> Result<String>;
        fn capabilities() -> Result<JjCapabilities>;
        fn git_clone(url: &str, dest: &Path, colocate: bool) -> Result<()>;
    }
    dir {
        fn status() -> Result<Vec<ChangedPath>>;
        fn status_text() -> Result<String>;
        fn log(revset: &str, max: usize) -> Result<Vec<Change>>;
        fn current_change() -> Result<Change>;
        fn describe(message: &str) -> Result<()>;
        fn describe_rev(revset: &str, message: &str) -> Result<()>;
        fn new_change(message: &str) -> Result<()>;
        fn bookmarks() -> Result<Vec<Bookmark>>;
        fn bookmarks_all() -> Result<Vec<BookmarkRef>>;
        fn reachable_bookmarks() -> Result<Vec<Bookmark>>;
        fn bookmark_track(name: &str, remote: &str) -> Result<()>;
        fn bookmark_set(name: &str, revision: &str) -> Result<()>;
        fn git_fetch() -> Result<()>;
        fn git_fetch_from(remote: &str) -> Result<()>;
        fn git_push(bookmark: Option<String>) -> Result<()>;
        fn root() -> Result<PathBuf>;
        fn current_bookmark() -> Result<Option<String>>;
        fn trunk() -> Result<Option<String>>;
        fn bookmark_create(name: &str, revision: &str) -> Result<()>;
        fn bookmark_rename(old: &str, new: &str) -> Result<()>;
        fn bookmark_delete(name: &str) -> Result<()>;
        fn bookmark_move(name: &str, to: &str, allow_backwards: bool) -> Result<()>;
        fn diff_summary(from: &str, to: &str) -> Result<Vec<ChangedPath>>;
        fn diff_stat(revset: &str) -> Result<DiffStat>;
        fn diff_text(spec: DiffSpec) -> Result<String>;
        fn diff(spec: DiffSpec) -> Result<Vec<FileDiff>>;
        fn commit_count(revset: &str) -> Result<usize>;
        fn is_conflicted(revset: &str) -> Result<bool>;
        fn has_workingcopy_conflict() -> Result<bool>;
        fn resolve_list(revset: &str) -> Result<Vec<String>>;
        fn template_query(revset: &str, template: &str, limit: Option<usize>) -> Result<String>;
        fn description(revset: &str) -> Result<String>;
        fn evolog(revset: &str, max: usize) -> Result<Vec<Change>>;
        fn file_annotate(path: &str, revset: Option<String>) -> Result<Vec<AnnotationLine>>;
        fn file_show(revset: &str, path: &str) -> Result<String>;
        fn absorb(from: Option<String>, filesets: &[JjFileset]) -> Result<()>;
        fn split_paths(filesets: &[JjFileset], message: &str) -> Result<()>;
        fn duplicate(revset: &str) -> Result<()>;
        fn rebase(onto: &str) -> Result<()>;
        fn rebase_branch(branch: &str, dest: &str) -> Result<()>;
        fn edit(revset: &str) -> Result<()>;
        fn squash_into(into: &str, use_destination_message: bool) -> Result<()>;
        fn commit_paths(filesets: &[JjFileset], message: &str) -> Result<()>;
        fn squash_paths(spec: SquashPaths) -> Result<()>;
        fn sparse_set(patterns: &[String]) -> Result<()>;
        fn new_merge(message: &str, parents: Vec<String>) -> Result<()>;
        fn abandon(revset: &str) -> Result<()>;
        fn git_fetch_branch(branch: &str) -> Result<()>;
        fn git_import() -> Result<()>;
        fn op_head() -> Result<String>;
        fn op_log(limit: usize) -> Result<Vec<Operation>>;
        fn op_restore(op_id: &str) -> Result<()>;
        fn op_undo() -> Result<()>;
        fn workspace_list() -> Result<Vec<Workspace>>;
        fn workspace_root(name: Option<String>) -> Result<PathBuf>;
        fn workspace_add(spec: WorkspaceAdd) -> Result<()>;
        fn workspace_forget(name: &str) -> Result<()>;
    }
}

// Manual forwarder: `transaction` takes a generic closure, which the declarative
// forwarder macro (fixed argument lists) cannot express.
impl<'a, R: ProcessRunner> JjAt<'a, R> {
    /// Bound form of [`Jj::transaction`] (with `dir` pre-bound): run `f` with
    /// op-log rollback on `Err`. See [`Jj::transaction`] for the caveats.
    pub async fn transaction<T, F, Fut>(&self, f: F) -> Result<T>
    where
        F: FnOnce(JjAt<'a, R>) -> Fut,
        Fut: Future<Output = Result<T>> + 'a,
    {
        self.jj.transaction(self.dir, f).await
    }
}

/// Synchronous, best-effort helpers for contexts that cannot `.await` — chiefly
/// a `Drop` guard. They shell out through `std::process` directly (no async, no
/// job-containment), so reserve them for short-lived cleanup.
pub mod blocking {
    use std::path::{Path, PathBuf};
    use std::process::Command;

    /// Forget a workspace synchronously (`jj workspace forget <name>`).
    pub fn workspace_forget(dir: &Path, name: &str) -> std::io::Result<()> {
        let status = Command::new(super::BINARY)
            .current_dir(dir)
            .args(["workspace", "forget", name])
            .status()?;
        if status.success() {
            Ok(())
        } else {
            Err(std::io::Error::other(format!(
                "`jj workspace forget` exited with {status}"
            )))
        }
    }

    /// Resolve the workspace *name* whose root matches `path`, synchronously —
    /// for `Drop`, which can't `.await` the typed `workspace_list`/`workspace_root`.
    /// Lists workspaces (`workspace list -T name`), then matches each
    /// `workspace root --name <n>` against `path` (canonicalised, Windows
    /// verbatim-prefix stripped). `None` when jj is missing or nothing matches —
    /// the caller then skips the forget rather than guessing.
    pub fn workspace_name_for_path(dir: &Path, path: &Path) -> Option<String> {
        let target = normalize(path);
        let out = Command::new(super::BINARY)
            .current_dir(dir)
            .args(["workspace", "list", "-T", "name ++ \"\\n\""])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        for name in String::from_utf8_lossy(&out.stdout).lines() {
            let name = name.trim();
            if name.is_empty() {
                continue;
            }
            let root = Command::new(super::BINARY)
                .current_dir(dir)
                .args(["workspace", "root", "--name", name])
                .output();
            if let Ok(r) = root
                && r.status.success()
            {
                let p = PathBuf::from(String::from_utf8_lossy(&r.stdout).trim().to_string());
                if normalize(&p) == target || p == target || p == path {
                    return Some(name.to_string());
                }
            }
        }
        None
    }

    /// Canonicalise + strip the Windows verbatim prefix (`\\?\…`, which
    /// `canonicalize` adds but jj never emits) for stable path comparison.
    fn normalize(p: &Path) -> PathBuf {
        let canonical = p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
        #[cfg(windows)]
        {
            let s = canonical.to_string_lossy();
            if let Some(rest) = s.strip_prefix(r"\\?\")
                && !rest.starts_with("UNC\\")
            {
                return PathBuf::from(rest.to_string());
            }
        }
        canonical
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use processkit::{RecordingRunner, Reply, ScriptedRunner};

    #[test]
    fn binary_name_is_jj() {
        assert_eq!(BINARY, "jj");
    }

    // Compile-time guard: the bound view stays `Copy` for the default `JobRunner`.
    #[allow(dead_code)]
    fn bound_view_is_copy_for_default_runner() {
        fn assert_copy<T: Copy>() {}
        assert_copy::<JjAt<'static, processkit::JobRunner>>();
    }

    // The bound view (`jj.at(dir)`) must produce byte-identical argv to the
    // dir-taking call — including the forced `--color never`.
    #[tokio::test]
    async fn bound_view_matches_dir_taking_calls() {
        let dir = Path::new("/repo");
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);

        jj.bookmark_move(dir, "main", "@", true).await.unwrap();
        jj.at(dir).bookmark_move("main", "@", true).await.unwrap();
        jj.describe_rev(dir, "feat", "msg").await.unwrap();
        jj.at(dir).describe_rev("feat", "msg").await.unwrap();
        jj.description(dir, "@-").await.unwrap();
        jj.at(dir).description("@-").await.unwrap();
        // One of the §4 additions.
        jj.duplicate(dir, "@-").await.unwrap();
        jj.at(dir).duplicate("@-").await.unwrap();

        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), calls[1].args_str());
        assert_eq!(calls[2].args_str(), calls[3].args_str());
        assert_eq!(calls[4].args_str(), calls[5].args_str());
        assert_eq!(calls[6].args_str(), calls[7].args_str());
        assert_eq!(calls[1].cwd.as_deref(), Some(dir.as_os_str()));
    }

    #[tokio::test]
    async fn workspace_list_parses_template_rows() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(
            ["workspace", "list"],
            Reply::ok("default\te2aa3420\tmain\nws1\t12345678\t\n"),
        ));
        let got = jj.workspace_list(Path::new(".")).await.expect("list");
        assert_eq!(got.len(), 2);
        assert_eq!(got[0].name, "default");
        assert_eq!(got[0].bookmarks, vec!["main".to_string()]);
        assert!(got[1].bookmarks.is_empty());
    }

    // `workspace_roots` fans out one `workspace root --name <n>` per name, returns
    // a path per slot in input order, and maps a non-zero exit to `Err` for that
    // slot (mirroring the single `workspace_root`). Runs through the scripted
    // runner, so it's hermetic.
    #[tokio::test]
    async fn workspace_roots_batches_per_name_and_maps_errors() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(
                    ["workspace", "root", "--name", "default"],
                    Reply::ok("/repo\n"),
                )
                .on(
                    ["workspace", "root", "--name", "ws1"],
                    Reply::ok("/repo/ws1\n"),
                )
                .on(
                    ["workspace", "root", "--name", "gone"],
                    Reply::fail(1, "Error: No such workspace"),
                ),
        );
        let jj = Jj::with_runner(&rec);
        let roots = jj
            .workspace_roots(
                Path::new("/repo"),
                &["default".into(), "gone".into(), "ws1".into()],
            )
            .await;
        // Order matches the input, regardless of completion order.
        assert_eq!(roots.len(), 3);
        assert_eq!(roots[0].as_deref().unwrap(), Path::new("/repo"));
        assert!(roots[1].is_err(), "a non-zero `workspace root` is Err");
        assert_eq!(roots[2].as_deref().unwrap(), Path::new("/repo/ws1"));
        // Exactly one `workspace root --name <n>` command per name.
        let calls = rec.calls();
        assert_eq!(calls.len(), 3);
        assert!(
            calls
                .iter()
                .all(|c| c.args_str()[..2] == ["workspace", "root"])
        );
    }

    // `workspace add` must build `--name <n> -r <base> <path>` in order.
    #[tokio::test]
    async fn workspace_add_builds_name_base_path() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.workspace_add(Path::new("/repo"), WorkspaceAdd::new("ws1", "main", "/wt"))
            .await
            .expect("workspace add");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "workspace",
                "add",
                "--name",
                "ws1",
                "-r",
                "main",
                "/wt",
                "--color",
                "never"
            ]
        );
    }

    // `--sparse-patterns <mode>` lands between `-r <base>` and the path.
    #[tokio::test]
    async fn workspace_add_with_sparse_mode() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.workspace_add(
            Path::new("/repo"),
            WorkspaceAdd::new("ws1", "main", "/wt").sparse(SparseMode::Empty),
        )
        .await
        .expect("workspace add");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "workspace",
                "add",
                "--name",
                "ws1",
                "-r",
                "main",
                "--sparse-patterns",
                "empty",
                "/wt",
                "--color",
                "never"
            ]
        );
    }

    #[test]
    fn fileset_quotes_metacharacters() {
        assert_eq!(
            JjFileset::path("src/a(b).rs").as_str(),
            "file:\"src/a(b).rs\""
        );
        // A Windows backslash separator is normalised to `/` so jj matches it
        // (a literal-backslash filename would match nothing).
        assert_eq!(JjFileset::path("src\\a.rs").as_str(), "file:\"src/a.rs\"");
        // A literal quote is escaped for the `file:"…"` string literal.
        assert_eq!(JjFileset::path("a\"b").as_str(), "file:\"a\\\"b\"");
    }

    #[tokio::test]
    async fn commit_paths_builds_filesets() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.commit_paths(
            Path::new("."),
            &[JjFileset::path("x|y.rs"), JjFileset::path("z.rs")],
            "msg",
        )
        .await
        .expect("commit_paths");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "commit",
                "-m",
                "msg",
                "file:\"x|y.rs\"",
                "file:\"z.rs\"",
                "--color",
                "never"
            ]
        );
    }

    #[tokio::test]
    async fn squash_paths_builds_from_into_filesets() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.squash_paths(
            Path::new("."),
            SquashPaths::new("@", "feat").filesets([JjFileset::path("a.rs")]),
        )
        .await
        .expect("squash_paths");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "squash",
                "--from",
                "@",
                "--into",
                "feat",
                "file:\"a.rs\"",
                "--color",
                "never"
            ]
        );
    }

    #[tokio::test]
    async fn squash_paths_keeps_destination_message() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.squash_paths(
            Path::new("."),
            SquashPaths::new("@", "feat")
                .filesets([JjFileset::path("a.rs")])
                .use_destination_message(),
        )
        .await
        .expect("squash_paths");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "squash",
                "--from",
                "@",
                "--into",
                "feat",
                "--use-destination-message",
                "file:\"a.rs\"",
                "--color",
                "never"
            ]
        );
    }

    #[tokio::test]
    async fn jj_new_revision_scoped_ops_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.describe_rev(Path::new("."), "feat", "msg")
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["describe", "-r", "feat", "-m", "msg", "--color", "never"]
        );

        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.rebase_branch(Path::new("."), "feat", "main")
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["rebase", "-b", "feat", "-d", "main", "--color", "never"]
        );

        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.bookmark_track(Path::new("."), "feat", "origin")
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["bookmark", "track", "feat@origin", "--color", "never"]
        );
    }

    #[tokio::test]
    async fn bookmarks_all_parses_local_and_remote() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(
            ["bookmark", "list"],
            Reply::ok("main\t\t0\tabc123\nmain\torigin\t1\tabc123\n"),
        ));
        let refs = jj.bookmarks_all(Path::new(".")).await.unwrap();
        assert_eq!(refs.len(), 2);
        assert_eq!(refs[0].name, "main");
        assert!(refs[0].remote.is_none() && !refs[0].tracked);
        assert_eq!(refs[1].remote.as_deref(), Some("origin"));
        assert!(refs[1].tracked);
    }

    #[tokio::test]
    async fn sparse_set_clears_then_adds() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.sparse_set(Path::new("."), &["README.md".into(), "lib".into()])
            .await
            .expect("sparse_set");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "sparse",
                "set",
                "--clear",
                "--add",
                "README.md",
                "--add",
                "lib",
                "--color",
                "never"
            ]
        );
    }

    // Parsed status() is backed by `diff -r @ --summary`, not `jj status`.
    #[tokio::test]
    async fn status_parses_diff_summary() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(
            ["diff", "-r", "@", "--summary"],
            Reply::ok("M a.rs\nA b.rs\n"),
        ));
        let entries = jj.status(Path::new(".")).await.expect("status");
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].status, 'M');
        assert_eq!(entries[1].path, "b.rs");
    }

    #[tokio::test]
    async fn status_text_is_raw_jj_status() {
        let jj = Jj::with_runner(
            ScriptedRunner::new().on(["status"], Reply::ok("Working copy changes:\n")),
        );
        assert!(
            jj.status_text(Path::new("."))
                .await
                .expect("status_text")
                .contains("Working copy changes")
        );
    }

    #[tokio::test]
    async fn run_args_forwards_str_slices() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(["root"], Reply::ok("/r\n")));
        assert_eq!(jj.run_args(&["root"]).await.unwrap(), "/r");
    }

    #[tokio::test]
    async fn bookmark_move_appends_allow_backwards() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.bookmark_move(Path::new("/r"), "main", "@", true)
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            [
                "bookmark",
                "move",
                "main",
                "--to",
                "@",
                "--allow-backwards",
                "--color",
                "never"
            ]
        );
    }

    #[tokio::test]
    async fn new_merge_appends_parents() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.new_merge(Path::new("/r"), "m", vec!["p1".into(), "p2".into()])
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["new", "-m", "m", "p1", "p2", "--color", "never"]
        );
    }

    #[tokio::test]
    async fn is_conflicted_reads_template_flag() {
        let yes = Jj::with_runner(ScriptedRunner::new().on(["log"], Reply::ok("1\n")));
        assert!(yes.is_conflicted(Path::new("."), "@").await.unwrap());
        let no = Jj::with_runner(ScriptedRunner::new().on(["log"], Reply::ok("0\n")));
        assert!(!no.is_conflicted(Path::new("."), "@").await.unwrap());
    }

    #[tokio::test]
    async fn commit_count_counts_template_lines() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(["log"], Reply::ok("a\nb\nc\n")));
        assert_eq!(jj.commit_count(Path::new("."), "::@").await.unwrap(), 3);
    }

    #[tokio::test]
    async fn reachable_bookmarks_queries_heads_revset() {
        let rec = RecordingRunner::replying(Reply::ok("main\tabc123\n"));
        let jj = Jj::with_runner(&rec);
        let got = jj.reachable_bookmarks(Path::new(".")).await.unwrap();
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].name, "main");
        let args = rec.only_call().args_str();
        assert_eq!(
            &args[..4],
            &["log", "-r", "heads(::@ & bookmarks())", "--no-graph"]
        );
    }

    #[tokio::test]
    async fn resolve_list_distinguishes_no_conflicts_from_errors() {
        // The benign "no conflicts" non-zero exit → empty list.
        let none = Jj::with_runner(ScriptedRunner::new().on(
            ["resolve"],
            Reply::fail(2, "Error: No conflicts found at this revision"),
        ));
        assert!(
            none.resolve_list(Path::new("."), "@")
                .await
                .unwrap()
                .is_empty()
        );
        // A real failure (e.g. bad revset) must surface, not read as "no conflicts".
        let bad = Jj::with_runner(ScriptedRunner::new().on(
            ["resolve"],
            Reply::fail(1, "Error: Revision `bogus` doesn't exist"),
        ));
        assert!(bad.resolve_list(Path::new("."), "bogus").await.is_err());
        // Success with conflicts → parsed paths.
        let some = Jj::with_runner(
            ScriptedRunner::new().on(["resolve"], Reply::ok("a.rs    2-sided conflict\n")),
        );
        assert_eq!(
            some.resolve_list(Path::new("."), "@").await.unwrap(),
            ["a.rs"]
        );
    }

    #[tokio::test]
    async fn current_bookmark_takes_first_or_none() {
        let some = Jj::with_runner(ScriptedRunner::new().on(["log"], Reply::ok("main\n")));
        assert_eq!(
            some.current_bookmark(Path::new("."))
                .await
                .unwrap()
                .as_deref(),
            Some("main")
        );
        let none = Jj::with_runner(ScriptedRunner::new().on(["log"], Reply::ok("\n")));
        assert!(
            none.current_bookmark(Path::new("."))
                .await
                .unwrap()
                .is_none()
        );
    }

    // Hermetic: real log() arg-building + template parsing against canned output.
    #[tokio::test]
    async fn current_change_parses_scripted_output() {
        let jj = Jj::with_runner(
            ScriptedRunner::new().on(["log"], Reply::ok("kztuxlro\t38e00654\tfalse\thello jj\n")),
        );
        let change = jj
            .current_change(Path::new("."))
            .await
            .expect("current_change");
        assert_eq!(change.change_id, "kztuxlro");
        assert!(!change.empty);
        assert_eq!(change.description, "hello jj");
    }

    // With a bookmark, the run must build `git push -b <name>`. Only that 4-token
    // command is scripted (no fallback), so a regression that dropped the flag
    // would match no rule and error.
    #[tokio::test]
    async fn git_push_appends_bookmark_flag() {
        let jj = Jj::with_runner(
            ScriptedRunner::new().on(["git", "push", "-b", "feature"], Reply::ok("")),
        );
        jj.git_push(Path::new("."), Some("feature".to_string()))
            .await
            .expect("should build `git push -b feature`");
    }

    // Without a bookmark, the run is a bare `git push`.
    #[tokio::test]
    async fn git_push_without_bookmark_is_bare() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(["git", "push"], Reply::ok("")));
        jj.git_push(Path::new("."), None).await.expect("bare push");
    }

    // `git_fetch` retries a transient (network) failure up to FETCH_ATTEMPTS times.
    #[tokio::test]
    async fn git_fetch_retries_transient_failures() {
        let rec = RecordingRunner::replying(Reply::fail(1, "Error: Could not resolve host: x"));
        let jj = Jj::with_runner(&rec);
        assert!(jj.git_fetch(Path::new(".")).await.is_err());
        assert_eq!(rec.calls().len(), FETCH_ATTEMPTS as usize);
    }

    // `git_fetch_from` names the remote and shares `git_fetch`'s transient retry.
    #[tokio::test]
    async fn git_fetch_from_builds_args_and_retries() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.git_fetch_from(Path::new("."), "upstream")
            .await
            .expect("git_fetch_from");
        assert_eq!(
            rec.only_call().args_str(),
            ["git", "fetch", "--remote", "upstream", "--color", "never"]
        );

        let failing = RecordingRunner::replying(Reply::fail(1, "Error: Connection timed out"));
        let jj = Jj::with_runner(&failing);
        assert!(jj.git_fetch_from(Path::new("."), "upstream").await.is_err());
        assert_eq!(failing.calls().len(), FETCH_ATTEMPTS as usize);
    }

    // `transaction` captures the op head and restores it when the closure errors —
    // and the original (closure) error is what surfaces.
    #[tokio::test]
    async fn transaction_restores_op_head_on_error() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["op", "log"], Reply::ok("abc123\n"))
                .on(["op", "restore"], Reply::ok(""))
                .on(["describe"], Reply::fail(1, "boom")),
        );
        let jj = Jj::with_runner(&rec);
        let res = jj
            .transaction(
                Path::new("/r"),
                |tx| async move { tx.describe("wip").await },
            )
            .await;
        let err = res.expect_err("closure error must surface");
        assert!(matches!(err, Error::Exit { .. }));
        let calls = rec.calls();
        assert_eq!(calls.len(), 3, "op head, mutation, restore: {calls:?}");
        assert_eq!(calls[0].args_str()[..2], ["op", "log"]);
        assert_eq!(calls[1].args_str()[0], "describe");
        assert_eq!(calls[2].args_str()[..3], ["op", "restore", "abc123"]);
    }

    // A successful transaction must NOT restore (that would undo the work).
    #[tokio::test]
    async fn transaction_keeps_changes_on_success() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["op", "log"], Reply::ok("abc123\n"))
                .on(["describe"], Reply::ok("")),
        );
        let jj = Jj::with_runner(&rec);
        jj.transaction(
            Path::new("/r"),
            |tx| async move { tx.describe("wip").await },
        )
        .await
        .expect("transaction");
        let calls = rec.calls();
        assert_eq!(calls.len(), 2);
        assert!(
            calls.iter().all(|c| c.args_str()[..2] != ["op", "restore"]),
            "no restore on success: {calls:?}"
        );
    }

    // The bound view forwards `transaction` with `dir` pre-bound.
    #[tokio::test]
    async fn bound_view_forwards_transaction() {
        let dir = Path::new("/repo");
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["op", "log"], Reply::ok("op9\n"))
                .on(["new"], Reply::ok("")),
        );
        let jj = Jj::with_runner(&rec);
        jj.at(dir)
            .transaction(|tx| async move { tx.new_change("x").await })
            .await
            .expect("transaction");
        assert_eq!(rec.calls()[1].cwd.as_deref(), Some(dir.as_os_str()));
    }

    // The injection guard: a flag-shaped value in any exposed positional slot
    // must be refused BEFORE anything spawns.
    #[tokio::test]
    async fn flag_like_positionals_are_rejected_before_spawning() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        let dir = Path::new("/r");

        assert!(jj.bookmark_create(dir, "-evil", "@").await.is_err());
        assert!(jj.bookmark_rename(dir, "ok", "-bad").await.is_err());
        assert!(jj.bookmark_delete(dir, "--all").await.is_err());
        assert!(jj.bookmark_move(dir, "-evil", "@", false).await.is_err());
        assert!(jj.edit(dir, "-evil").await.is_err());
        assert!(jj.duplicate(dir, "-r").await.is_err());
        assert!(jj.abandon(dir, "-evil").await.is_err());
        // Token-prefix and other bare positionals:
        assert!(
            jj.bookmark_track(dir, "--config=x", "origin")
                .await
                .is_err(),
            "name leads the {{name}}@{{remote}} token"
        );
        assert!(jj.bookmark_set(dir, "-evil", "@").await.is_err());
        assert!(jj.op_restore(dir, "--help").await.is_err());
        assert!(jj.workspace_forget(dir, "-evil").await.is_err());
        assert!(
            jj.new_merge(dir, "m", vec!["@".into(), "--ignore-working-copy".into()])
                .await
                .is_err(),
            "a flag-shaped parent is refused"
        );
        assert!(jj.git_clone("-evil", dir, false).await.is_err());
        assert!(jj.edit(dir, "").await.is_err(), "empty refused too");
        assert!(
            rec.calls().is_empty(),
            "nothing may spawn: {:?}",
            rec.calls()
        );

        // …and legitimate values still pass through unchanged.
        jj.edit(dir, "abc123").await.expect("edit");
        assert_eq!(
            rec.only_call().args_str(),
            ["edit", "abc123", "--color", "never"]
        );
    }

    #[test]
    fn revset_expr_validates() {
        assert!(RevsetExpr::new("heads(::@ & bookmarks())").is_ok());
        assert_eq!(RevsetExpr::new("@-").unwrap().as_str(), "@-");
        assert!(RevsetExpr::new("-evil").is_err());
        assert!(RevsetExpr::new("").is_err());
    }

    // capabilities parses jj's version line (incl. dev-build suffixes) and
    // gates precisely on the validated 0.38 floor.
    #[tokio::test]
    async fn capabilities_parse_and_gate_versions() {
        let jj = Jj::with_runner(ScriptedRunner::new().on(["--version"], Reply::ok("jj 0.38.0\n")));
        let caps = jj.capabilities().await.expect("capabilities");
        assert!(caps.is_supported());
        caps.ensure_supported().expect("supported");

        // A dev-build suffix parses; an older release fails the precise gate.
        let dev = Jj::with_runner(
            ScriptedRunner::new().on(["--version"], Reply::ok("jj 0.39.0-dev+abc123\n")),
        );
        assert!(dev.capabilities().await.unwrap().is_supported());

        let old =
            Jj::with_runner(ScriptedRunner::new().on(["--version"], Reply::ok("jj 0.35.0\n")));
        let caps = old.capabilities().await.expect("capabilities");
        assert!(!caps.is_supported());
        let err = caps.ensure_supported().expect_err("unsupported");
        // The message must name both the floor and the found version.
        let Error::Spawn { source, .. } = &err else {
            panic!("expected Spawn, got {err:?}");
        };
        let message = source.to_string();
        assert!(message.contains("0.38.0"), "names the floor: {message}");
        assert!(
            message.contains("0.35.0"),
            "names the found version: {message}"
        );

        let garbage = Jj::with_runner(ScriptedRunner::new().on(["--version"], Reply::ok("nope")));
        assert!(matches!(
            garbage.capabilities().await.unwrap_err(),
            Error::Parse { .. }
        ));
    }

    // git_clone is dir-less; the colocate flag is ALWAYS explicit (jj's default
    // varies by version/config) and `--color never` still lands at the very end.
    #[tokio::test]
    async fn git_clone_builds_dirless_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.git_clone("https://x/r.git", Path::new("/dest"), true)
            .await
            .expect("clone");
        let call = rec.only_call();
        assert_eq!(
            call.args_str(),
            [
                "git",
                "clone",
                "https://x/r.git",
                "/dest",
                "--colocate",
                "--color",
                "never"
            ]
        );
        assert_eq!(call.cwd, None, "clone runs without a working directory");

        let plain = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&plain);
        jj.git_clone("u", Path::new("/d"), false).await.unwrap();
        let call = plain.only_call();
        assert!(call.has_flag("--no-colocate"), "explicit either way");
        assert!(!call.has_flag("--colocate"));
    }

    #[tokio::test]
    async fn absorb_and_split_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.absorb(Path::new("/r"), None, &[]).await.unwrap();
        jj.absorb(
            Path::new("/r"),
            Some("@-".into()),
            &[JjFileset::path("src/a.rs")],
        )
        .await
        .unwrap();
        jj.split_paths(Path::new("/r"), &[JjFileset::path("b.rs")], "split out b")
            .await
            .unwrap();
        jj.duplicate(Path::new("/r"), "@-").await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["absorb", "--color", "never"]);
        assert_eq!(
            calls[1].args_str(),
            [
                "absorb",
                "--from",
                "@-",
                "file:\"src/a.rs\"",
                "--color",
                "never"
            ]
        );
        assert_eq!(
            calls[2].args_str(),
            [
                "split",
                "-m",
                "split out b",
                "file:\"b.rs\"",
                "--color",
                "never"
            ]
        );
        assert_eq!(calls[3].args_str(), ["duplicate", "@-", "--color", "never"]);
    }

    // An empty split would open jj's interactive diff editor and hang headless —
    // it must be refused BEFORE any process spawns.
    #[tokio::test]
    async fn split_paths_refuses_empty_filesets_without_spawning() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        let err = jj
            .split_paths(Path::new("/r"), &[], "msg")
            .await
            .expect_err("empty filesets must be refused");
        assert!(matches!(err, Error::Spawn { .. }), "got {err:?}");
        assert!(rec.calls().is_empty(), "nothing may spawn");
    }

    #[tokio::test]
    async fn op_log_parses_template_rows() {
        let rec = RecordingRunner::new(ScriptedRunner::new().on(
            ["op", "log"],
            Reply::ok("abc\tu@h\t2026-06-05T10:00:00+0200\tnew empty commit\n"),
        ));
        let jj = Jj::with_runner(&rec);
        let ops = jj.op_log(Path::new("."), 5).await.expect("op_log");
        assert_eq!(ops.len(), 1);
        assert_eq!(ops[0].id, "abc");
        assert_eq!(ops[0].description, "new empty commit");
        let args = rec.only_call().args_str();
        assert_eq!(&args[..5], &["op", "log", "--no-graph", "--limit", "5"]);
    }

    // evolog must use the commit-context template (bare `change_id` doesn't
    // exist there) but flows through the same Change parser.
    #[tokio::test]
    async fn evolog_uses_commit_context_template() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new().on(["evolog"], Reply::ok("kz\t38\tfalse\twip\n")),
        );
        let jj = Jj::with_runner(&rec);
        let rows = jj.evolog(Path::new("."), "@", 10).await.expect("evolog");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].description, "wip");
        let args = rec.only_call().args_str();
        assert_eq!(
            &args[..6],
            &["evolog", "-r", "@", "--no-graph", "--limit", "10"]
        );
        let template = &args[7];
        assert!(
            template.contains("commit.change_id()"),
            "commit-context form required, got {template}"
        );
    }

    #[tokio::test]
    async fn file_annotate_and_show_build_args() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(
                    ["file", "annotate"],
                    Reply::ok("kz\tline one\nkz\tline two"),
                )
                .on(["file", "show"], Reply::ok("content\n")),
        );
        let jj = Jj::with_runner(&rec);
        let lines = jj
            .file_annotate(Path::new("."), "src/a.rs", Some("@-".into()))
            .await
            .expect("annotate");
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].change_id, "kz");
        assert_eq!(lines[1].line, 2);
        assert_eq!(
            jj.file_show(Path::new("."), "@-", "src/a.rs")
                .await
                .unwrap(),
            "content"
        );
        let calls = rec.calls();
        // The path follows a `--` separator (a leading-`-` filename stays safe);
        // `--color never` must precede `--`, not trail it.
        assert_eq!(
            calls[0].args_str(),
            [
                "file",
                "annotate",
                "-r",
                "@-",
                "-T",
                parse::ANNOTATE_TEMPLATE,
                "--color",
                "never",
                "--",
                "src/a.rs"
            ]
        );
        // file_show wraps the path as an exact-path fileset (metacharacters in
        // the name must stay literal); annotate takes a PLAIN path — quoting
        // it would break jj's path lookup.
        assert_eq!(
            calls[1].args_str(),
            [
                "file",
                "show",
                "-r",
                "@-",
                "file:\"src/a.rs\"",
                "--color",
                "never"
            ]
        );
    }

    // `description` is a fixed template query: first match only, raw description.
    #[tokio::test]
    async fn description_builds_single_commit_template_query() {
        let rec = RecordingRunner::replying(Reply::ok("feat: parser\n\nbody\n"));
        let jj = Jj::with_runner(&rec);
        let text = jj
            .description(Path::new("."), "abc123")
            .await
            .expect("description");
        assert_eq!(text, "feat: parser\n\nbody");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "log",
                "-r",
                "abc123",
                "--no-graph",
                "--limit",
                "1",
                "-T",
                "description",
                "--color",
                "never"
            ]
        );
    }

    // `diff_text` for the working copy must build `diff -r @ --git`.
    #[tokio::test]
    async fn diff_text_builds_working_copy_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let jj = Jj::with_runner(&rec);
        jj.diff_text(Path::new("."), DiffSpec::WorkingTree)
            .await
            .expect("diff_text");
        assert_eq!(
            rec.only_call().args_str(),
            ["diff", "-r", "@", "--git", "--color", "never"]
        );
    }

    // Every repo-scoped command forces `--color never` so a user's
    // `ui.color = "always"` config can't wrap parsed output in ANSI escapes.
    #[tokio::test]
    async fn commands_force_color_off() {
        let rec = RecordingRunner::replying(Reply::ok("x\n"));
        let jj = Jj::with_runner(&rec);
        jj.status_text(Path::new(".")).await.expect("status_text");
        let args = rec.only_call().args_str();
        let pos = args.iter().position(|a| a == "--color");
        assert_eq!(
            pos.map(|p| args.get(p + 1).map(String::as_str)),
            Some(Some("never"))
        );
    }

    // Hermetic: real diff() arg-building (`Rev`) + the ported parser against
    // canned git-format output.
    #[tokio::test]
    async fn diff_parses_scripted_output() {
        let out = "diff --git a/m b/m\n--- a/m\n+++ b/m\n@@ -1 +1 @@\n-a\n+b\n";
        let jj = Jj::with_runner(ScriptedRunner::new().on(["diff"], Reply::ok(out)));
        let files = jj
            .diff(Path::new("."), DiffSpec::Rev("@-".into()))
            .await
            .expect("diff");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "m");
        assert_eq!(files[0].change, ChangeKind::Modified);
    }

    #[cfg(feature = "mock")]
    #[tokio::test]
    async fn consumer_mocks_the_interface() {
        let mut mock = MockJjApi::new();
        mock.expect_describe().returning(|_, _| Ok(()));
        assert!(mock.describe(Path::new("."), "msg").await.is_ok());
    }
}

// Long-form how-to guides, rendered from this crate's docs/*.md on docs.rs.
#[doc = include_str!("../docs/jj.md")]
#[allow(rustdoc::broken_intra_doc_links)]
pub mod guide {}