rinkaku 0.4.1

Condense PR diffs into signatures and their dependencies for LLM-friendly review
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
//! Composition root for the `rinkaku` binary.
//!
//! This is the only place allowed to know about the concrete CLI wiring.
//! It stays a thin entry point: parse arguments, obtain the diff text
//! (stdin, `git diff`, or a resolved PR), read changed files, and
//! dispatch to the pure core in `lib.rs` (`pipeline::analyze_diff`,
//! `render::render`).
//!
//! The file-reading port passed to `analyze_diff` differs by input mode:
//!
//! - `--base` mode: the diff comes from `git diff <base>...<head>`, so
//!   files are read via `git show <head>:<path>` rather than off the
//!   working tree. This keeps the diff and the file content read from the
//!   exact same commit by construction, regardless of what the working
//!   tree currently holds (uncommitted changes, a dirty checkout, etc.).
//! - `--pr` mode (ADR 0004, ADR 0005, ADR 0006, ADR 0007): the PR's base
//!   branch, base commit (`baseRefOid`), and head commit are resolved via
//!   `gh pr view`; the head is fetched with `git fetch`, and the base
//!   commit is resolved via `baseRefOid` rather than the base branch's
//!   current tip (ADR 0007) — this is what makes `--pr` work on a merged
//!   PR, whose base branch has since advanced past the PR's own commits.
//!   The resulting base/head SHAs are handed to exactly the same
//!   `git show`-backed read strategy as `--base` mode — `--pr` is a
//!   resolution step in front of the `--base` pipeline, not a separate
//!   read strategy. A bare PR number requires running inside a local
//!   clone of the target repository. A PR URL also uses the current
//!   directory when its `origin` matches the URL's repository; otherwise
//!   it prefers an existing `ghq`-managed clone of the repository when one
//!   is found (ADR 0006), and only falls back to auto-cloning a blobless
//!   partial clone into a per-repository cache directory (ADR 0005) if
//!   neither the cwd nor `ghq` has one — so URL input works from any
//!   directory either way. `gh` must be installed and authenticated
//!   either way.
//! - stdin mode: the diff's provenance is unknown to rinkaku (it could be
//!   `gh pr diff`, a saved patch file, anything). Files are read off the
//!   working tree, under the assumption that **the diff is consistent
//!   with the current working tree** — i.e. applying it (or having
//!   already applied it) would reproduce the working tree's content. If
//!   that assumption doesn't hold, line numbers in the extracted symbols
//!   may not line up with the actual file content.

mod self_update;

use clap::{Parser, Subcommand};
use rinkaku_core::deps::TagsResolver;
use rinkaku_core::language::language_for_path;
use rinkaku_core::pipeline::analyze_diff;
use rinkaku_core::render::{OutputFormat, render};
use std::io::BufRead;
use std::io::IsTerminal;
use std::io::Read;
use std::io::Write;

/// rinkaku (輪郭) — condense PR diffs into signatures and their dependencies.
#[derive(Parser, Debug, PartialEq, Eq)]
#[command(name = "rinkaku", version, about, long_about = None)]
struct Cli {
    /// Subcommand to run. Omitted for the default diff-condensation flow
    /// (stdin / `--base` / `--deps` / `--format` below), which stays the
    /// primary, backward-compatible entry point.
    #[command(subcommand)]
    command: Option<Command>,

    /// Base ref to diff against (runs `git diff <base>...<head>` instead
    /// of reading from stdin).
    #[arg(long, conflicts_with = "pr")]
    base: Option<String>,

    /// Head ref to diff against `base`. Only meaningful together with
    /// `--base`; defaults to `HEAD`.
    //
    // `conflicts_with = "pr"` only fires when `--head` is explicitly
    // passed (clap does not treat a default value as "provided"), which
    // is exactly what's wanted: `--pr` resolves its own head commit via
    // `gh`, so an explicit `--head` alongside `--pr` would be silently
    // ignored otherwise.
    #[arg(long, default_value = "HEAD", conflicts_with = "pr")]
    head: String,

    /// GitHub PR to review, as a URL
    /// (`https://github.com/<owner>/<repo>/pull/<number>`) or a bare PR
    /// number (`76`). A bare number must be run inside a local clone of
    /// the target repository; a URL also works from any other directory
    /// by auto-cloning into a cache. Requires `gh` installed and
    /// authenticated.
    // See ADR 0004 for the resolve-then-fetch design and ADR 0005 for the
    // auto-clone-into-cache behavior this drives in `main`.
    #[arg(long)]
    pr: Option<String>,

    /// Output format.
    #[arg(long, value_enum, default_value_t = Format::Md)]
    format: Format,

    /// Whether to resolve each changed symbol's 1-hop dependencies
    /// (ADR 0003). `1` (default) runs the tags-based `Resolver` over
    /// every file tracked by `git ls-files`; `0` skips resolution
    /// entirely (no `Resolver::resolve` calls), which is faster and
    /// avoids the repo-wide indexing pass.
    #[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u8).range(0..=1))]
    deps: u8,
}

#[derive(Subcommand, Debug, PartialEq, Eq)]
enum Command {
    /// Update rinkaku to the latest GitHub release in place. If you
    /// installed via Homebrew or `cargo install`, prefer `brew upgrade`
    /// or `cargo install rinkaku` instead so your package manager stays
    /// in sync — self-update works either way, but it bypasses those
    /// managers' bookkeeping.
    ///
    /// Requires either an interactive terminal (to confirm the update) or
    /// `--yes`. Refuses to run when stdin is not a TTY and `--yes` is not
    /// given, since there would be no one to answer the confirmation
    /// prompt.
    SelfUpdate {
        /// Skip the interactive confirmation prompt and proceed.
        #[arg(long, short = 'y')]
        yes: bool,
    },
}

#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum Format {
    Md,
    Json,
}

impl From<Format> for OutputFormat {
    fn from(format: Format) -> Self {
        match format {
            Format::Md => OutputFormat::Markdown,
            Format::Json => OutputFormat::Json,
        }
    }
}

fn main() -> anyhow::Result<()> {
    // Default to `info`-level progress output on stderr (env_logger's own
    // default is error-only, which meant `--pr`/`--base` runs — the ones
    // slow enough to want a heartbeat, see the dependency-index build
    // below — gave no feedback at all while running). `RUST_LOG` still
    // overrides this, same as any other `env_logger::Builder::from_env`
    // setup.
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
    let cli = Cli::parse();

    if let Some(Command::SelfUpdate { yes }) = cli.command {
        return self_update::run_self_update(yes);
    }

    let report = if let Some(pr_arg) = &cli.pr {
        // Validate the arg and derive the fetch refspec's PR number, but
        // pass the original (trimmed) value — not the parsed number — to
        // `gh pr view` (see that function's doc comment for why).
        let parsed = parse_pr_arg(pr_arg)?;
        let number = parsed.number();
        let workdir = resolve_pr_workdir(&parsed)?;
        log::info!("resolving PR #{number} via gh");
        let pr_info = fetch_pr_info(pr_arg.trim())?;
        let cwd = workdir.as_deref();
        log::info!("fetching PR #{number} head");
        let head_sha = fetch_pr_head(number, cwd)?;
        if head_sha != pr_info.head_ref_oid {
            anyhow::bail!(
                "fetched PR #{number} head ({head_sha}) does not match `gh`'s reported head \
                 ({expected}); this usually means the PR belongs to a different repository than \
                 the target clone's `origin` remote, or the PR was updated between resolving it \
                 and fetching it — verify `origin` points at the PR's repository and re-run",
                expected = pr_info.head_ref_oid,
            );
        }
        log::info!("resolving PR #{number} base commit");
        let (base_sha, used_fallback) = resolve_pr_base_sha(
            &pr_info.base_ref_oid,
            |oid| object_exists_locally(cwd, oid),
            || fetch_branch_head(&pr_info.base_ref_name, cwd),
            |oid| fetch_oid(cwd, oid),
        )?;
        if used_fallback {
            log::warn!(
                "could not resolve PR #{number}'s base commit ({base_oid}) locally; falling \
                 back to the current tip of {base_branch}, which may not reproduce the original \
                 PR diff for a merged PR",
                base_oid = pr_info.base_ref_oid,
                base_branch = pr_info.base_ref_name,
            );
        }
        run_base_pipeline(&cli, &base_sha, &head_sha, cwd)?
    } else if let Some(base) = &cli.base {
        run_base_pipeline(&cli, base, &cli.head, None)?
    } else {
        let diff_text = read_stdin_diff()?;
        if diff_text.trim().is_empty() {
            eprintln!("note: diff is empty, nothing to analyze");
        }
        let resolver = build_resolver(&cli, &diff_text, read_working_tree_file, None, None)?;
        log::info!("analyzing diff");
        let report = analyze_diff(
            &diff_text,
            read_working_tree_file,
            resolver
                .as_ref()
                .map(|r| r as &dyn rinkaku_core::deps::Resolver),
        )?;
        if let Some(note) = garbage_input_note(&diff_text, &report) {
            eprintln!("{note}");
        }
        report
    };

    let output = render(&report, cli.format.into())?;
    print!("{output}");

    Ok(())
}

/// Determines which repository `--pr` mode should run its `git` commands
/// in, and clones one into the cache if needed. Probes in order (ADR
/// 0006): (1) the current directory, (2) a ghq-managed clone, (3) the
/// cache clone (ADR 0005).
///
/// `PrArg::Number` always uses the process's current directory (`None`,
/// meaning "no override" to the `cwd` parameters downstream) — a bare
/// number carries no repository information, so ADR 0004's "run inside a
/// local clone" requirement is unchanged for it.
///
/// `PrArg::Url` first checks whether the current directory is already a
/// clone of that repository (`git remote get-url origin` matching
/// `owner`/`repo`, case-insensitively via `github_remote_matches`); if so
/// it also returns `None`, reusing the cwd exactly like `PrArg::Number`
/// does today. Otherwise it asks `ghq list --full-path --exact
/// <owner>/<repo>` for candidate clones (`ghq_candidate_clones`) and
/// picks the first whose real origin matches (`select_matching_clone`,
/// resolving each candidate's origin via `git_remote_origin_url`); ghq
/// being absent, erroring, or returning only non-matching clones all
/// fall through silently to this step returning `None` (per ADR 0006 —
/// `ghq_candidate_clones` already logs the reason at debug level). Only
/// if neither the cwd nor a ghq clone matches does it fall back to the
/// per-repository cache directory (`cache_repo_dir`, reading the real
/// environment here at the boundary) and clone into it if it doesn't
/// exist yet — an existing cache entry, like a discovered ghq clone, is
/// left alone here and refreshed by the `git fetch` calls `main` makes
/// afterwards, not re-cloned.
fn resolve_pr_workdir(parsed: &PrArg) -> anyhow::Result<Option<std::path::PathBuf>> {
    let PrArg::Url { owner, repo, .. } = parsed else {
        return Ok(None);
    };

    if let Some(origin) = git_remote_origin_url(None)?
        && github_remote_matches(&origin, owner, repo)
    {
        log::info!("using the current directory as a clone of {owner}/{repo}");
        return Ok(None);
    }

    let ghq_candidates = ghq_candidate_clones(owner, repo);
    if let Some(discovered) = select_matching_clone(
        &ghq_candidates,
        |path| git_remote_origin_url(Some(path)).ok().flatten(),
        owner,
        repo,
    ) {
        log::info!(
            "using ghq-managed clone of {owner}/{repo} at {}",
            discovered.display()
        );
        return Ok(Some(discovered));
    }

    let dir = cache_repo_dir(
        std::env::var("RINKAKU_CACHE_DIR").ok().as_deref(),
        std::env::var("XDG_CACHE_HOME").ok().as_deref(),
        std::env::var("HOME").ok().as_deref(),
        owner,
        repo,
    )?;
    if !dir.exists() {
        // Create the parent (`.../repos/github.com/<owner>/`) only, not
        // `dir` itself: `gh repo clone` (like `git clone`) creates its
        // destination directory and fails if it already exists.
        std::fs::create_dir_all(dir.parent().unwrap_or(&dir)).map_err(|source| {
            anyhow::anyhow!(
                "failed to create cache directory for {}: {source}",
                dir.display()
            )
        })?;
        log::info!(
            "cloning {owner}/{repo} into cache at {} (first run against this repository)",
            dir.display()
        );
        clone_repo_into_cache(owner, repo, &dir)?;
    } else {
        log::info!("using cache clone of {owner}/{repo} at {}", dir.display());
    }
    Ok(Some(dir))
}

/// Runs `git diff <base>...<head>` and analyzes the result, reading file
/// content via `git show <head>:<path>` (ADR: keeps the diff and file
/// reads pinned to the same commit regardless of the working tree's
/// state). Shared by `--base` mode (`base`/`head` are the ref strings the
/// user passed) and `--pr` mode (`base`/`head` are the SHAs resolved and
/// fetched from the PR, see ADR 0004) — `--pr` is a resolution step in
/// front of this same pipeline, not a separate read strategy.
///
/// An empty (or whitespace-only) diff — most commonly a `--base`/`--pr`
/// range with no actual changes, e.g. `base == head` — returns the empty
/// `Report` immediately, printing the same "diff is empty" note the stdin
/// path prints, and **without calling `build_resolver`**: indexing every
/// tracked file for dependency resolution is pointless work when there is
/// nothing to resolve dependencies for, and on a large repository it is
/// also the single slowest part of a run (one `git show`/`cat-file` per
/// tracked file). A non-empty diff that nonetheless yields zero entries
/// (garbage input) still gets its own note via `garbage_input_note` after
/// the full pipeline runs, same as stdin mode.
///
/// `cwd` selects which repository every subprocess in this call runs in
/// (same rationale as `read_git_show_file`'s `cwd`: `None` uses the
/// process's current directory for `--base` and cwd-clone `--pr` runs,
/// `Some(dir)` targets a cache clone (ADR 0005) or a test fixture).
fn run_base_pipeline(
    cli: &Cli,
    base: &str,
    head: &str,
    cwd: Option<&std::path::Path>,
) -> anyhow::Result<rinkaku_core::render::Report> {
    log::info!("diffing {base}...{head}");
    let diff_text = run_git_diff(base, head, cwd)?;
    if diff_text.trim().is_empty() {
        eprintln!("note: diff is empty, nothing to analyze");
        return Ok(rinkaku_core::render::Report {
            files: Vec::new(),
            skipped: Vec::new(),
        });
    }

    let read_file = {
        let head = head.to_string();
        move |path: &str| read_git_show_file(cwd, &head, path)
    };
    let resolver = build_resolver(cli, &diff_text, &read_file, Some(head), cwd)?;
    log::info!("analyzing diff");
    let report = analyze_diff(
        &diff_text,
        read_file,
        resolver
            .as_ref()
            .map(|r| r as &dyn rinkaku_core::deps::Resolver),
    )?;
    if let Some(note) = garbage_input_note(&diff_text, &report) {
        eprintln!("{note}");
    }
    Ok(report)
}

/// Returns a warning note for stdin input that is garbage rather than a
/// unified diff — non-empty input that nonetheless produced zero
/// recognized file entries (`parse_unified_diff` never errors on
/// unrecognized text, it simply finds nothing to report, see `diff.rs`),
/// which would otherwise silently exit 0 with an empty report and no
/// indication anything went wrong. `None` when `diff_text` is empty or
/// whitespace-only (already covered by the separate "diff is empty" note
/// at the call site — the two notes are mutually exclusive) or when the
/// report has any file or skip entry at all.
fn garbage_input_note(
    diff_text: &str,
    report: &rinkaku_core::render::Report,
) -> Option<&'static str> {
    if diff_text.trim().is_empty() {
        return None;
    }
    if !report.files.is_empty() || !report.skipped.is_empty() {
        return None;
    }
    Some("note: no file changes recognized in input; expected a unified diff")
}

/// Builds the `TagsResolver` used for `--deps 1` (the default), or `None`
/// when `--deps 0` skips dependency resolution entirely.
///
/// Indexes every file `git ls-files` reports as tracked — untracked files
/// are excluded by construction (not merely `.gitignore`-filtered, since
/// `ls-files` only ever lists tracked paths in the first place) — so the
/// index only ever contains content the repository actually owns.
///
/// Before indexing, `diff_text` is parsed once (via
/// `pipeline::collect_referenced_names`, reading changed files through
/// `diff_read_file`) to compute the set of names any changed symbol
/// actually references. That set drives `TagsResolver::new`'s prefilter:
/// only tracked files whose content could plausibly contain one of those
/// names get parsed at all (see `deps.rs`'s performance doc comment for
/// why this cannot lose recall). This re-parses the diff and re-reads
/// changed files a second time (`analyze_diff` does its own pass over the
/// same diff right after `build_resolver` returns) — accepted the same
/// way `analyze_diff`'s doc comment already accepts `TagsResolver::new`
/// parsing changed files a second time for its index.
///
/// `head`, when `Some`, matches `--base` mode's read strategy: file
/// content is read via a single `git cat-file --batch` process
/// (`read_git_show_files_batch` — one process for every tracked file,
/// rather than one `git show` subprocess per file) so the index and the
/// diff being analyzed are consistent with the same commit regardless of
/// the working tree's state (same rationale as `read_git_show_file`,
/// applied here to the whole repo rather than just the changed files).
/// `cwd` selects the repository `list_git_files` runs `git ls-files` in
/// (same rationale as `read_git_show_file`'s `cwd`: `None` uses the
/// process's current directory for production callers, `Some(dir)` pins
/// it for tests). Only reached when `cli.deps != 0` — the `deps == 0`
/// branch returns before doing any repository scan at all, verified by
/// `should_skip_git_ls_files_when_deps_is_zero` below (pointing `cwd` at
/// a directory with no git repository would make `list_git_files` fail,
/// so a passing `Ok(None)` there is proof the scan never ran).
fn build_resolver(
    cli: &Cli,
    diff_text: &str,
    diff_read_file: impl Fn(&str) -> std::io::Result<String>,
    head: Option<&str>,
    cwd: Option<&std::path::Path>,
) -> anyhow::Result<Option<TagsResolver>> {
    if cli.deps == 0 {
        return Ok(None);
    }

    let reference_names =
        rinkaku_core::pipeline::collect_referenced_names(diff_text, diff_read_file)?;

    let paths = list_git_files(cwd)?;
    log::info!(
        "building dependency index over {} tracked files",
        paths.len()
    );
    let files: Vec<(String, String)> = match head {
        // One `git cat-file --batch` child process serves every path
        // (see `read_git_show_files_batch`'s doc comment for why this
        // replaces a `git show` subprocess per file). A single
        // unresolvable path is isolated inside that call (same
        // best-effort skip as the working-tree branch below); the `?`
        // here only ever fires for a genuinely unrecoverable failure
        // (the child process itself failing to start, or the batch
        // stream desyncing), which cannot be isolated to one path.
        Some(head) => read_git_show_files_batch(cwd, head, paths)?,
        None => paths
            .into_iter()
            .filter_map(|path| {
                // A file listed by `git ls-files` can still fail to read
                // (e.g. deleted in the working tree but not yet staged, a
                // submodule gitlink entry) — skipped rather than failing
                // the whole run, since the resolver's index is a
                // best-effort aid, not a correctness-critical input.
                read_working_tree_file(&path)
                    .ok()
                    .map(|content| (path, content))
            })
            .collect(),
    };
    Ok(Some(TagsResolver::new(
        files,
        language_for_path,
        &reference_names,
    )))
}

/// Lists every file tracked by git in `cwd` (or the process's current
/// directory when `None`) via `git ls-files`.
fn list_git_files(cwd: Option<&std::path::Path>) -> anyhow::Result<Vec<String>> {
    let mut command = std::process::Command::new("git");
    command.args(["ls-files"]);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let output = command.output()?;
    if !output.status.success() {
        anyhow::bail!(
            "git ls-files failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(String::from_utf8(output.stdout)?
        .lines()
        .map(str::to_string)
        .collect())
}

/// Reads the diff from stdin. Errors with a clear message if stdin is a
/// terminal (interactive), since there is nothing to read in that case and
/// `--base` should be used instead.
fn read_stdin_diff() -> anyhow::Result<String> {
    if std::io::stdin().is_terminal() {
        anyhow::bail!(
            "no diff input: pipe a diff via stdin (e.g. `gh pr diff 123 | rinkaku`) or pass --base <ref>"
        );
    }
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf)?;
    Ok(buf)
}

/// Runs `git diff <base>...<head>` and returns its stdout.
///
/// `cwd` selects the repository to run `git` in; `None` uses the process's
/// current directory (production `--base`/cwd-clone `--pr` callers),
/// `Some(dir)` pins it (cache clones, tests).
fn run_git_diff(base: &str, head: &str, cwd: Option<&std::path::Path>) -> anyhow::Result<String> {
    let range = format!("{base}...{head}");
    let mut command = std::process::Command::new("git");
    command.args(["diff", &range]);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let output = command.output()?;
    if !output.status.success() {
        anyhow::bail!(
            "git diff {range} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(String::from_utf8(output.stdout)?)
}

/// The subset of `gh pr view --json number,baseRefName,baseRefOid,
/// headRefOid` this binary needs to drive `--pr` mode (ADR 0004, ADR
/// 0007): which PR, what its base branch is called (fallback path),
/// the commit its base was pinned to at PR time (`base_ref_oid`,
/// preferred — see ADR 0007), and the exact commit its head is expected
/// to be at (checked against what `git fetch` actually retrieves, see
/// `main`'s mismatch check).
#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
struct PrInfo {
    number: u64,
    #[serde(rename = "baseRefName")]
    base_ref_name: String,
    #[serde(rename = "baseRefOid")]
    base_ref_oid: String,
    #[serde(rename = "headRefOid")]
    head_ref_oid: String,
}

/// A validated `--pr` argument. `Url` carries `owner`/`repo` (not just the
/// PR number) so callers can decide, per ADR 0005, whether the current
/// directory's clone matches the PR's repository or a cache clone is
/// needed — information a bare `Number` inherently cannot provide, which
/// is exactly why `Number` still requires running inside a local clone.
#[derive(Debug, Clone, PartialEq, Eq)]
enum PrArg {
    Number(u64),
    Url {
        owner: String,
        repo: String,
        number: u64,
    },
}

impl PrArg {
    /// The PR number, regardless of which variant this is. Used to build
    /// the `refs/pull/<number>/head` fetch refspec, which only needs the
    /// number even for `Url`.
    fn number(&self) -> u64 {
        match self {
            PrArg::Number(number) => *number,
            PrArg::Url { number, .. } => *number,
        }
    }
}

/// Extracts a validated `--pr` argument: either a bare number (`"76"`) or
/// a GitHub PR URL
/// (`https://github.com/<owner>/<repo>/pull/<number>`, tolerating a
/// trailing slash or extra path segments like `/files`).
///
/// `0` is rejected even though it parses as a `u64`: GitHub PR numbers
/// are 1-indexed, so `0` can only be a typo, and failing fast here beats
/// a confusing `gh pr view 0` error downstream.
fn parse_pr_arg(value: &str) -> anyhow::Result<PrArg> {
    match value.trim().strip_prefix("https://github.com/") {
        Some(rest) => {
            // Expect `<owner>/<repo>/pull/<number>[/...]`.
            let segments: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
            match segments.as_slice() {
                [owner, repo, "pull", number, ..] => Ok(PrArg::Url {
                    owner: owner.to_string(),
                    repo: repo.to_string(),
                    number: parse_positive_pr_number(number, value)?,
                }),
                _ => anyhow::bail!(
                    "--pr URL must look like https://github.com/<owner>/<repo>/pull/<number>, \
                     got: {value}"
                ),
            }
        }
        None => Ok(PrArg::Number(parse_positive_pr_number(
            value.trim(),
            value,
        )?)),
    }
}

/// Parses `candidate` as a positive `u64` PR number, reporting errors
/// against the original (untrimmed/un-extracted) `--pr` value so the user
/// sees what they actually typed.
fn parse_positive_pr_number(candidate: &str, original_value: &str) -> anyhow::Result<u64> {
    let number: u64 = candidate.parse().map_err(|_| {
        anyhow::anyhow!("--pr must be a PR number or a GitHub PR URL, got: {original_value}")
    })?;
    if number == 0 {
        anyhow::bail!("--pr must be a positive PR number, got: {original_value}");
    }
    Ok(number)
}

/// Extracts `(owner, repo)` from a git remote URL, if it points at
/// GitHub. Accepts the forms `git remote get-url` can return for a GitHub
/// remote: `https://github.com/<owner>/<repo>`, the same with a `.git`
/// suffix, the scp-like SSH form `git@github.com:<owner>/<repo>(.git)`,
/// and the explicit `ssh://` form `ssh://git@github.com/<owner>/<repo>
/// (.git)`. Any other host, or a string that doesn't parse as one of
/// these forms, yields `None` — used by `main` to decide whether the
/// current directory's `origin` matches a `--pr` URL's repository (ADR
/// 0005), where "not GitHub" and "malformed" are both simply "no match".
fn parse_github_remote(url: &str) -> Option<(String, String)> {
    let url = url.trim();
    let rest = url
        .strip_prefix("https://github.com/")
        .or_else(|| url.strip_prefix("ssh://git@github.com/"))
        .or_else(|| url.strip_prefix("git@github.com:"))?;
    let rest = rest.strip_suffix(".git").unwrap_or(rest);

    let segments: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
    match segments.as_slice() {
        [owner, repo] => Some((owner.to_string(), repo.to_string())),
        _ => None,
    }
}

/// Whether `remote_url` (as returned by `git remote get-url origin`)
/// points at the same GitHub repository as `owner`/`repo`. GitHub
/// owner/repo names are case-insensitive, so the comparison is too — a
/// clone whose `origin` is `.../Octocat/Hello-World` must still be
/// recognized as matching a `--pr` URL spelled `.../octocat/hello-world`.
/// A `remote_url` that isn't a GitHub remote at all (`parse_github_remote`
/// returns `None`) never matches.
fn github_remote_matches(remote_url: &str, owner: &str, repo: &str) -> bool {
    match parse_github_remote(remote_url) {
        Some((remote_owner, remote_repo)) => {
            remote_owner.eq_ignore_ascii_case(owner) && remote_repo.eq_ignore_ascii_case(repo)
        }
        None => false,
    }
}

/// Resolves the root cache directory for `--pr` URL auto-clones (ADR
/// 0005), then the per-repository clone path under it.
///
/// Precedence for the root, evaluated in order: `rinkaku_cache_dir`
/// (`$RINKAKU_CACHE_DIR`) if set, else `<xdg_cache_home>/rinkaku`
/// (`$XDG_CACHE_HOME/rinkaku`) if set, else `<home>/.cache/rinkaku`. An
/// error if none of the three inputs is available — there is then no
/// sane place to put the cache. All three are taken as arguments rather
/// than read from the environment here, so this stays a pure function the
/// precedence order can be unit-tested against directly; `main` is the
/// only place that reads the actual environment.
///
/// Repo layout under the root: `repos/github.com/<owner>/<repo>`, so
/// different git hosts (a future extension) could share one cache root
/// without path collisions, and so the cache directory's own contents
/// read as self-explanatory if a user goes looking (`~/.cache/rinkaku/
/// repos/github.com/octocat/hello-world`).
fn cache_repo_dir(
    rinkaku_cache_dir: Option<&str>,
    xdg_cache_home: Option<&str>,
    home: Option<&str>,
    owner: &str,
    repo: &str,
) -> anyhow::Result<std::path::PathBuf> {
    let root = if let Some(dir) = rinkaku_cache_dir {
        std::path::PathBuf::from(dir)
    } else if let Some(dir) = xdg_cache_home {
        std::path::PathBuf::from(dir).join("rinkaku")
    } else if let Some(dir) = home {
        std::path::PathBuf::from(dir).join(".cache").join("rinkaku")
    } else {
        anyhow::bail!(
            "cannot determine a cache directory for --pr: set $RINKAKU_CACHE_DIR, \
             $XDG_CACHE_HOME, or $HOME"
        );
    };
    Ok(root.join("repos").join("github.com").join(owner).join(repo))
}

/// Parses `gh pr view --json number,baseRefName,baseRefOid,headRefOid`'s
/// stdout. Split out from `fetch_pr_info` so the JSON shape can be
/// unit-tested without shelling out to `gh`.
fn parse_pr_view_json(json: &str) -> anyhow::Result<PrInfo> {
    Ok(serde_json::from_str(json)?)
}

/// Runs `gh pr view <arg> --json number,baseRefName,baseRefOid,headRefOid`
/// and parses the result.
///
/// Takes the user's original `--pr` argument (URL or bare number) rather
/// than the number `parse_pr_arg` extracts from it, and this is load-bearing
/// rather than cosmetic: `gh pr view <number>` always resolves against the
/// *current directory's* repository, ignoring any owner/repo encoded in a
/// URL the user passed. If it were fed only the number, `--pr
/// https://github.com/other/repo/pull/5` run inside an unrelated clone
/// would silently resolve and analyze that clone's own PR #5. Passing the
/// full URL through lets `gh` itself resolve against the URL's repository,
/// so a foreign-repo URL makes `gh` report a `headRefOid` that the
/// cwd-scoped `git fetch origin refs/pull/<n>/head` in `main` cannot
/// possibly match — the mismatch check there is what actually surfaces the
/// error, and it only works if `gh` and `git` are allowed to disagree on
/// which repository they resolved against.
fn fetch_pr_info(arg: &str) -> anyhow::Result<PrInfo> {
    let output = std::process::Command::new("gh")
        .args([
            "pr",
            "view",
            arg,
            "--json",
            "number,baseRefName,baseRefOid,headRefOid",
        ])
        .output()?;
    if !output.status.success() {
        anyhow::bail!(
            "gh pr view {arg} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    parse_pr_view_json(&String::from_utf8(output.stdout)?)
}

/// Fetches PR `number`'s head ref into the repository at `cwd` and
/// returns the fetched commit's SHA, via
/// `git fetch origin refs/pull/<number>/head` followed by
/// `git rev-parse FETCH_HEAD`.
fn fetch_pr_head(number: u64, cwd: Option<&std::path::Path>) -> anyhow::Result<String> {
    run_git_fetch(&format!("refs/pull/{number}/head"), cwd)
}

/// Fetches branch `name` into the repository at `cwd` and returns the
/// fetched commit's SHA. Used to resolve `--pr` mode's base commit from
/// the base branch name `gh pr view` reports.
fn fetch_branch_head(name: &str, cwd: Option<&std::path::Path>) -> anyhow::Result<String> {
    run_git_fetch(name, cwd)
}

/// Resolves `--pr` mode's diff base commit following ADR 0007's
/// availability cascade, preferring `base_ref_oid` (pinned to the PR-time
/// base, correct for both open and merged PRs) over the base branch's
/// current tip (correct only for open PRs, since a merged PR's base
/// branch has since advanced past it).
///
/// Cascade, each step only taken if the previous one didn't already
/// resolve `base_ref_oid` locally:
///
/// 1. `object_exists` (`git cat-file -e <oid>^{commit}`) — already have it.
/// 2. `fetch_base_branch` (`git fetch origin <base_ref_name>`, returning
///    the fetched tip's SHA) then re-check `object_exists` — an ordinary
///    branch fetch usually retrieves it, since `base_ref_oid` is normally
///    reachable from the base branch's history. A failure here (e.g. the
///    base branch was deleted after the PR merged, or renamed) is soft:
///    `log::warn!` and fall through to step 3 rather than aborting the
///    whole run — step 3 is exactly the recovery path for a base branch
///    that no longer leads to `base_ref_oid`, so a step-2 failure must not
///    short-circuit past it.
/// 3. `fetch_oid` (`git fetch origin <oid>`) then re-check `object_exists`
///    — covers a base branch that has since been force-pushed past it,
///    renamed, or deleted (including the case where step 2 itself failed
///    to fetch at all).
/// 4. Fall back to the base branch's tip with `used_fallback` signaling
///    the caller should warn — the commit is unreachable by any means
///    available, so this degrades rather than fails the whole run. Reuses
///    step 2's fetched tip when step 2 succeeded, rather than fetching the
///    same branch a second time; only calls `fetch_base_branch` again here
///    if step 2 itself failed (so there is no tip yet to reuse).
///
/// Every IO step is injected as a closure so this decision logic is
/// unit-testable without shelling out to `git`, following the same
/// pattern as `select_matching_clone` elsewhere in this file.
///
/// Returns the resolved SHA and whether the fallback (step 4) was used.
fn resolve_pr_base_sha(
    base_ref_oid: &str,
    mut object_exists: impl FnMut(&str) -> bool,
    mut fetch_base_branch: impl FnMut() -> anyhow::Result<String>,
    mut fetch_oid: impl FnMut(&str) -> anyhow::Result<()>,
) -> anyhow::Result<(String, bool)> {
    if object_exists(base_ref_oid) {
        return Ok((base_ref_oid.to_string(), false));
    }

    let branch_tip = match fetch_base_branch() {
        Ok(tip) => {
            if object_exists(base_ref_oid) {
                return Ok((base_ref_oid.to_string(), false));
            }
            Some(tip)
        }
        Err(source) => {
            log::warn!(
                "fetching the base branch failed, continuing the base-commit resolution \
                 cascade: {source}"
            );
            None
        }
    };

    if fetch_oid(base_ref_oid).is_ok() && object_exists(base_ref_oid) {
        return Ok((base_ref_oid.to_string(), false));
    }

    let branch_tip = match branch_tip {
        Some(tip) => tip,
        None => fetch_base_branch()?,
    };
    Ok((branch_tip, true))
}

/// Runs `git cat-file -e <oid>^{commit}` in `cwd`, i.e. whether `oid`
/// already exists locally as a commit object — the cheap first check in
/// `resolve_pr_base_sha`'s cascade, run before attempting any fetch.
fn object_exists_locally(cwd: Option<&std::path::Path>, oid: &str) -> bool {
    let mut command = std::process::Command::new("git");
    command.args(["cat-file", "-e", &format!("{oid}^{{commit}}")]);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    command.output().is_ok_and(|output| output.status.success())
}

/// Runs `git fetch origin <oid>` in `cwd` — the direct-oid step of
/// `resolve_pr_base_sha`'s cascade, tried only when the base branch itself
/// (already fetched by the caller) didn't bring the commit in, e.g. after
/// a force-push past it. Unlike `run_git_fetch`, this doesn't need
/// `FETCH_HEAD` afterwards: the caller re-checks `object_exists_locally`
/// instead, since fetching a bare oid doesn't update any ref.
fn fetch_oid(cwd: Option<&std::path::Path>, oid: &str) -> anyhow::Result<()> {
    let mut command = std::process::Command::new("git");
    command.args(["fetch", "origin", oid]);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let output = command.output()?;
    if !output.status.success() {
        anyhow::bail!(
            "git fetch origin {oid} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(())
}

/// Runs `git fetch origin <refspec>` then `git rev-parse FETCH_HEAD` in
/// the repository at `cwd`, returning the resulting SHA. Shared by
/// `fetch_pr_head` and `fetch_branch_head`, which differ only in what
/// refspec they fetch.
///
/// `cwd` selects the repository to run `git` in; `None` uses the
/// process's current directory (production cwd-clone callers),
/// `Some(dir)` pins it (cache clones, tests) — same rationale as
/// `read_git_show_file`'s `cwd`.
fn run_git_fetch(refspec: &str, cwd: Option<&std::path::Path>) -> anyhow::Result<String> {
    let mut fetch_command = std::process::Command::new("git");
    fetch_command.args(["fetch", "origin", refspec]);
    if let Some(cwd) = cwd {
        fetch_command.current_dir(cwd);
    }
    let fetch_output = fetch_command.output()?;
    if !fetch_output.status.success() {
        anyhow::bail!(
            "git fetch origin {refspec} failed: {}",
            String::from_utf8_lossy(&fetch_output.stderr)
        );
    }

    let mut rev_parse_command = std::process::Command::new("git");
    rev_parse_command.args(["rev-parse", "FETCH_HEAD"]);
    if let Some(cwd) = cwd {
        rev_parse_command.current_dir(cwd);
    }
    let rev_parse_output = rev_parse_command.output()?;
    if !rev_parse_output.status.success() {
        anyhow::bail!(
            "git rev-parse FETCH_HEAD failed after fetching {refspec}: {}",
            String::from_utf8_lossy(&rev_parse_output.stderr)
        );
    }
    Ok(String::from_utf8(rev_parse_output.stdout)?
        .trim()
        .to_string())
}

/// Runs `git remote get-url origin` in `cwd` (or the process's current
/// directory when `None`) and returns its stdout, trimmed. `Ok(None)`
/// (rather than an `Err`) when the command fails — not being inside a git
/// repository, or a repository with no `origin` remote, are both
/// expected, ordinary situations for `--pr` URL mode (ADR 0005): they
/// simply mean "the current directory doesn't match, use the cache"
/// rather than a fatal error worth surfacing to the user.
fn git_remote_origin_url(cwd: Option<&std::path::Path>) -> anyhow::Result<Option<String>> {
    let mut command = std::process::Command::new("git");
    command.args(["remote", "get-url", "origin"]);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let output = command.output()?;
    if !output.status.success() {
        return Ok(None);
    }
    Ok(Some(String::from_utf8(output.stdout)?.trim().to_string()))
}

/// Clones `owner/repo` as a blobless partial clone (`--filter=blob:none`,
/// ADR 0005) into `dir` via `gh repo clone`, delegating authentication to
/// `gh` (ADR 0004's stance, applied to cloning too). Only called when
/// `dir` does not already exist — an existing cache entry is refreshed by
/// the ordinary `git fetch` calls in `main` instead of being re-cloned.
fn clone_repo_into_cache(owner: &str, repo: &str, dir: &std::path::Path) -> anyhow::Result<()> {
    let slug = format!("{owner}/{repo}");
    let output = std::process::Command::new("gh")
        .args([
            "repo",
            "clone",
            &slug,
            &dir.to_string_lossy(),
            "--",
            "--filter=blob:none",
        ])
        .output()?;
    if !output.status.success() {
        anyhow::bail!(
            "gh repo clone {slug} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(())
}

/// Parses `ghq list --full-path --exact <owner>/<repo>`'s stdout into
/// candidate clone paths: one per non-blank line, trimmed. `ghq` prints
/// one absolute path per line and nothing else on success, but blank
/// lines (a trailing newline, or possibly a stray empty line) are
/// filtered out defensively rather than turned into a bogus empty-path
/// candidate.
fn parse_ghq_list_output(stdout: &str) -> Vec<std::path::PathBuf> {
    stdout
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(std::path::PathBuf::from)
        .collect()
}

/// Runs `ghq list --full-path --exact <owner>/<repo>` and returns the
/// candidate clone paths it reports (ADR 0006's ghq-discovery probe,
/// step 2 between the cwd check and the cache fallback).
///
/// Always returns an empty `Vec` rather than an `Err` — never a fatal
/// error for `--pr` mode — for every way this can fail to find a usable
/// clone: `ghq` missing from `PATH` (`Command::output` fails with
/// `io::ErrorKind::NotFound`), a non-zero exit (e.g. `ghq` installed but
/// its own config is broken), or a zero exit with no matching clones.
/// ADR 0006 is explicit that all of these "fall through silently to the
/// cache"; a `log::debug!` records which case fired, for anyone who wants
/// to know why a clone wasn't discovered without it being an error.
fn ghq_candidate_clones(owner: &str, repo: &str) -> Vec<std::path::PathBuf> {
    let slug = format!("{owner}/{repo}");
    let output = match std::process::Command::new("ghq")
        .args(["list", "--full-path", "--exact", &slug])
        .output()
    {
        Ok(output) => output,
        Err(source) => {
            log::debug!("ghq not runnable, falling back to cache for {slug}: {source}");
            return Vec::new();
        }
    };
    if !output.status.success() {
        log::debug!(
            "ghq list {slug} exited non-zero, falling back to cache: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        return Vec::new();
    }
    match String::from_utf8(output.stdout) {
        Ok(stdout) => parse_ghq_list_output(&stdout),
        Err(source) => {
            log::debug!(
                "ghq list {slug} produced non-UTF-8 output, falling back to cache: {source}"
            );
            Vec::new()
        }
    }
}

/// Picks the first of `candidates` whose origin (resolved by the injected
/// `origin_of` port) matches `owner`/`repo` per `github_remote_matches`.
/// `None` if `candidates` is empty or none of them match.
///
/// `origin_of` is injected — production wires it to
/// `|path| git_remote_origin_url(Some(path)).ok().flatten()`, tests wire
/// it to an in-memory map — so this selection logic is unit-testable
/// without shelling out to `git`, following the same read-file-port style
/// as `analyze_diff`/`build_resolver` elsewhere in this file.
fn select_matching_clone(
    candidates: &[std::path::PathBuf],
    origin_of: impl Fn(&std::path::Path) -> Option<String>,
    owner: &str,
    repo: &str,
) -> Option<std::path::PathBuf> {
    candidates
        .iter()
        .find(|candidate| {
            origin_of(candidate).is_some_and(|origin| github_remote_matches(&origin, owner, repo))
        })
        .cloned()
}

/// Reads a changed file's new-side content off the working tree.
fn read_working_tree_file(path: &str) -> std::io::Result<String> {
    std::fs::read_to_string(path)
}

/// Reads a changed file's content as committed at `head`, via
/// `git show <head>:<path>`. Used in `--base` mode so the content read
/// always matches the commit the diff was generated against, independent
/// of the working tree's current state.
///
/// `cwd` selects the repository to run `git` in; `None` uses the process's
/// current directory (production callers), `Some(dir)` pins it to a
/// specific directory (tests, so they don't depend on or mutate the
/// process-wide current directory).
fn read_git_show_file(
    cwd: Option<&std::path::Path>,
    head: &str,
    path: &str,
) -> std::io::Result<String> {
    let object = format!("{head}:{path}");
    let mut command = std::process::Command::new("git");
    command.args(["show", &object]);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let output = command.output()?;
    if !output.status.success() {
        return Err(std::io::Error::other(format!(
            "git show {object} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        )));
    }
    String::from_utf8(output.stdout)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}

/// Reads every path in `paths` at `head` (`git show <head>:<path>`'s
/// content, for each path) via a single long-lived `git cat-file --batch`
/// child process, instead of spawning one `git show` subprocess per path
/// (`read_git_show_file`'s approach — fine for the handful of files a diff
/// actually changes, but prohibitively slow for `build_resolver`'s
/// repository-wide index, which reads every tracked file: a repository
/// with a few thousand tracked files previously meant a few thousand
/// process spawns just to build the dependency index).
///
/// Protocol: `git cat-file --batch` reads `<object>\n` requests from
/// stdin and writes a response to stdout per request, documented in
/// `git help cat-file`'s BATCH OUTPUT section — mainly the "found" shape
/// (`<oid> <type> <size>\n` followed by exactly `size` content bytes and
/// a trailing `\n`) and several single-line, no-content shapes
/// (`<object> missing`, `<object> ambiguous`, `<oid> submodule`, ...);
/// see `read_cat_file_batch_response`'s doc comment for exactly which
/// shapes are treated as "skip this path" versus a hard failure.
///
/// Requests and responses are sent one at a time (write a request, then
/// immediately read its response) rather than writing every request up
/// front: `git cat-file --batch`'s stdout is a pipe with a bounded OS
/// buffer, and with ~thousands of paths the parent could deadlock writing
/// requests while the child blocks trying to write responses into an
/// already-full pipe that nobody is draining. One-at-a-time interleaving
/// avoids that entirely while still cutting the process count from one
/// per file to exactly one for the whole index — the actual cost this
/// change targets. stderr is drained concurrently on a dedicated thread
/// for the same reason (see the inline comment where it's spawned) — a
/// verbose enough diagnostic on stderr could otherwise fill that pipe too
/// and deadlock the same way.
fn read_git_show_files_batch(
    cwd: Option<&std::path::Path>,
    head: &str,
    paths: Vec<String>,
) -> anyhow::Result<Vec<(String, String)>> {
    let mut command = std::process::Command::new("git");
    command
        .args(["cat-file", "--batch"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let mut child = command
        .spawn()
        .map_err(|source| anyhow::anyhow!("failed to start git cat-file --batch: {source}"))?;
    let mut stdin = child
        .stdin
        .take()
        .expect("stdin is piped, so it must be present");
    let stdout = child
        .stdout
        .take()
        .expect("stdout is piped, so it must be present");
    let stderr = child
        .stderr
        .take()
        .expect("stderr is piped, so it must be present");
    let mut reader = std::io::BufReader::new(stdout);

    // Drained on a dedicated thread rather than read after `wait()`: this
    // call writes/reads stdin and stdout on the main thread in lockstep,
    // so nothing here would otherwise ever read stderr. If `git` writes
    // enough diagnostics to fill the OS pipe buffer, the child would block
    // writing to stderr while this thread blocks reading stdout — an
    // indefinite mutual stall neither side can break out of. A concurrent
    // reader keeps that pipe draining regardless of what the main thread
    // is doing.
    let stderr_reader = std::thread::spawn(move || {
        let mut stderr = stderr;
        let mut buf = Vec::new();
        let _ = stderr.read_to_end(&mut buf);
        buf
    });

    let mut files = Vec::with_capacity(paths.len());
    for path in paths {
        let object = format!("{head}:{path}");
        writeln!(stdin, "{object}").map_err(|source| {
            anyhow::anyhow!("failed to write to git cat-file --batch: {source}")
        })?;
        stdin.flush().map_err(|source| {
            anyhow::anyhow!("failed to flush git cat-file --batch stdin: {source}")
        })?;

        match read_cat_file_batch_response(&mut reader, &object)? {
            Some(content) => files.push((path, content)),
            None => continue,
        }
    }

    // Dropping `stdin` here (end of scope) closes the pipe, which is what
    // makes `git cat-file --batch` exit; `wait()` then just reaps it.
    drop(stdin);
    let status = child
        .wait()
        .map_err(|source| anyhow::anyhow!("failed to wait on git cat-file --batch: {source}"))?;
    // The child has exited, so its stderr end is closed and this join
    // cannot block indefinitely waiting for more output.
    let stderr_output = stderr_reader
        .join()
        .unwrap_or_else(|_| b"<failed to read stderr: reader thread panicked>".to_vec());
    if !status.success() {
        anyhow::bail!(
            "git cat-file --batch exited with {status}: {}",
            String::from_utf8_lossy(&stderr_output)
        );
    }
    Ok(files)
}

/// Reads and parses one `git cat-file --batch` response for `object`
/// (`<head>:<path>`). See `read_git_show_files_batch`'s doc comment for
/// the "found" response shape.
///
/// `git cat-file --batch` has more single-line, no-content-body response
/// shapes than just `<object> missing` — `git help cat-file`'s BATCH
/// OUTPUT section also documents `<object> ambiguous` (an ambiguous short
/// name — not reachable through this call's `<head>:<path>` requests,
/// which are never short/ambiguous, but defended against anyway) and
/// `<oid> submodule` (a gitlink entry whose target commit isn't present
/// in the repository). Any header line that isn't the `<oid> <type>
/// <size>` "found" shape is therefore treated the same way as `missing`:
/// skip this single path, since a single line was already fully consumed
/// by `read_line` and the stream position is well-defined regardless of
/// what that line actually said — there is nothing to desync.
///
/// `Ok(None)` for any such skippable single-line response, or for
/// found-but-non-UTF-8 content (both "skip this path", matching the
/// working-tree read path's `.ok()` handling and restoring the same
/// per-file isolation `read_git_show_file` had before batching). `Err`
/// only for an IO failure reading the header line, the exact-size content
/// bytes, or the trailing newline after a "found" header — those are the
/// only points where the stream's position becomes genuinely unknown
/// (a partial read of `size` content bytes, in particular, means there is
/// no way to know where the next response begins), so recovery for later
/// paths in the same batch is not possible and the whole call must fail.
fn read_cat_file_batch_response(
    reader: &mut impl BufRead,
    object: &str,
) -> anyhow::Result<Option<String>> {
    let mut header = String::new();
    reader.read_line(&mut header).map_err(|source| {
        anyhow::anyhow!("failed to read git cat-file --batch header: {source}")
    })?;
    let header = header.trim_end_matches('\n');

    // "Found" shape: "<oid> <type> <size>", the size being the last
    // whitespace-separated token. Anything else (missing, ambiguous,
    // submodule, or any other single-line shape this code doesn't
    // specifically know about) is a skip, not a hard error — see the doc
    // comment above for why that's safe.
    let Some(size) = header
        .rsplit(' ')
        .next()
        .and_then(|s| s.parse::<usize>().ok())
    else {
        return Ok(None);
    };

    let mut content = vec![0u8; size];
    reader.read_exact(&mut content).map_err(|source| {
        anyhow::anyhow!("failed to read git cat-file --batch content for {object}: {source}")
    })?;
    // Every found response is followed by exactly one trailing newline
    // after the content bytes, regardless of whether the content itself
    // ends in one.
    let mut trailing_newline = [0u8; 1];
    reader.read_exact(&mut trailing_newline).map_err(|source| {
        anyhow::anyhow!(
            "failed to read git cat-file --batch trailing newline for {object}: {source}"
        )
    })?;

    match String::from_utf8(content) {
        Ok(content) => Ok(Some(content)),
        Err(_) => Ok(None),
    }
}

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

    #[test]
    fn should_default_to_markdown_head_and_no_base_when_no_args_given() {
        let expected = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_set_base_when_base_flag_given() {
        let expected = Cli {
            command: None,
            base: Some("main".to_string()),
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "--base", "main"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_set_base_and_head_when_both_flags_given() {
        let expected = Cli {
            command: None,
            base: Some("main".to_string()),
            head: "feature-branch".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "--base", "main", "--head", "feature-branch"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_set_format_json_when_format_flag_given() {
        let expected = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Json,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "--format", "json"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_reject_unknown_format_value() {
        let actual = Cli::try_parse_from(["rinkaku", "--format", "yaml"]);

        assert!(actual.is_err());
    }

    #[test]
    fn should_set_deps_zero_when_deps_flag_given() {
        let expected = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 0,
        };
        let actual = Cli::parse_from(["rinkaku", "--deps", "0"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_reject_deps_value_outside_zero_or_one() {
        let actual = Cli::try_parse_from(["rinkaku", "--deps", "2"]);

        assert!(actual.is_err());
    }

    #[test]
    fn should_set_self_update_command_when_self_update_subcommand_given() {
        let expected = Cli {
            command: Some(Command::SelfUpdate { yes: false }),
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "self-update"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_set_yes_flag_when_self_update_yes_flag_given() {
        let expected = Cli {
            command: Some(Command::SelfUpdate { yes: true }),
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "self-update", "--yes"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_set_yes_flag_when_self_update_short_y_flag_given() {
        let expected = Cli {
            command: Some(Command::SelfUpdate { yes: true }),
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "self-update", "-y"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_verify_cli_definition() {
        // clap's own consistency check (duplicate args, invalid
        // configuration, etc.) — mirrors skem's `Cli::command().debug_assert()`
        // convention for catching CLI wiring mistakes at test time.
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    #[test]
    fn should_set_pr_when_pr_flag_given() {
        // Also covers that `--pr` alone (no explicit `--head`) parses
        // successfully: `--head` has a default value, so clap's
        // `conflicts_with` must not fire unless `--head` was actually
        // passed on the command line — this is the behavior the ADR relies
        // on to let `--pr` reuse the `Cli` struct's `head` field internally
        // without users needing to omit an unrelated flag.
        let expected = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: Some("76".to_string()),
            format: Format::Md,
            deps: 1,
        };
        let actual = Cli::parse_from(["rinkaku", "--pr", "76"]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn should_reject_pr_and_base_together() {
        let actual = Cli::try_parse_from(["rinkaku", "--pr", "76", "--base", "main"]);

        assert!(actual.is_err());
    }

    #[test]
    fn should_reject_pr_and_explicit_head_together() {
        let actual = Cli::try_parse_from(["rinkaku", "--pr", "76", "--head", "feature-branch"]);

        assert!(actual.is_err());
    }

    #[rstest]
    #[case::should_parse_bare_number("76", PrArg::Number(76))]
    #[case::should_parse_number_with_surrounding_whitespace(" 76 ", PrArg::Number(76))]
    #[case::should_parse_pull_url(
        "https://github.com/octocat/hello-world/pull/123",
        PrArg::Url {
            owner: "octocat".to_string(),
            repo: "hello-world".to_string(),
            number: 123,
        }
    )]
    #[case::should_parse_pull_url_with_trailing_slash(
        "https://github.com/octocat/hello-world/pull/123/",
        PrArg::Url {
            owner: "octocat".to_string(),
            repo: "hello-world".to_string(),
            number: 123,
        }
    )]
    #[case::should_parse_pull_url_with_extra_path_segment(
        "https://github.com/octocat/hello-world/pull/123/files",
        PrArg::Url {
            owner: "octocat".to_string(),
            repo: "hello-world".to_string(),
            number: 123,
        }
    )]
    fn should_parse_pr_arg_when_input_is_valid(#[case] input: &str, #[case] expected: PrArg) {
        let actual = parse_pr_arg(input).expect("expected a valid PR arg");

        assert_eq!(expected, actual);
    }

    #[rstest]
    #[case::should_reject_empty_string("")]
    #[case::should_reject_non_numeric_string("abc")]
    #[case::should_reject_zero("0")]
    #[case::should_reject_negative_number("-1")]
    #[case::should_reject_non_pull_github_url("https://github.com/octocat/hello-world/issues/123")]
    #[case::should_reject_github_url_missing_number("https://github.com/octocat/hello-world/pull/")]
    #[case::should_reject_unrelated_url("https://example.com/pull/123")]
    fn should_reject_pr_arg_when_input_is_invalid(#[case] input: &str) {
        let actual = parse_pr_arg(input);

        assert!(actual.is_err(), "expected an error for input: {input}");
    }

    #[rstest]
    #[case::should_parse_https_url(
        "https://github.com/octocat/hello-world",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_parse_https_url_with_dot_git_suffix(
        "https://github.com/octocat/hello-world.git",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_parse_scp_like_ssh_url(
        "git@github.com:octocat/hello-world.git",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_parse_scp_like_ssh_url_without_dot_git_suffix(
        "git@github.com:octocat/hello-world",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_parse_explicit_ssh_url(
        "ssh://git@github.com/octocat/hello-world.git",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_parse_explicit_ssh_url_without_dot_git_suffix(
        "ssh://git@github.com/octocat/hello-world",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_trim_surrounding_whitespace(
        " https://github.com/octocat/hello-world.git \n",
        Some(("octocat".to_string(), "hello-world".to_string()))
    )]
    #[case::should_reject_non_github_host("https://gitlab.com/octocat/hello-world.git", None)]
    #[case::should_reject_url_missing_repo_segment("https://github.com/octocat", None)]
    #[case::should_reject_url_with_extra_path_segment(
        "https://github.com/octocat/hello-world/extra",
        None
    )]
    #[case::should_reject_empty_string("", None)]
    fn should_parse_github_remote(#[case] url: &str, #[case] expected: Option<(String, String)>) {
        let actual = parse_github_remote(url);

        assert_eq!(expected, actual);
    }

    #[rstest]
    #[case::should_match_identical_owner_and_repo(
        "https://github.com/octocat/hello-world.git",
        "octocat",
        "hello-world",
        true
    )]
    #[case::should_match_case_insensitively(
        "https://github.com/Octocat/Hello-World.git",
        "octocat",
        "hello-world",
        true
    )]
    #[case::should_not_match_different_repo(
        "https://github.com/octocat/hello-world.git",
        "octocat",
        "other-repo",
        false
    )]
    #[case::should_not_match_different_owner(
        "https://github.com/octocat/hello-world.git",
        "someone-else",
        "hello-world",
        false
    )]
    #[case::should_not_match_non_github_remote(
        "https://gitlab.com/octocat/hello-world.git",
        "octocat",
        "hello-world",
        false
    )]
    fn should_check_github_remote_match(
        #[case] remote_url: &str,
        #[case] owner: &str,
        #[case] repo: &str,
        #[case] expected: bool,
    ) {
        let actual = github_remote_matches(remote_url, owner, repo);

        assert_eq!(expected, actual);
    }

    #[rstest]
    #[case::should_prefer_rinkaku_cache_dir_when_set(
        Some("/custom/cache"),
        Some("/xdg/cache"),
        Some("/home/user"),
        "/custom/cache/repos/github.com/octocat/hello-world"
    )]
    #[case::should_fall_back_to_xdg_cache_home_when_rinkaku_cache_dir_unset(
        None,
        Some("/xdg/cache"),
        Some("/home/user"),
        "/xdg/cache/rinkaku/repos/github.com/octocat/hello-world"
    )]
    #[case::should_fall_back_to_home_when_neither_env_var_set(
        None,
        None,
        Some("/home/user"),
        "/home/user/.cache/rinkaku/repos/github.com/octocat/hello-world"
    )]
    fn should_build_cache_repo_dir(
        #[case] rinkaku_cache_dir: Option<&str>,
        #[case] xdg_cache_home: Option<&str>,
        #[case] home: Option<&str>,
        #[case] expected: &str,
    ) {
        let actual = cache_repo_dir(
            rinkaku_cache_dir,
            xdg_cache_home,
            home,
            "octocat",
            "hello-world",
        )
        .expect("expected a cache directory to be resolved");

        assert_eq!(std::path::PathBuf::from(expected), actual);
    }

    #[test]
    fn should_fail_to_build_cache_repo_dir_when_no_env_source_is_available() {
        let actual = cache_repo_dir(None, None, None, "octocat", "hello-world");

        assert!(actual.is_err());
    }

    #[rstest]
    #[case::should_parse_single_line(
        "/home/user/ghq/github.com/octocat/hello-world\n",
        vec![std::path::PathBuf::from("/home/user/ghq/github.com/octocat/hello-world")]
    )]
    #[case::should_parse_multiple_lines(
        "/home/user/ghq/github.com/octocat/hello-world\n/home/user/work/hello-world\n",
        vec![
            std::path::PathBuf::from("/home/user/ghq/github.com/octocat/hello-world"),
            std::path::PathBuf::from("/home/user/work/hello-world"),
        ]
    )]
    #[case::should_skip_blank_lines_between_entries(
        "/home/user/ghq/github.com/octocat/hello-world\n\n/home/user/work/hello-world\n",
        vec![
            std::path::PathBuf::from("/home/user/ghq/github.com/octocat/hello-world"),
            std::path::PathBuf::from("/home/user/work/hello-world"),
        ]
    )]
    #[case::should_trim_surrounding_whitespace_per_line(
        "  /home/user/ghq/github.com/octocat/hello-world  \n",
        vec![std::path::PathBuf::from("/home/user/ghq/github.com/octocat/hello-world")]
    )]
    #[case::should_return_empty_vec_for_empty_string("", vec![])]
    #[case::should_return_empty_vec_for_whitespace_only_string("\n\n  \n", vec![])]
    fn should_parse_ghq_list_output(
        #[case] stdout: &str,
        #[case] expected: Vec<std::path::PathBuf>,
    ) {
        let actual = parse_ghq_list_output(stdout);

        assert_eq!(expected, actual);
    }

    #[rstest]
    #[case::should_return_first_candidate_when_it_matches(
        vec!["/a", "/b"],
        vec![("/a", "https://github.com/octocat/hello-world.git")],
        Some(std::path::PathBuf::from("/a"))
    )]
    #[case::should_return_later_candidate_when_earlier_ones_mismatch(
        vec!["/a", "/b", "/c"],
        vec![
            ("/a", "https://github.com/someone-else/other-repo.git"),
            ("/b", "https://github.com/octocat/hello-world.git"),
        ],
        Some(std::path::PathBuf::from("/b"))
    )]
    #[case::should_return_none_when_no_candidate_matches(
        vec!["/a", "/b"],
        vec![
            ("/a", "https://github.com/someone-else/other-repo.git"),
            ("/b", "https://gitlab.com/octocat/hello-world.git"),
        ],
        None
    )]
    #[case::should_return_none_when_candidates_is_empty(vec![], vec![], None)]
    #[case::should_return_none_when_origin_lookup_yields_nothing_for_any_candidate(
        vec!["/a"],
        vec![],
        None
    )]
    fn should_select_matching_clone(
        #[case] candidates: Vec<&str>,
        #[case] origins: Vec<(&str, &str)>,
        #[case] expected: Option<std::path::PathBuf>,
    ) {
        let candidates: Vec<std::path::PathBuf> = candidates
            .into_iter()
            .map(std::path::PathBuf::from)
            .collect();
        let origin_of = |path: &std::path::Path| {
            origins
                .iter()
                .find(|(candidate_path, _)| std::path::Path::new(candidate_path) == path)
                .map(|(_, origin)| origin.to_string())
        };

        let actual = select_matching_clone(&candidates, origin_of, "octocat", "hello-world");

        assert_eq!(expected, actual);
    }

    mod resolve_pr_base_sha_tests {
        use super::*;
        use pretty_assertions::assert_eq;
        use std::cell::RefCell;

        #[test]
        fn should_return_base_ref_oid_when_it_already_exists_locally() {
            let fetch_base_branch_calls = RefCell::new(0);
            let fetch_oid_calls = RefCell::new(0);

            let actual = resolve_pr_base_sha(
                "base789",
                |_oid| true,
                || {
                    *fetch_base_branch_calls.borrow_mut() += 1;
                    Ok("branch-tip-sha".to_string())
                },
                |_oid| {
                    *fetch_oid_calls.borrow_mut() += 1;
                    Ok(())
                },
            )
            .expect("should resolve without error");

            assert_eq!(("base789".to_string(), false), actual);
            assert_eq!(0, *fetch_base_branch_calls.borrow());
            assert_eq!(0, *fetch_oid_calls.borrow());
        }

        #[test]
        fn should_return_base_ref_oid_when_fetching_the_base_branch_makes_it_available() {
            let exists_calls = RefCell::new(0);
            let object_exists = |_oid: &str| {
                let mut calls = exists_calls.borrow_mut();
                *calls += 1;
                // First check (before any fetch) fails; the check right
                // after `fetch_base_branch` succeeds.
                *calls > 1
            };

            let actual = resolve_pr_base_sha(
                "base789",
                object_exists,
                || Ok("branch-tip-sha".to_string()),
                |_oid| panic!("fetch_oid must not be called when the base branch fetch sufficed"),
            )
            .expect("should resolve without error");

            assert_eq!(("base789".to_string(), false), actual);
        }

        #[test]
        fn should_return_base_ref_oid_when_fetching_the_oid_directly_makes_it_available() {
            let exists_calls = RefCell::new(0);
            let object_exists = |_oid: &str| {
                let mut calls = exists_calls.borrow_mut();
                *calls += 1;
                // Neither the initial check nor the one after the base
                // branch fetch succeed; only the one after `fetch_oid`
                // does (third call).
                *calls > 2
            };

            let actual = resolve_pr_base_sha(
                "base789",
                object_exists,
                || Ok("branch-tip-sha".to_string()),
                |_oid| Ok(()),
            )
            .expect("should resolve without error");

            assert_eq!(("base789".to_string(), false), actual);
        }

        #[test]
        fn should_fall_back_to_branch_tip_when_the_oid_is_unreachable_by_any_means() {
            let actual = resolve_pr_base_sha(
                "base789",
                |_oid| false,
                || Ok("branch-tip-sha".to_string()),
                |_oid| anyhow::bail!("simulated: base789 not found on the remote"),
            )
            .expect("should fall back rather than error");

            assert_eq!(("branch-tip-sha".to_string(), true), actual);
        }

        #[test]
        fn should_fall_back_to_branch_tip_when_fetch_oid_succeeds_but_object_still_missing() {
            // `git fetch origin <oid>` can itself succeed (e.g. the remote
            // accepts the request) while the object is still not resolvable
            // locally afterwards — covered separately from the "fetch_oid
            // errors outright" case above.
            let actual = resolve_pr_base_sha(
                "base789",
                |_oid| false,
                || Ok("branch-tip-sha".to_string()),
                |_oid| Ok(()),
            )
            .expect("should fall back rather than error");

            assert_eq!(("branch-tip-sha".to_string(), true), actual);
        }

        // Regression test for the must-fix correctness bug: a step-2
        // fetch failure (e.g. the base branch was deleted or renamed after
        // the PR merged) must not abort the whole cascade — step 3 (fetch
        // the oid directly) is exactly the recovery path for this
        // situation, so it must still run and can still resolve
        // `base_ref_oid` even though step 2 failed.
        #[test]
        fn should_fall_through_to_fetch_oid_when_fetching_the_base_branch_fails() {
            let exists_calls = RefCell::new(0);
            let object_exists = |_oid: &str| {
                let mut calls = exists_calls.borrow_mut();
                *calls += 1;
                // Only the initial check happens before the failed branch
                // fetch (which does not re-check); the check after
                // `fetch_oid` (second call) succeeds.
                *calls > 1
            };

            let actual = resolve_pr_base_sha(
                "base789",
                object_exists,
                || anyhow::bail!("simulated: base branch was deleted"),
                |_oid| Ok(()),
            )
            .expect("a step-2 failure must not abort the cascade");

            assert_eq!(("base789".to_string(), false), actual);
        }

        // Sibling case: if step 3 also can't resolve the oid after a
        // step-2 failure, the cascade must still fall back (step 4) rather
        // than propagating the step-2 error — step 2's failure was already
        // handled by falling through, not by failing the whole call.
        #[test]
        fn should_fetch_branch_tip_for_fallback_when_step_two_failed_and_fetch_oid_also_fails() {
            let fetch_base_branch_calls = RefCell::new(0);

            let actual = resolve_pr_base_sha(
                "base789",
                |_oid| false,
                || {
                    let mut calls = fetch_base_branch_calls.borrow_mut();
                    *calls += 1;
                    if *calls == 1 {
                        anyhow::bail!("simulated: base branch was deleted")
                    } else {
                        // Step 4 must re-fetch since step 2 never produced
                        // a tip to reuse.
                        Ok("branch-tip-sha".to_string())
                    }
                },
                |_oid| anyhow::bail!("simulated: base789 not found on the remote"),
            )
            .expect("should fall back rather than error");

            assert_eq!(("branch-tip-sha".to_string(), true), actual);
            assert_eq!(2, *fetch_base_branch_calls.borrow());
        }

        // Regression test for the must-fix cleanup: when step 2 succeeded
        // (returned a tip) but didn't make `base_ref_oid` resolvable, and
        // step 3 also fails, step 4's fallback must reuse step 2's tip
        // rather than fetching the same base branch a second time.
        #[test]
        fn should_reuse_step_two_tip_for_fallback_without_refetching() {
            let fetch_base_branch_calls = RefCell::new(0);

            let actual = resolve_pr_base_sha(
                "base789",
                |_oid| false,
                || {
                    *fetch_base_branch_calls.borrow_mut() += 1;
                    Ok("branch-tip-sha".to_string())
                },
                |_oid| anyhow::bail!("simulated: base789 not found on the remote"),
            )
            .expect("should fall back rather than error");

            assert_eq!(("branch-tip-sha".to_string(), true), actual);
            assert_eq!(
                1,
                *fetch_base_branch_calls.borrow(),
                "fetch_base_branch must only be called once (by step 2); step 4 must reuse its \
                 result instead of fetching the base branch again"
            );
        }

        #[test]
        fn should_propagate_error_when_the_branch_tip_fallback_itself_fails() {
            let fetch_base_branch_calls = RefCell::new(0);

            let actual = resolve_pr_base_sha(
                "base789",
                |_oid| false,
                || {
                    let mut calls = fetch_base_branch_calls.borrow_mut();
                    *calls += 1;
                    anyhow::bail!("simulated: git fetch origin main failed")
                },
                |_oid| anyhow::bail!("simulated: base789 not found on the remote"),
            );

            assert!(actual.is_err());
        }
    }

    #[test]
    fn should_parse_pr_view_json_into_pr_info() {
        let json = r#"{"number":123,"baseRefName":"main","baseRefOid":"base789","headRefOid":"abc123def456"}"#;

        let actual = parse_pr_view_json(json).expect("expected valid JSON to parse");

        assert_eq!(
            PrInfo {
                number: 123,
                base_ref_name: "main".to_string(),
                base_ref_oid: "base789".to_string(),
                head_ref_oid: "abc123def456".to_string(),
            },
            actual
        );
    }

    #[test]
    fn should_fail_to_parse_pr_view_json_when_a_required_field_is_missing() {
        let json = r#"{"number":123,"baseRefName":"main"}"#;

        let actual = parse_pr_view_json(json);

        assert!(actual.is_err());
    }

    /// Runs `git` inside `dir`, panicking with the captured stderr on
    /// failure. Test-only helper: production code never wants a panicking
    /// git wrapper.
    fn run_git(dir: &std::path::Path, args: &[&str]) {
        let output = std::process::Command::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .expect("git must be installed to run this test");
        assert!(
            output.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// Sets up a throwaway git repository with deterministic author/committer
    /// identity (avoids depending on the host's global git config) and one
    /// commit containing `src/lib.rs` with `content`.
    fn init_repo_with_committed_file(dir: &std::path::Path, content: &str) {
        run_git(dir, &["init", "--initial-branch=main"]);
        run_git(dir, &["config", "user.email", "test@example.com"]);
        run_git(dir, &["config", "user.name", "Test"]);
        std::fs::create_dir_all(dir.join("src")).expect("create src dir");
        std::fs::write(dir.join("src/lib.rs"), content).expect("write src/lib.rs");
        run_git(dir, &["add", "src/lib.rs"]);
        run_git(dir, &["commit", "-m", "initial commit"]);
    }

    // Integration test for the must-fix design: `--base` mode must read
    // file content via `git show <head>:<path>`, not off the working tree.
    // A dirty working tree (uncommitted edit) must not affect what gets
    // read — only the committed content at `head` should come back.
    #[test]
    fn should_read_committed_content_when_working_tree_is_dirty() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        let committed = "fn foo(a: i32) -> i32 {\n    a\n}\n";
        init_repo_with_committed_file(dir.path(), committed);

        // Dirty the working tree after the commit: if `read_git_show_file`
        // fell back to the working tree, it would read this instead.
        std::fs::write(
            dir.path().join("src/lib.rs"),
            "fn foo(a: i32) -> i32 {\n    a + 999\n}\n",
        )
        .expect("dirty the working tree");

        let actual = read_git_show_file(Some(dir.path()), "HEAD", "src/lib.rs")
            .expect("git show should succeed for a committed file");

        assert_eq!(committed, actual);
    }

    // Integration test for the perf fix: a single `git cat-file --batch`
    // process must return the same content `read_git_show_file` would
    // have returned per-file, for every tracked path in one pass.
    #[test]
    fn should_read_every_path_via_a_single_cat_file_batch_process() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        run_git(dir.path(), &["init", "--initial-branch=main"]);
        run_git(dir.path(), &["config", "user.email", "test@example.com"]);
        run_git(dir.path(), &["config", "user.name", "Test"]);
        std::fs::write(dir.path().join("a.rs"), "fn a() {}\n").expect("write a.rs");
        std::fs::write(dir.path().join("b.rs"), "fn b() {}\n").expect("write b.rs");
        run_git(dir.path(), &["add", "a.rs", "b.rs"]);
        run_git(dir.path(), &["commit", "-m", "initial commit"]);

        let mut actual = read_git_show_files_batch(
            Some(dir.path()),
            "HEAD",
            vec!["a.rs".to_string(), "b.rs".to_string()],
        )
        .expect("git cat-file --batch should succeed for tracked files");
        actual.sort();

        assert_eq!(
            vec![
                ("a.rs".to_string(), "fn a() {}\n".to_string()),
                ("b.rs".to_string(), "fn b() {}\n".to_string()),
            ],
            actual
        );
    }

    // Sibling case: a dirty working tree must not affect what the batch
    // read returns, same guarantee `read_git_show_file` already provides
    // per-file (`should_read_committed_content_when_working_tree_is_dirty`
    // above).
    #[test]
    fn should_read_committed_content_via_batch_when_working_tree_is_dirty() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        let committed = "fn foo(a: i32) -> i32 {\n    a\n}\n";
        init_repo_with_committed_file(dir.path(), committed);

        std::fs::write(
            dir.path().join("src/lib.rs"),
            "fn foo(a: i32) -> i32 {\n    a + 999\n}\n",
        )
        .expect("dirty the working tree");

        let actual =
            read_git_show_files_batch(Some(dir.path()), "HEAD", vec!["src/lib.rs".to_string()])
                .expect("git cat-file --batch should succeed for a committed file");

        assert_eq!(
            vec![("src/lib.rs".to_string(), committed.to_string())],
            actual
        );
    }

    // A path `git ls-files` lists but that doesn't resolve to a blob at
    // `head` (e.g. a submodule gitlink entry, or here simply a path that
    // was never committed) must be skipped rather than failing the whole
    // batch — matching `build_resolver`'s existing best-effort handling of
    // per-file read failures.
    #[test]
    fn should_skip_missing_paths_when_reading_via_batch() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        init_repo_with_committed_file(dir.path(), "fn foo() {}\n");

        let actual = read_git_show_files_batch(
            Some(dir.path()),
            "HEAD",
            vec!["src/lib.rs".to_string(), "does/not/exist.rs".to_string()],
        )
        .expect("git cat-file --batch should succeed even with a missing path");

        assert_eq!(
            vec![("src/lib.rs".to_string(), "fn foo() {}\n".to_string())],
            actual
        );
    }

    // A tracked file whose committed content isn't valid UTF-8 (a binary
    // file) must be skipped rather than failing the batch or the whole
    // resolver build — matching `build_resolver`'s existing best-effort
    // handling (content.ok() drops read failures, and a `String::from_utf8`
    // failure is exactly the same kind of "can't use this as source text"
    // situation).
    #[test]
    fn should_skip_non_utf8_content_when_reading_via_batch() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        run_git(dir.path(), &["init", "--initial-branch=main"]);
        run_git(dir.path(), &["config", "user.email", "test@example.com"]);
        run_git(dir.path(), &["config", "user.name", "Test"]);
        std::fs::write(dir.path().join("text.rs"), "fn ok() {}\n").expect("write text.rs");
        std::fs::write(dir.path().join("binary.dat"), [0xff_u8, 0xfe, 0x00, 0x01])
            .expect("write binary.dat");
        run_git(dir.path(), &["add", "text.rs", "binary.dat"]);
        run_git(dir.path(), &["commit", "-m", "initial commit"]);

        let mut actual = read_git_show_files_batch(
            Some(dir.path()),
            "HEAD",
            vec!["text.rs".to_string(), "binary.dat".to_string()],
        )
        .expect("git cat-file --batch should succeed even with binary content present");
        actual.sort();

        assert_eq!(
            vec![("text.rs".to_string(), "fn ok() {}\n".to_string())],
            actual
        );
    }

    mod read_cat_file_batch_response_tests {
        use super::*;
        use pretty_assertions::assert_eq;

        #[test]
        fn should_return_content_when_response_is_found() {
            let mut reader = std::io::Cursor::new(b"abc123 blob 5\nhello\n".to_vec());

            let actual = read_cat_file_batch_response(&mut reader, "HEAD:a.rs")
                .expect("a well-formed found response must parse");

            assert_eq!(Some("hello".to_string()), actual);
        }

        #[test]
        fn should_return_none_when_response_is_missing() {
            let mut reader = std::io::Cursor::new(b"HEAD:a.rs missing\n".to_vec());

            let actual = read_cat_file_batch_response(&mut reader, "HEAD:a.rs")
                .expect("a missing response must not be a hard error");

            assert_eq!(None, actual);
        }

        // `git help cat-file`'s BATCH OUTPUT section documents this shape
        // for an ambiguous short name. Not reachable in practice through
        // this codebase's `<head>:<path>` requests (never a short/
        // ambiguous name by construction), but must still be treated as a
        // skip rather than a hard error if git ever emitted it — it's a
        // single line with no content body, so there is nothing to
        // desync on.
        #[test]
        fn should_return_none_when_response_is_ambiguous() {
            let mut reader = std::io::Cursor::new(b"abc1 ambiguous\n".to_vec());

            let actual = read_cat_file_batch_response(&mut reader, "abc1")
                .expect("an ambiguous response must not be a hard error");

            assert_eq!(None, actual);
        }

        // `git help cat-file`'s BATCH OUTPUT section documents this shape
        // for a gitlink (submodule) entry whose target commit isn't
        // present in the repository — exactly the kind of single-file
        // condition the regression this test guards against used to turn
        // into a hard failure for the whole batch (the "<size>" parse
        // used to require the header be an exact `missing` match or
        // parse as `<oid> <type> <size>`; anything else, including this
        // shape, fell into an `Err`).
        #[test]
        fn should_return_none_when_response_is_a_submodule_entry() {
            let mut reader = std::io::Cursor::new(
                b"3eb8e680cc28d03641be1d2af8e098e8ac6a42f8 submodule\n".to_vec(),
            );

            let actual = read_cat_file_batch_response(&mut reader, "HEAD:sub")
                .expect("a submodule response must not be a hard error");

            assert_eq!(None, actual);
        }

        #[test]
        fn should_return_none_when_found_content_is_not_valid_utf8() {
            let mut reader = std::io::Cursor::new(
                [
                    b"abc123 blob 4\n".as_slice(),
                    &[0xff, 0xfe, 0x00, 0x01],
                    b"\n",
                ]
                .concat(),
            );

            let actual = read_cat_file_batch_response(&mut reader, "HEAD:binary.dat")
                .expect("non-UTF-8 content must not be a hard error");

            assert_eq!(None, actual);
        }

        // Regression guard for the opposite direction of the fix above:
        // a genuine stream desync (here, content truncated shorter than
        // the declared size) must still be a hard error — it cannot be
        // isolated to a single path, unlike the skippable shapes above.
        #[test]
        fn should_return_error_when_content_is_truncated() {
            let mut reader = std::io::Cursor::new(b"abc123 blob 100\nshort\n".to_vec());

            let actual = read_cat_file_batch_response(&mut reader, "HEAD:a.rs");

            assert!(actual.is_err());
        }
    }

    // Regression test for the must-fix cleanup: the exit-status error
    // message must include the child's stderr, matching every other
    // subprocess call in this file. Also exercises the concurrent
    // stderr-draining thread end to end (rather than only reasoning about
    // it): a non-git `cwd` makes `git cat-file --batch` write a `fatal:
    // not a git repository...` diagnostic to stderr and exit non-zero,
    // and that diagnostic must show up in the returned error.
    #[test]
    fn should_include_stderr_in_error_when_git_cat_file_batch_exits_non_zero() {
        let dir = tempfile::TempDir::new().expect("create tempdir");

        let actual = read_git_show_files_batch(Some(dir.path()), "HEAD", vec!["a.rs".to_string()]);

        let error = actual.expect_err("a non-git cwd must fail rather than silently succeed");
        let message = error.to_string();
        assert!(
            message.contains("not a git repository"),
            "expected the child's stderr to be included in the error, got: {message:?}"
        );
    }

    // Integration test for `--pr` URL mode's cwd-vs-cache decision (ADR
    // 0005): a real repository with an `origin` remote set must have that
    // URL surfaced by `git_remote_origin_url` so `github_remote_matches`
    // (already unit-tested above against arbitrary strings) can decide
    // whether to reuse the cwd. Exercises the subprocess wrapper itself
    // rather than `github_remote_matches`'s string logic, which is
    // already covered directly.
    #[test]
    fn should_return_origin_url_when_repository_has_an_origin_remote() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        init_repo_with_committed_file(dir.path(), "fn foo() {}\n");
        run_git(
            dir.path(),
            &[
                "remote",
                "add",
                "origin",
                "https://github.com/octocat/hello-world.git",
            ],
        );

        let actual =
            git_remote_origin_url(Some(dir.path())).expect("git remote get-url should not error");

        assert_eq!(
            Some("https://github.com/octocat/hello-world.git".to_string()),
            actual
        );
    }

    // Sibling case: a repository with no `origin` remote at all (rather
    // than a missing/misconfigured one) must come back as `Ok(None)`, not
    // an `Err` — ADR 0005 treats "doesn't match" and "isn't even a clone"
    // identically as "use the cache", so this must not be a fatal error.
    #[test]
    fn should_return_none_when_repository_has_no_origin_remote() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        init_repo_with_committed_file(dir.path(), "fn foo() {}\n");

        let actual = git_remote_origin_url(Some(dir.path()))
            .expect("missing origin remote should not error");

        assert_eq!(None, actual);
    }

    // Sibling case: a directory that isn't a git repository at all must
    // also come back as `Ok(None)`, matching the "run outside any clone"
    // scenario ADR 0005's cache path exists to handle.
    #[test]
    fn should_return_none_when_directory_is_not_a_git_repository() {
        let dir = tempfile::TempDir::new().expect("create tempdir");

        let actual = git_remote_origin_url(Some(dir.path()))
            .expect("a non-repository directory should not error");

        assert_eq!(None, actual);
    }

    // Regression test for the must-fix performance bug: `build_resolver`
    // must return before doing any repository scan when `deps == 0`. This
    // is exercised indirectly rather than by inspecting call counts (no
    // mocking of `git`, per this project's test conventions): `cwd` points
    // at a plain (non-git) tempdir, so if `list_git_files` were reached,
    // `git ls-files` would fail there and `build_resolver` would return
    // `Err`. Observing `Ok(None)` is therefore proof the scan never ran.
    //
    // NOTE: partial assertion (`is_none()` rather than a fully qualified
    // comparison) because `TagsResolver` derives neither `Debug` nor
    // `PartialEq` — its `HashMap` index isn't meant to be compared as a
    // value, only used through `Resolver::resolve`. Which variant of
    // `Option` came back is exactly what this test needs to know.
    #[test]
    fn should_skip_repository_scan_when_deps_is_zero() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        let cli = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 0,
        };
        // Never called if `deps == 0` truly short-circuits before doing
        // any work at all — deliberately panics so a regression that
        // starts calling it would fail loudly rather than silently
        // reading an empty string.
        let read_file = |_: &str| -> std::io::Result<String> {
            panic!("read_file must not be called when deps == 0")
        };

        let actual = build_resolver(&cli, "", read_file, None, Some(dir.path()))
            .expect("deps == 0 must not touch the repository at all");

        assert!(actual.is_none());
    }

    // Sibling case to the one above: with `deps == 1` (repository scan
    // enabled), the same non-git `cwd` makes `list_git_files` fail,
    // confirming the scan is actually attempted in this branch and that
    // the `Ok(None)` above is specific to `deps == 0`, not an artifact of
    // the test directory itself.
    #[test]
    fn should_fail_when_deps_is_one_and_cwd_has_no_git_repository() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        let cli = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let read_file = |_: &str| -> std::io::Result<String> { Ok(String::new()) };

        let actual = build_resolver(&cli, "", read_file, None, Some(dir.path()));

        assert!(actual.is_err());
    }

    // Regression test for the must-fix performance/correctness bug: an
    // empty diff (base == head, e.g. `--pr` on an already-merged PR before
    // ADR 0007's fix, or `--base main --head main`) must return the empty
    // `Report` directly, without ever invoking `build_resolver`'s
    // repository-wide `git ls-files` scan. Unlike `deps == 0`'s sibling
    // tests above (which call `build_resolver` directly and can simply
    // point `cwd` at a non-git directory), `run_base_pipeline` calls
    // `run_git_diff` unconditionally first — a non-git `cwd` would make
    // that fail too, before the empty-diff branch is ever reached. So this
    // test instead uses a real repository (required for `run_git_diff` to
    // succeed) and revokes read permission on `.git/index` specifically:
    // `git diff <base>...<head>` (a tree-to-tree comparison between two
    // commits) never opens the index, but `git ls-files` always does — so
    // if `build_resolver` were reached, `list_git_files` would fail and
    // this test would observe `Err` instead of the expected `Ok`.
    #[test]
    fn should_skip_repository_scan_when_diff_is_empty() {
        let dir = tempfile::TempDir::new().expect("create tempdir");
        init_repo_with_committed_file(dir.path(), "fn foo() {}\n");
        let index_path = dir.path().join(".git/index");
        let mut permissions = std::fs::metadata(&index_path)
            .expect("read .git/index metadata")
            .permissions();
        let original_mode = std::os::unix::fs::PermissionsExt::mode(&permissions);
        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o000);
        std::fs::set_permissions(&index_path, permissions).expect("revoke .git/index read access");

        let cli = Cli {
            command: None,
            base: None,
            head: "HEAD".to_string(),
            pr: None,
            format: Format::Md,
            deps: 1,
        };
        let actual = run_base_pipeline(&cli, "HEAD", "HEAD", Some(dir.path()));

        // Restore permissions before asserting so a failed assertion
        // doesn't leave an unreadable file behind for the tempdir cleanup.
        let mut permissions = std::fs::metadata(&index_path)
            .expect("re-read .git/index metadata")
            .permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, original_mode);
        std::fs::set_permissions(&index_path, permissions).expect("restore .git/index permissions");

        assert_eq!(
            rinkaku_core::render::Report {
                files: Vec::new(),
                skipped: Vec::new(),
            },
            actual.expect("empty diff must not touch the repository-wide index scan")
        );
    }

    mod garbage_input_note_tests {
        use super::*;
        use pretty_assertions::assert_eq;
        use rinkaku_core::render::Report;

        fn empty_report() -> Report {
            Report {
                files: vec![],
                skipped: vec![],
            }
        }

        fn non_empty_report() -> Report {
            Report {
                files: vec![rinkaku_core::render::FileReport {
                    path: "src/lib.rs".to_string(),
                    symbols: vec![],
                }],
                skipped: vec![],
            }
        }

        #[test]
        fn should_return_note_when_input_is_non_empty_but_report_has_no_entries() {
            let actual = garbage_input_note("this is not a diff at all\n", &empty_report());

            assert_eq!(
                Some("note: no file changes recognized in input; expected a unified diff"),
                actual
            );
        }

        #[test]
        fn should_return_none_when_input_is_empty() {
            let actual = garbage_input_note("", &empty_report());

            assert_eq!(None, actual);
        }

        #[test]
        fn should_return_none_when_input_is_whitespace_only() {
            let actual = garbage_input_note("   \n\n  ", &empty_report());

            assert_eq!(None, actual);
        }

        #[test]
        fn should_return_none_when_report_has_file_entries() {
            let actual = garbage_input_note("some diff text", &non_empty_report());

            assert_eq!(None, actual);
        }

        #[test]
        fn should_return_none_when_report_has_only_skipped_entries() {
            let report = Report {
                files: vec![],
                skipped: vec![rinkaku_core::render::SkippedFile {
                    path: "assets/logo.png".to_string(),
                    reason: rinkaku_core::render::SkipReason::Binary,
                }],
            };

            let actual = garbage_input_note("some diff text", &report);

            assert_eq!(None, actual);
        }
    }
}