git-queue 0.1.3

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

use crate::engine::Engine;
use crate::queue::{Line, Queue};
use crate::render::{self, Entry, PrRef};
use crate::{gh, git, ident, meta, requeue};
use anyhow::{bail, Context, Result};

/// Advertise merge order with commit statuses: the bottom-most open PR's head
/// gets a green `git-queue/merge-order` status; every open PR above it gets a
/// red one naming (and linking to) the PR that must merge first. Advisory: it
/// signals in the checks UI without touching draft state, branch rules, or
/// pushes. Assumes the branches were just pushed, so local tips == PR heads.
fn apply_status_gate(entries: &[Entry]) -> Result<()> {
    for s in render::gate_plan(entries) {
        let sha = git::rev_parse(&s.branch)?;
        gh::set_commit_status(
            &sha,
            render::GATE_CONTEXT,
            s.success,
            &s.description,
            s.target_url.as_deref(),
        )?;
    }
    Ok(())
}

/// Ask a yes/no question on the TTY; `default_yes` decides bare Enter.
fn confirm(question: &str, default_yes: bool) -> bool {
    use std::io::Write;
    print!("{question} [{}] ", if default_yes { "Y/n" } else { "y/N" });
    std::io::stdout().flush().ok();
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer).ok();
    match answer.trim().to_lowercase().as_str() {
        "" => default_yes,
        "y" | "yes" => true,
        _ => false,
    }
}

/// `git queue setup [--yes] [--undo]` — interactive, per-step opt-in setup:
/// the git hooks, the merge-order gate, the Claude Code skill, and (when
/// other agents are detected) an AGENTS.md section. `--yes` accepts the two
/// repo-local steps non-interactively; the integrations always ask.
pub(crate) fn setup(yes: bool, undo: bool) -> Result<()> {
    git::ensure_repo()?;
    if undo {
        return setup_undo();
    }
    let tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
    if !tty && !yes {
        bail!("`git queue setup` is interactive; pass --yes to accept the repo-local steps");
    }
    let ask = |q: &str| -> bool {
        if tty {
            confirm(q, true)
        } else {
            yes
        }
    };

    // 1. Hooks.
    if ask(
        "Install the git hooks? (plain `git commit`/`--amend` auto-requeue descendants;
new queue commits get a Stable-Commit-Id)",
    ) {
        hooks_install()?;
    }
    // 2. Merge-order gate.
    if ask(
        "Enable the merge-order gate? (submit/sync post a red/green commit status per PR
so reviewers see which PR merges next)",
    ) {
        meta::set_gate("status")?;
        println!("Merge-order gate enabled.");
    }
    // The next three steps are user-scoped (not repo-local), so they only run
    // interactively — never under a non-interactive `--yes`.
    // 3. Man page (Unix only — Windows has no `man`).
    if tty
        && !cfg!(windows)
        && confirm(
            "Install the man page? (`man git-queue`, and `git queue --help`)",
            true,
        )
    {
        if let Err(e) = install_man_pages() {
            eprintln!("note: could not install the man page: {e:#}");
        }
    }
    // 4. Shell completion.
    if tty {
        match detect_shell() {
            Some(shell) => {
                if confirm(
                    &format!("Install {shell} completion for the `git queue` commands?"),
                    true,
                ) {
                    if let Err(e) = install_completions(shell) {
                        eprintln!("note: could not install completion: {e:#}");
                    }
                }
            }
            None => println!(
                "note: shell not recognised from $SHELL; skipping completion \
                 (bash / zsh / fish are supported)."
            ),
        }
    }
    // 5. `git q` alias.
    if tty
        && confirm(
            "Add a `git q` alias to your global git config (shortcut for `git queue`)?",
            true,
        )
    {
        if let Err(e) = install_git_alias() {
            eprintln!("note: could not set the alias: {e:#}");
        }
    }
    // 6. Claude Code skill (only when Claude Code is present; interactive only).
    let home = home_dir();
    let claude_dir = home.join(".claude");
    if tty
        && claude_dir.exists()
        && confirm(
            "Claude Code detected. Install the `using-git-queue` skill so Claude drives
git-queue correctly?",
            true,
        )
    {
        let dir = claude_dir.join("skills").join("using-git-queue");
        std::fs::create_dir_all(&dir)?;
        std::fs::write(dir.join("SKILL.md"), EMBEDDED_SKILL)?;
        println!("Installed {}.", dir.join("SKILL.md").display());
    }
    // 7. Other agents -> AGENTS.md (the cross-agent convention).
    let others: Vec<&str> = [
        ("codex", ".codex"),
        ("cursor", ".cursor"),
        ("gemini", ".gemini"),
        ("windsurf", ".windsurf"),
        ("copilot", ".config/github-copilot"),
    ]
    .iter()
    .filter(|(_, d)| home.join(d).exists())
    .map(|(n, _)| *n)
    .collect();
    if tty
        && !others.is_empty()
        && confirm(
            &format!(
                "Detected other agents ({}). Add a git-queue section to this repo's AGENTS.md
(read by Codex, Cursor, Copilot and most agent CLIs)?",
                others.join(", ")
            ),
            true,
        )
    {
        write_agents_md_section()?;
    }
    println!(
        "
Setup done. `git queue doctor` reports the current state."
    );
    Ok(())
}

fn setup_undo() -> Result<()> {
    hooks_uninstall()?;
    let _ = git::ok(&["config", "--local", "--unset", "queue.gate"]);
    println!("Merge-order gate disabled.");
    remove_man_pages();
    remove_completions();
    // Only remove the alias if it's still the one we set.
    if git::out(&["config", "--global", "--get", "alias.q"])
        .ok()
        .as_deref()
        == Some("queue")
    {
        let _ = git::ok(&["config", "--global", "--unset", "alias.q"]);
        println!("Removed the `git q` alias.");
    }
    let skill = home_dir().join(".claude/skills/using-git-queue/SKILL.md");
    if skill.exists() {
        std::fs::remove_file(&skill).ok();
        println!("Removed {}.", skill.display());
    }
    strip_agents_md_section()?;
    Ok(())
}

/// The user's home directory, portably: `HOME` on unix, `USERPROFILE` on
/// Windows.
fn home_dir() -> std::path::PathBuf {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(std::path::PathBuf::from)
        .unwrap_or_default()
}

/// The candidate `man1` directories, preferring a system-wide location.
fn man_dirs() -> Vec<std::path::PathBuf> {
    vec![
        std::path::PathBuf::from("/usr/local/share/man/man1"),
        home_dir().join(".local/share/man/man1"),
    ]
}

/// True if `dir` accepts a file we write (a real writability probe — a
/// successful `mkdir` does not guarantee it).
fn dir_writable(dir: &std::path::Path) -> bool {
    let probe = dir.join(".git-queue-probe");
    let ok = std::fs::write(&probe, b"").is_ok();
    let _ = std::fs::remove_file(&probe);
    ok
}

/// Render and install the man page into a writable man1 directory that's on
/// the MANPATH, noting how to extend MANPATH when a user-local dir is used.
fn install_man_pages() -> Result<()> {
    let text = crate::man_text()?;
    let dir = man_dirs()
        .into_iter()
        .find(|d| std::fs::create_dir_all(d).is_ok() && dir_writable(d))
        .ok_or_else(|| {
            anyhow::anyhow!("no writable man directory (tried /usr/local and ~/.local)")
        })?;
    let path = dir.join("git-queue.1");
    std::fs::write(&path, &text)?;
    println!("Installed man page: {}", path.display());

    let user_base = home_dir().join(".local/share/man");
    if dir.starts_with(&user_base) && !manpath_contains(&user_base) {
        println!(
            "note: add {0} to your MANPATH so `man git-queue` resolves, e.g.:\n      \
             export MANPATH=\"{0}:$(manpath)\"",
            user_base.display()
        );
    }
    Ok(())
}

fn remove_man_pages() {
    for dir in man_dirs() {
        for name in ["git-queue.1", "git-q.1"] {
            let p = dir.join(name);
            if p.exists() && std::fs::remove_file(&p).is_ok() {
                println!("Removed {}.", p.display());
            }
        }
    }
}

fn manpath_contains(dir: &std::path::Path) -> bool {
    std::process::Command::new("manpath")
        .output()
        .ok()
        .is_some_and(|o| {
            String::from_utf8_lossy(&o.stdout)
                .split(':')
                .any(|p| std::path::Path::new(p.trim()) == dir)
        })
}

/// The user's shell, from `$SHELL`, if it's one we can generate completions for.
fn detect_shell() -> Option<clap_complete::Shell> {
    let shell = std::env::var("SHELL").ok()?;
    match std::path::Path::new(&shell)
        .file_name()?
        .to_string_lossy()
        .as_ref()
    {
        "bash" => Some(clap_complete::Shell::Bash),
        "zsh" => Some(clap_complete::Shell::Zsh),
        "fish" => Some(clap_complete::Shell::Fish),
        _ => None,
    }
}

/// Where a shell looks for a completion file, and the file's name.
fn completion_target(shell: clap_complete::Shell) -> Option<(std::path::PathBuf, &'static str)> {
    use clap_complete::Shell::{Bash, Fish, Zsh};
    let home = home_dir();
    match shell {
        Bash => Some((
            home.join(".local/share/bash-completion/completions"),
            "git-queue",
        )),
        Zsh => Some((home.join(".local/share/zsh/site-functions"), "_git-queue")),
        Fish => Some((home.join(".config/fish/completions"), "git-queue.fish")),
        _ => None,
    }
}

/// Generate and install a completion script for the `git-queue` binary. git's
/// own completion resolves `git queue` / `git q` through it.
fn install_completions(shell: clap_complete::Shell) -> Result<()> {
    let (dir, name) = completion_target(shell)
        .ok_or_else(|| anyhow::anyhow!("no completion location for {shell}"))?;
    std::fs::create_dir_all(&dir)?;
    let mut cmd = crate::cli_command();
    let mut buf: Vec<u8> = Vec::new();
    clap_complete::generate(shell, &mut cmd, "git-queue", &mut buf);
    let path = dir.join(name);
    std::fs::write(&path, &buf)?;
    println!("Installed {shell} completion: {}", path.display());
    if shell == clap_complete::Shell::Zsh {
        println!(
            "note: ensure {0} is on your $fpath and compinit runs, e.g. in ~/.zshrc:\n      \
             fpath=({0} $fpath); autoload -Uz compinit && compinit",
            dir.display()
        );
    }
    Ok(())
}

fn remove_completions() {
    for shell in [
        clap_complete::Shell::Bash,
        clap_complete::Shell::Zsh,
        clap_complete::Shell::Fish,
    ] {
        if let Some((dir, name)) = completion_target(shell) {
            let p = dir.join(name);
            if p.exists() && std::fs::remove_file(&p).is_ok() {
                println!("Removed {}.", p.display());
            }
        }
    }
}

/// `git queue completions <shell>` — print a completion script to stdout.
pub(crate) fn completions(shell: clap_complete::Shell) -> Result<()> {
    let mut cmd = crate::cli_command();
    clap_complete::generate(shell, &mut cmd, "git-queue", &mut std::io::stdout());
    Ok(())
}

/// Add a `git q` → `git queue` alias to the user's global git config.
fn install_git_alias() -> Result<()> {
    git::run(&["config", "--global", "alias.q", "queue"])?;
    println!("Added `git q` alias to your global git config (shortcut for `git queue`).");
    Ok(())
}

const EMBEDDED_SKILL: &str = include_str!("../skills/using-git-queue/SKILL.md");
const AGENTS_BEGIN: &str = "<!-- git-queue:agents:begin -->";
const AGENTS_END: &str = "<!-- git-queue:agents:end -->";

/// Idempotently write a marker-delimited git-queue section into AGENTS.md.
fn write_agents_md_section() -> Result<()> {
    let section = format!(
        "{AGENTS_BEGIN}
## git-queue (PR queues)

         This repo uses git-queue for stacked/queued PRs. Rules:

         - See `git queue --help` (man page) for every command; `git queue status`/`log` show the queue.
         - Never hand-rebase a queue branch: use `git queue commit`/`amend`/`move`/`checkout`.
         - After changing history, run `git queue sync` to requeue, push (lease) and refresh PRs.
         - PRs merge front-first; never merge a PR whose `git-queue/merge-order` status is red.
         - Commits carry `Stable-Commit-Id:` trailers — preserve commit messages when rewriting.
         {AGENTS_END}
"
    );
    let path = std::path::Path::new("AGENTS.md");
    let existing = std::fs::read_to_string(path).unwrap_or_default();
    let updated = match (existing.find(AGENTS_BEGIN), existing.find(AGENTS_END)) {
        (Some(a), Some(b)) if b > a => format!(
            "{}{}{}",
            &existing[..a],
            section.trim_end(),
            &existing[b + AGENTS_END.len()..]
        ),
        _ if existing.is_empty() => section,
        _ => format!(
            "{}
{}",
            existing.trim_end(),
            section
        ),
    };
    std::fs::write(path, updated)?;
    println!("Wrote the git-queue section of AGENTS.md.");
    Ok(())
}

fn strip_agents_md_section() -> Result<()> {
    let path = std::path::Path::new("AGENTS.md");
    let Ok(existing) = std::fs::read_to_string(path) else {
        return Ok(());
    };
    if let (Some(a), Some(b)) = (existing.find(AGENTS_BEGIN), existing.find(AGENTS_END)) {
        if b > a {
            let rest = format!("{}{}", &existing[..a], &existing[b + AGENTS_END.len()..]);
            if rest.trim().is_empty() {
                std::fs::remove_file(path).ok();
            } else {
                std::fs::write(path, rest)?;
            }
            println!("Removed the git-queue section of AGENTS.md.");
        }
    }
    Ok(())
}

/// `git queue doctor` — report-only diagnostics for merge-order enforcement.
pub(crate) fn doctor() -> Result<()> {
    git::ensure_repo()?;
    println!("git queue doctor — merge-order enforcement\n");

    match meta::gate().as_deref() {
        Some("status") => {
            println!("  \u{2713} gate: enabled (status mode)");
            println!(
                "    `git queue submit` posts a `{}` commit status on every open PR:",
                render::GATE_CONTEXT
            );
            println!("    green \u{2713} on the PR at the front of the queue, red \u{2717} (\u{201c}merge PR #N first\u{201d})");
            println!("    on the ones behind it.");
        }
        Some(other) => {
            println!("  ! gate: unknown mode `{other}` \u{2014} run `git queue setup` to (re)enable status mode");
        }
        None => {
            println!("  \u{2717} gate: not enabled \u{2014} run `git queue setup` to turn it on");
        }
    }

    if gh::ready() {
        println!("  \u{2713} GitHub CLI: authenticated");
    } else {
        println!("  ! GitHub CLI: not authenticated (`gh auth login`) \u{2014} needed for `submit` to post merge-order statuses");
    }

    println!("\nNote: the gate is advisory \u{2014} a red \u{2717} in the checks list warns reviewers off,");
    println!("but it does not disable the merge button.");
    Ok(())
}

/// `git queue create <name> [--base <branch>]` — new branch queued after the
/// current one (or on an explicit `--base` branch).
pub(crate) fn create(name: &str, base: Option<&str>, queue_flag: Option<&str>) -> Result<()> {
    git::ensure_repo()?;
    let trunk = meta::trunk()?;
    let parent = match base {
        Some(b) => {
            let b = resolve_branch_arg(b)?;
            if !git::branch_exists(&b) {
                bail!("base branch `{b}` does not exist");
            }
            b
        }
        None => git::current_branch()?,
    };
    // Every queue is named: inherit when extending, otherwise ask/take one.
    // `namespaced` decides whether the new branch lives under queue/<name>/…:
    // true when the queue name is explicit or the queue already follows the
    // convention — so you type short names and never the prefix (as with
    // edit), and plain-named queues stay plain.
    let (qname, namespaced) = if meta::parent(&parent).is_some() {
        let q = Queue::load()?;
        let line = q.line_through(&parent)?;
        match line_queue_name(&line) {
            Some(n) => {
                let ns = line
                    .branches
                    .first()
                    .is_some_and(|b| b.starts_with("queue/"));
                (n, ns)
            }
            None => bail!("this queue has no name; run `git queue name <name>` first"),
        }
    } else {
        require_queue_name(queue_flag, name)?
    };
    let name = if name.contains('/') || !namespaced {
        name.to_string()
    } else {
        format!("queue/{qname}/{name}")
    };
    let name = name.as_str();
    if git::branch_exists(name) {
        bail!("branch `{name}` already exists");
    }
    let parent_sha = git::rev_parse(&parent)?;

    git::create_branch(name, &parent)?;
    meta::set_parent(name, &parent)?;
    meta::set_parent_sha(name, &parent_sha)?;
    meta::set_branch_queue(name, &qname)?;
    meta::touch_queue(&qname);
    git::checkout(name)?;

    if parent == trunk {
        println!("Created `{name}` on trunk `{trunk}`. It is the front of a new queue.");
    } else if meta::parent(&parent).is_none() {
        println!("Created `{name}` on `{parent}`. It is the front of a new queue;");
        println!("its PR will target `{parent}` (the merge base), not `{trunk}`.");
    } else {
        println!("Created `{name}` after `{parent}` in the queue.");
    }
    println!("Make your commits, then `git queue submit` to open PRs.");
    Ok(())
}

/// `git queue edit` — open the whole queue in an editor. Every branch is a
/// `[name]` section; the commits beneath a header belong to that branch. The
/// commit sequence is fixed — commits cannot be reordered or deleted, only
/// assigned to branches — so editing means moving, renaming, adding, or
/// removing the `[name]` header lines. Branch refs simply move to the new
/// section boundaries; no commit is rewritten.
pub(crate) fn edit(queue_flag: Option<&str>) -> Result<()> {
    git::ensure_repo()?;
    if !git::worktree_clean() {
        bail!(
            "working tree has uncommitted changes; commit or stash them before editing the queue"
        );
    }
    let queue = Queue::load()?;
    let branch = git::current_branch()?;

    // Scope: the current queue line — all its branches, all their commits.
    // An untracked branch edits as one provisional section over trunk.
    let (line_branches, base, qname, explicit) = if queue.is_tracked(&branch) {
        let line = queue.line_through(&branch)?;
        if let Some(f) = &line.fork_at {
            eprintln!("warning: `{f}` has multiple children; editing this line only.");
        }
        let (qname, explicit) = match line_queue_name(&line) {
            Some(n) => (n, queue_flag.is_some()),
            None => require_queue_name(queue_flag, &branch)?,
        };
        (line.branches, line.base, qname, explicit)
    } else {
        let (qname, explicit) = require_queue_name(queue_flag, &branch)?;
        (vec![branch.clone()], queue.trunk, qname, explicit)
    };

    // Every commit of the line, oldest first (front of the queue at the top
    // of the file), plus how many belong to each branch.
    let mut all: Vec<(String, Option<String>, String)> = Vec::new();
    let mut counts: Vec<(String, usize)> = Vec::new();
    let mut parent = base.clone();
    for b in &line_branches {
        let commits = git::commits_between_with_ids(&parent, b)?;
        counts.push((b.clone(), commits.len()));
        all.extend(commits);
        parent = b.clone();
    }
    if all.is_empty() {
        bail!("the queue has no commits to edit");
    }

    // Whether short section names get namespaced to queue/<qname>/<short>:
    // when the line already follows that convention, or the queue name was
    // given explicitly. Plain-named queues stay plain (same rule as create).
    let namespaced = line_branches.iter().any(|b| b.starts_with("queue/")) || explicit;
    let display = |b: &str| -> String {
        b.strip_prefix(&format!("queue/{qname}/"))
            .unwrap_or(b)
            .to_string()
    };
    let resolve = |n: &str| -> String {
        if n.contains('/') || line_branches.iter().any(|b| b == n) || !namespaced {
            n.to_string()
        } else {
            format!("queue/{qname}/{n}")
        }
    };

    let assignments = run_queue_editor(&qname, &base, &counts, &all, &display)?;
    let segments = fold_segments(&assignments, &all)?;
    let segments: Vec<(String, String)> = segments
        .into_iter()
        .map(|(n, sha)| (resolve(&n), sha))
        .collect();

    // New names must be free.
    for (name, _) in &segments {
        if !line_branches.contains(name) && git::branch_exists(name) {
            bail!("branch `{name}` already exists; pick a different name");
        }
    }

    // Nothing moved and nothing renamed? Then there is nothing to apply.
    let unchanged = segments.len() == line_branches.len()
        && segments
            .iter()
            .zip(&line_branches)
            .all(|((n, tip), b)| n == b && git::rev_parse(b).is_ok_and(|s| &s == tip));
    if unchanged {
        println!("Queue unchanged.");
        return Ok(());
    }

    // Detach so refs can move freely, then place each branch at its section
    // boundary and wire up the parent pointers bottom-up.
    git::detach_head()?;
    let mut parent = base.clone();
    for (name, tip_sha) in &segments {
        if git::branch_exists(name) {
            git::force_ref(name, tip_sha)?;
        } else {
            git::create_branch(name, tip_sha)?;
        }
        meta::set_parent(name, &parent)?;
        meta::set_parent_sha(name, &git::rev_parse(&parent)?)?;
        meta::set_branch_queue(name, &qname)?;
        parent = name.clone();
    }
    meta::touch_queue(&qname);

    // Branches whose headers were removed are gone from the queue: their
    // commits now belong to other sections, so the old refs are redundant.
    let removed: Vec<String> = line_branches
        .iter()
        .filter(|b| !segments.iter().any(|(n, _)| &n == b))
        .cloned()
        .collect();
    for b in &removed {
        let pr = meta::pr(b);
        meta::untrack(b);
        git::run(&["branch", "-q", "-D", b])?;
        println!("Deleted `{b}` (its commits are covered by the remaining branches).");
        if let Some(n) = pr {
            println!(
                "note: its PR #{n} is still open on GitHub — close it, or repurpose it manually."
            );
        }
        if git::remote_branch(&meta::remote(), b).is_some() {
            println!(
                "note: it still exists on the remote; remove it with `git push {} --delete {b}`.",
                meta::remote()
            );
        }
    }

    let land = if segments.iter().any(|(n, _)| n == &branch) {
        branch
    } else {
        segments.last().map_or(branch, |s| s.0.clone())
    };
    git::checkout(&land)?;

    println!("Queue `{qname}` now has {} branches:", segments.len());
    let mut p = base;
    for (name, _) in &segments {
        println!("  {p}{name}");
        p = name.clone();
    }
    println!("Now on `{land}`. Run `git queue sync` to update the PRs.");
    Ok(())
}

/// `git queue tui` — open the current queue line in the interactive editor.
///
/// Enforces the non-TTY guard here (the engine is headless and never checks
/// for a terminal), loads the headless engine — which applies the
/// clean-worktree, empty-queue and forked-line guards — then hands off to the
/// ratatui view.
pub(crate) fn tui() -> Result<()> {
    git::ensure_repo()?;
    if !std::io::IsTerminal::is_terminal(&std::io::stdout()) {
        bail!(
            "`git queue tui` needs an interactive terminal; use `git queue edit` \
             for a non-interactive, scriptable queue editor"
        );
    }

    let engine = Engine::load()?;
    crate::view::run(engine)
}

/// Write the queue-edit file, open `$GIT_EDITOR` on it, and parse the result
/// into per-commit `(section name, sha token)` assignments in file order.
fn run_queue_editor(
    qname: &str,
    base: &str,
    counts: &[(String, usize)],
    all: &[(String, Option<String>, String)],
    display: &dyn Fn(&str) -> String,
) -> Result<Vec<(String, String)>> {
    let dir = std::path::PathBuf::from(git::out(&["rev-parse", "--git-dir"])?);
    let path = dir.join("QUEUE_EDIT");

    let mut body = String::new();
    body.push_str(&format!(
        "# Queue `{qname}` on `{base}` — assign commits to branches.\n\
         #\n\
         # A `[branch]` line starts a branch; the commits listed below it belong\n\
         # to that branch. The first section is the front of the queue (merges\n\
         # first). Move, rename, add, or remove the `[branch]` lines to change\n\
         # which branch a commit belongs to — but keep every commit line exactly\n\
         # where it is: commits cannot be reordered or deleted here.\n\
         # Removing a header dissolves that branch into its neighbours; adding\n\
         # one splits a branch in two. Short names are fine — they resolve\n\
         # within this queue. Lines starting with `#` are ignored.\n"
    ));
    let mut idx = 0;
    for (b, n) in counts {
        body.push_str(&format!("\n[{}]\n", display(b)));
        for (sha, id, subject) in &all[idx..idx + n] {
            // Same identity format as `git queue log`: the abbreviated
            // Stable-Commit-Id; sha only for commits that don't carry one.
            let token = match id {
                Some(id) => id.chars().take(10).collect::<String>(),
                None => sha[..sha.len().min(12)].to_string(),
            };
            body.push_str(&format!("{token} {subject}\n"));
        }
        idx += n;
    }
    std::fs::write(&path, body)?;

    let editor = git::out(&["var", "GIT_EDITOR"])?;
    let status = std::process::Command::new("sh")
        .arg("-c")
        .arg(format!("{editor} \"$1\""))
        .arg("sh")
        .arg(&path)
        .status()
        .context("failed to launch editor")?;
    if !status.success() {
        bail!("editor exited with an error; edit cancelled");
    }
    let raw = std::fs::read_to_string(&path)?;
    let _ = std::fs::remove_file(&path);

    let mut out = Vec::new();
    let mut headers: Vec<String> = Vec::new();
    let mut section: Option<String> = None;
    for line in raw.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
            let name = name.trim();
            if name.is_empty() {
                bail!("a `[]` header has no branch name");
            }
            headers.push(name.to_string());
            section = Some(name.to_string());
            continue;
        }
        let Some(sha) = line.split_whitespace().next().map(str::to_string) else {
            continue;
        };
        match &section {
            Some(s) => out.push((s.clone(), sha)),
            None => bail!("commit `{sha}` appears before any `[branch]` header"),
        }
    }
    for h in &headers {
        if !out.iter().any(|(s, _)| s == h) {
            bail!("branch `{h}` has no commits; remove its header or move commits beneath it");
        }
    }
    Ok(out)
}

/// Validate the edited assignments against the original commit order and fold
/// them into contiguous `(branch, tip_full_sha)` segments in queue order.
fn fold_segments(
    assignments: &[(String, String)],
    all: &[(String, Option<String>, String)],
) -> Result<Vec<(String, String)>> {
    if assignments.len() != all.len() {
        bail!(
            "expected {} commit lines but found {}; commits cannot be added or deleted here",
            all.len(),
            assignments.len()
        );
    }
    let mut segments: Vec<(String, String)> = Vec::new();
    let mut seen: Vec<String> = Vec::new();
    for (i, (name, token)) in assignments.iter().enumerate() {
        let (full_sha, id, _) = &all[i];
        let in_place = token.is_empty()
            || if token.starts_with("q-") {
                id.as_deref()
                    .is_some_and(|id| id.starts_with(token.as_str()))
            } else {
                full_sha.starts_with(token.as_str())
            };
        if !in_place {
            bail!("commit lines were reordered; commits cannot be reordered here — only assigned to branches");
        }
        match segments.last_mut() {
            Some((last, tip)) if last == name => *tip = full_sha.clone(),
            _ => {
                if seen.contains(name) {
                    bail!(
                        "branch `{name}` appears twice; a branch is one contiguous run of commits"
                    );
                }
                seen.push(name.clone());
                segments.push((name.clone(), full_sha.clone()));
            }
        }
    }
    Ok(segments)
}

/// `git queue track [--parent <branch>]` — adopt the current branch. Offers
/// to stamp `Stable-Commit-Id` trailers onto the adopted commits (a history rewrite,
/// so it asks first; `--stamp-ids`/`--no-stamp-ids` decide non-interactively).
pub(crate) fn track(
    parent: Option<String>,
    stamp_ids: bool,
    no_stamp_ids: bool,
    edit_after: bool,
    queue_flag: Option<&str>,
) -> Result<()> {
    git::ensure_repo()?;
    let trunk = meta::trunk()?;
    let branch = git::current_branch()?;
    if branch == trunk {
        bail!("cannot track the trunk branch itself");
    }
    if edit_after && !git::worktree_clean() {
        bail!("working tree has uncommitted changes; commit or stash them before `track --edit`");
    }
    let parent = match parent {
        Some(p) => resolve_branch_arg(&p)?,
        None => trunk,
    };
    if !git::branch_exists(&parent) {
        bail!("parent branch `{parent}` does not exist");
    }
    if !git::is_ancestor(&parent, &branch) {
        bail!(
            "`{parent}` is not an ancestor of `{branch}`; pass the correct --parent or rebase first"
        );
    }
    let base = git::merge_base(&parent, &branch)?;
    meta::set_parent(&branch, &parent)?;
    meta::set_parent_sha(&branch, &base)?;
    // Every queue is named: inherit when adopting into an existing queue,
    // otherwise ask/take one.
    let qname = {
        let q = Queue::load()?;
        let line = q.line_through(&branch)?;
        match line_queue_name(&line) {
            Some(n) => n,
            None => require_queue_name(queue_flag, &branch)?.0,
        }
    };
    meta::set_branch_queue(&branch, &qname)?;
    meta::touch_queue(&qname);
    println!("Tracking `{branch}` with parent `{parent}` in queue `{qname}`.");

    // Offer stable change identity to the adopted commits.
    let missing: Vec<String> = git::queue_ids(&format!("{base}..{branch}"))?
        .into_iter()
        .filter(|(_, id)| id.is_none())
        .map(|(sha, _)| sha)
        .collect();
    if missing.is_empty() {
        return edit_if_requested(edit_after, &base, &branch, queue_flag);
    }
    let n = missing.len();
    let stamp = if stamp_ids {
        true
    } else if no_stamp_ids {
        false
    } else if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        println!();
        println!("`{branch}` has {n} commit(s) without a Stable-Commit-Id (stable change identity");
        println!("that survives rebases; used for safe syncing and squash-merge detection).");
        println!("Stamping rewrites those commits — their hashes change. If the branch is");
        println!("already pushed, the next `git queue sync`/`submit` will force-push it (with");
        println!("lease), and anyone who fetched the old hashes will need to reset onto the");
        println!("new ones. Any open PR keeps working.");
        print!("Stamp them now? [Y/n] ");
        use std::io::Write;
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer).ok();
        matches!(answer.trim().to_lowercase().as_str(), "" | "y" | "yes")
    } else {
        eprintln!(
            "note: {n} commit(s) have no Stable-Commit-Id; re-run `git queue track --stamp-ids` to \
             stamp them (rewrites their hashes)."
        );
        false
    };
    if !stamp {
        return edit_if_requested(edit_after, &base, &branch, queue_flag);
    }
    if !git::worktree_clean() {
        eprintln!("note: working tree has uncommitted changes; skipping id stamping. Commit or");
        eprintln!("stash, then re-run `git queue track --stamp-ids`.");
        return edit_if_requested(edit_after, &base, &branch, queue_flag);
    }
    git::rebase_stamp_ids(&base, &branch, &missing)?;
    println!("Stamped {n} commit(s) with Stable-Commit-Ids (their hashes changed).");
    edit_if_requested(edit_after, &base, &branch, queue_flag)
}

/// The `--edit` tail of `track`: hand off to the queue editor, unless the
/// adopted branch is too small to divide.
fn edit_if_requested(
    requested: bool,
    base: &str,
    branch: &str,
    queue_flag: Option<&str>,
) -> Result<()> {
    if !requested {
        return Ok(());
    }
    if git::ahead_count(base, branch)? < 2 {
        println!("`{branch}` has fewer than 2 commits — nothing to divide.");
        return Ok(());
    }
    edit(queue_flag)
}

/// `git queue untrack` — forget the current branch's queue metadata.
pub(crate) fn untrack() -> Result<()> {
    git::ensure_repo()?;
    let branch = git::current_branch()?;
    meta::untrack(&branch);
    println!("Stopped tracking `{branch}`.");
    Ok(())
}

/// `git queue describe [-m <text>]` — set the description of what the current
/// branch/PR is about. It becomes the body of the PR (below the queue list) on
/// the next `submit`. Opens `$EDITOR` when `-m` is omitted.
pub(crate) fn describe(message: Option<String>) -> Result<()> {
    git::ensure_repo()?;
    let queue = Queue::load()?;
    let branch = git::current_branch()?;
    if !queue.is_tracked(&branch) {
        bail!("`{branch}` is not a queue branch; `git queue create`/`track` it first");
    }
    let line = queue.line_through(&branch)?;
    let Some(qname) = line_queue_name(&line) else {
        bail!("this queue has no name yet; run `git queue name <name>` first");
    };
    let text = match message {
        Some(m) => m,
        None => edit_description(
            &format!("queue `{qname}`"),
            meta::queue_description(&qname).as_deref(),
            "the whole queue (the \"About this queue\" section of every PR in it)",
        )?,
    };
    meta::set_queue_description(&qname, &text)?;
    meta::touch_queue(&qname);
    if text.trim().is_empty() {
        println!("Cleared the description of queue `{qname}`.");
    } else {
        println!("Saved the description of queue `{qname}`. Every PR in the queue shows it");
        println!("under \"About this queue\" on the next `git queue submit`/`sync`.");
    }
    Ok(())
}

/// `git queue describe-branch [-m <text>]` — describe what the current branch
/// is about; becomes the "About this branch" section of its PR.
pub(crate) fn describe_branch(message: Option<String>) -> Result<()> {
    git::ensure_repo()?;
    let queue = Queue::load()?;
    let branch = git::current_branch()?;
    if !queue.is_tracked(&branch) {
        bail!("`{branch}` is not a queue branch; `git queue create`/`track` it first");
    }
    let text = match message {
        Some(m) => m,
        None => edit_description(
            &format!("`{branch}`"),
            meta::description(&branch).as_deref(),
            "this branch (the \"About this branch\" section of its PR)",
        )?,
    };
    meta::set_description(&branch, &text)?;
    if text.trim().is_empty() {
        println!("Cleared the description for `{branch}`.");
    } else {
        println!(
            "Saved the description for `{branch}`. It will appear in the PR on `git queue submit`."
        );
    }
    Ok(())
}

/// `git queue name [<name>]` — show or set the current queue's name. Setting
/// records membership on every branch of the line.
pub(crate) fn name(new_name: Option<String>) -> Result<()> {
    git::ensure_repo()?;
    let queue = Queue::load()?;
    let branch = git::current_branch()?;
    if !queue.is_tracked(&branch) {
        bail!("`{branch}` is not a queue branch");
    }
    let line = queue.line_through(&branch)?;
    match new_name {
        None => match line_queue_name(&line) {
            Some(n) => println!("{n}"),
            None => println!("(this queue has no name; set one with `git queue name <name>`)"),
        },
        Some(n) => {
            meta::validate_queue_name(&n)?;
            for b in &line.branches {
                meta::set_branch_queue(b, &n)?;
            }
            meta::touch_queue(&n);
            println!("Named this queue `{n}` ({} branches).", line.branches.len());
        }
    }
    Ok(())
}

/// `git queue ls` — every queue in the repo, most recently touched first.
pub(crate) fn ls() -> Result<()> {
    git::ensure_repo()?;
    let queue = Queue::load()?;
    let current = git::current_branch().ok();

    // Group tracked lines by queue name (leaf-per-line; forks share a name).
    let mut queues: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();
    let mut unnamed: Vec<String> = Vec::new();
    for leaf in queue.leaves() {
        let Ok(line) = queue.line_through(&leaf) else {
            continue;
        };
        match line_queue_name(&line) {
            Some(n) => {
                let e = queues.entry(n).or_default();
                for b in &line.branches {
                    if !e.contains(b) {
                        e.push(b.clone());
                    }
                }
            }
            None => unnamed.push(line.branches.first().cloned().unwrap_or(leaf)),
        }
    }
    // Named queues with metadata but no live branches still show up.
    for n in meta::all_queue_names() {
        queues.entry(n).or_default();
    }
    if queues.is_empty() && unnamed.is_empty() {
        println!("No queues yet. Create one with `git queue create <name>`.");
        return Ok(());
    }
    let mut ordered: Vec<(String, Vec<String>)> = queues.into_iter().collect();
    ordered.sort_by_key(|(n, _)| std::cmp::Reverse(meta::queue_touched_at(n)));
    for (n, branches) in &ordered {
        let here = current
            .as_deref()
            .is_some_and(|c| branches.iter().any(|b| b == c));
        let marker = if here { "  ← current" } else { "" };
        let desc = meta::queue_description(n)
            .map(|d| {
                let first = d.lines().next().unwrap_or("").trim().to_string();
                format!("{first}")
            })
            .unwrap_or_default();
        println!(
            "{n}  ({} branch{}){desc}{marker}",
            branches.len(),
            if branches.len() == 1 { "" } else { "es" }
        );
        for b in branches {
            println!("    {b}");
        }
    }
    for front in unnamed {
        println!("(unnamed queue starting at `{front}` — run `git queue name <name>` from it)");
    }
    Ok(())
}

/// Open the user's git editor on a temp file seeded with `existing`, and return
/// the edited text (lines starting with `#` are stripped as comments).
fn edit_description(what: &str, existing: Option<&str>, becomes: &str) -> Result<String> {
    let dir = std::path::PathBuf::from(git::out(&["rev-parse", "--git-dir"])?);
    let path = dir.join("QUEUE_DESCRIBE");
    let template = format!(
        "{}\n\n# Describe {what}. This becomes the PR text for {becomes}.\n\
         # Lines starting with '#' are ignored.\n",
        existing.unwrap_or("")
    );
    std::fs::write(&path, template)?;

    let editor = git::out(&["var", "GIT_EDITOR"])?;
    let status = std::process::Command::new("sh")
        .arg("-c")
        .arg(format!("{editor} \"$1\""))
        .arg("sh") // $0
        .arg(&path) // $1
        .status()
        .context("failed to launch editor")?;
    if !status.success() {
        bail!("editor exited with an error; description unchanged");
    }
    let raw = std::fs::read_to_string(&path)?;
    let _ = std::fs::remove_file(&path);
    let cleaned: Vec<&str> = raw
        .lines()
        .filter(|l| !l.trim_start().starts_with('#'))
        .collect();
    Ok(cleaned.join("\n").trim().to_string())
}

/// `git queue status`
pub(crate) fn status() -> Result<()> {
    show_tree(false)
}

/// `git queue log` — the status tree, with each branch's commits indented one
/// level beneath it, newest first, each prefixed by its abbreviated Stable-Commit-Id.
pub(crate) fn log() -> Result<()> {
    show_tree(true)
}

fn show_tree(with_commits: bool) -> Result<()> {
    git::ensure_repo()?;
    let queue = Queue::load()?;
    let current = git::current_branch()?;

    // Choose a line to show: the current branch's; or, standing on trunk or a
    // base branch, the first queue rooted here.
    let anchor = if queue.is_tracked(&current) {
        current.clone()
    } else if let Some(child) = queue.children(&current).into_iter().next() {
        child
    } else if current == queue.trunk {
        if let Some(r) = queue.roots().into_iter().next() {
            r
        } else {
            println!("No queues yet. Create one with `git queue create <name>`.");
            return Ok(());
        }
    } else {
        println!("Branch `{current}` is not tracked. Adopt it with `git queue track`.");
        return Ok(());
    };

    // Show the WHOLE tree the anchor belongs to, forks included: the current
    // chain renders at indent 0, and each forked subtree renders one level in,
    // directly above the branch it forks from.
    let chain = queue.chain_to_base(&anchor)?;
    let root = chain[0].clone();
    let base = queue
        .parent_of(&root)
        .map(str::to_string)
        .ok_or_else(|| anyhow::anyhow!("`{root}` has no parent branch"))?;
    fn topdown(
        queue: &Queue,
        branch: &str,
        indent: usize,
        chain: &[String],
        out: &mut Vec<(String, usize)>,
    ) {
        let kids = queue.children(branch);
        let main = kids
            .iter()
            .find(|k| chain.contains(k))
            .or_else(|| kids.first())
            .cloned();
        if let Some(m) = &main {
            topdown(queue, m, indent, chain, out);
        }
        for k in kids.iter().filter(|k| Some(*k) != main.as_ref()) {
            topdown(queue, k, indent + 1, chain, out);
        }
        out.push((branch.to_string(), indent));
    }
    let mut ordered: Vec<(String, usize)> = Vec::new();
    topdown(&queue, &root, 0, &chain, &mut ordered);

    let branches: Vec<String> = ordered.iter().map(|(b, _)| b.clone()).collect();
    let mut entries = build_entries(&branches)?;
    for (e, (_, indent)) in entries.iter_mut().zip(&ordered) {
        e.indent = *indent;
        let parent = queue
            .parent_of(&e.branch)
            .map(str::to_string)
            .ok_or_else(|| anyhow::anyhow!("`{}` has no parent branch", e.branch))?;
        if e.conflicted {
            e.conflicts = git::conflict_files(&e.branch);
        }
        if with_commits {
            if let Ok(commits) = git::commits_with_ids(&format!("{parent}..{}", e.branch)) {
                e.commits = commits;
            }
        }
    }
    let tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
    let color = tty && std::env::var_os("NO_COLOR").is_none();
    let repo_url = if tty && terminal_renders_hyperlinks() {
        git::github_repo_url(&meta::remote())
    } else {
        None
    };
    print!(
        "{}",
        render::status_tree(
            &entries,
            &current,
            &base,
            base == queue.trunk,
            color,
            repo_url.as_deref()
        )
    );
    Ok(())
}

/// Best-effort detection of OSC 8 hyperlink support — there is no capability
/// query, so this is the allowlist heuristic other CLIs use.
fn terminal_renders_hyperlinks() -> bool {
    let var = |k: &str| std::env::var(k).unwrap_or_default();
    let term_program = var("TERM_PROGRAM");
    if matches!(
        term_program.as_str(),
        "iTerm.app" | "WezTerm" | "ghostty" | "Hyper" | "vscode" | "Tabby"
    ) {
        return true;
    }
    if !var("KITTY_WINDOW_ID").is_empty() || !var("WT_SESSION").is_empty() {
        return true;
    }
    if var("VTE_VERSION").parse::<u32>().is_ok_and(|v| v >= 5000) {
        return true;
    }
    if var("KONSOLE_VERSION")
        .parse::<u32>()
        .is_ok_and(|v| v >= 201_100)
    {
        return true;
    }
    let term = var("TERM");
    term.contains("kitty") || term.contains("wezterm") || term.contains("foot")
}

/// `git queue prev` / `down` — check out the parent branch.
pub(crate) fn prev() -> Result<()> {
    git::ensure_repo()?;
    let branch = git::current_branch()?;
    match meta::parent(&branch) {
        Some(p) => {
            git::checkout(&p)?;
            Ok(())
        }
        None => bail!("`{branch}` has no tracked parent"),
    }
}

/// `git queue next` / `up` — check out the child branch.
pub(crate) fn next() -> Result<()> {
    git::ensure_repo()?;
    let queue = Queue::load()?;
    let branch = git::current_branch()?;
    let kids = queue.children(&branch);
    match kids.len() {
        0 => bail!("`{branch}` is at the top of its queue (no children)"),
        1 => git::checkout(&kids[0]),
        _ => {
            let list = kids.join("\n  ");
            bail!("`{branch}` has multiple children; check one out directly:\n  {list}")
        }
    }
}

/// `git queue sync [--no-push]` — pull in commits others pushed to queue
/// branches, requeue the whole queue onto the latest trunk, and (by default)
/// push every branch back with `--force-with-lease` so remote work is never
/// clobbered.
pub(crate) fn sync(no_push: bool) -> Result<()> {
    git::ensure_repo()?;
    if git::rebase_in_progress() {
        bail!("a rebase is already in progress; finish it (`git rebase --continue`/`--abort`) then re-run `git queue sync`");
    }
    std::env::set_var(git::GUARD_ENV, "1"); // suppress our hooks during internal git ops
    let mut queue = Queue::load()?;
    let remote = meta::remote();
    let original = git::current_branch()?;
    let started_clean = git::worktree_clean();

    println!("Fetching `{remote}`...");
    if let Err(e) = git::fetch(&remote) {
        eprintln!("warning: fetch failed; syncing against local refs only: {e}");
    }

    // Bring every line's local base (trunk, release branches, ...) up to its
    // remote tip. Bases are treated as remote-canonical, like trunk always was.
    for base in queue.bases() {
        if let Some(remote_base) = git::remote_trunk(&remote, &base) {
            let tip = git::rev_parse(&remote_base)?;
            if original == base {
                let _ = git::merge_ff_only(&remote_base);
            } else {
                let _ = git::force_ref(&base, &tip);
            }
        }
    }

    // Heal branches orphaned by a merged-and-deleted parent. `--delete-branch`
    // (and manual branch deletion) removes the branch's git config, including
    // our `queueParent`, leaving its children pointing at a branch that no
    // longer exists. Reparent those onto trunk.
    queue = heal_dangling_parents(queue)?;

    // Prune branches whose PRs have merged: reparent their children onto the
    // nearest surviving ancestor (trunk, once the bottom lands) and drop them
    // from the queue. The requeue below then rebases the survivors onto trunk.
    queue = prune_landed_by_id(queue)?;
    if gh::ready() {
        queue = prune_merged(queue)?;
    }

    // Stamp Stable-Commit-Ids onto any queue commits that lack them: identity
    // is one of the invariants sync converges. Message-only rewrites, so no
    // conflicts are possible; --update-refs carries branch refs along.
    for leaf in queue.leaves() {
        let Ok(line) = queue.line_through(&leaf) else {
            continue;
        };
        let top = line.top().to_string();
        let Ok(ids) = git::queue_ids(&format!("{}..{top}", line.base)) else {
            continue;
        };
        let missing: Vec<String> = ids
            .into_iter()
            .filter(|(_, id)| id.is_none())
            .map(|(sha, _)| sha)
            .collect();
        if missing.is_empty() {
            continue;
        }
        let n = missing.len();
        git::rebase_stamp_ids(&line.base, &top, &missing)?;
        for (i, br) in line.branches.iter().enumerate() {
            let parent = if i == 0 {
                line.base.clone()
            } else {
                line.branches[i - 1].clone()
            };
            meta::set_parent_sha(br, &git::rev_parse(&parent)?)?;
        }
        println!("Stamped {n} commit(s) with Stable-Commit-Ids (queue ending at `{top}`).");
    }
    git::checkout_quiet(&original)?;

    // Pull in commits teammates pushed to our queue branches (bottom-up).
    for branch in queue.topo_order() {
        match incorporate_remote(&branch, &remote, &original)? {
            Some(RemoteAction::FastForwarded) => {
                println!("Pulled remote commits into `{branch}` (fast-forward).");
            }
            Some(RemoteAction::Pulled(n)) => {
                println!("Pulled {n} teammate commit(s) into `{branch}`.");
            }
            None => {}
        }
    }

    // Detach HEAD while refs move: `git replay` updates refs in place without
    // touching the worktree, so requeueing the checked-out branch would leave
    // the worktree stale. Detaching makes the checkout below a real one.
    git::detach_head()?;

    // Reconcile the whole forest onto updated parents (new engine).
    let report = requeue::requeue_forest(&queue)?;

    // Return to where we started before pushing. Requeueing moves refs without
    // touching the worktree, so if `original` itself was requeued the files on
    // disk are stale; with a clean starting tree it is safe to snap them to the
    // branch tip.
    git::checkout_quiet(&original)?;
    if started_clean {
        git::reset_hard_head()?;
    } else {
        eprintln!(
            "note: the worktree had local changes when sync started; if `{original}` was \
             rebased, run `git reset --hard` once your changes are safe."
        );
    }

    // Push every branch back, with lease, unless asked not to. A push can
    // legitimately fail mid-sync — e.g. GitHub marks queued PRs merged and
    // auto-deletes their branches the moment an earlier push makes their
    // commits reachable from the base — so keep going and say so instead of
    // dying half-way through.
    let mut push_failures = 0usize;
    if !no_push {
        for branch in queue.topo_order() {
            if push_would_mislabel_child(&queue, &branch) {
                push_failures += 1;
                continue;
            }
            println!("Pushing `{branch}`...");
            if let Err(e) = git::push(&remote, &branch) {
                eprintln!("warning: push of `{branch}` failed: {e:#}");
                push_failures += 1;
            }
        }
        if push_failures > 0 {
            eprintln!(
                "note: {push_failures} push(es) failed. If a PR merged or its branch was \
                 deleted on the remote mid-sync, re-run `git queue sync` — it will prune \
                 merged branches and settle the rest."
            );
        }
    }

    // Reconcile PRs on every *published* line — one with at least one PR
    // anywhere in it, including a PR that predates the branch becoming a
    // queue. Missing PRs are opened; existing ones get their base, numbered
    // title and nav block rewritten. Lines with no PRs at all stay local:
    // `git queue submit` publishes those deliberately.
    if !no_push && gh::ready() {
        for leaf in queue.leaves() {
            let Ok(line) = queue.line_through(&leaf) else {
                continue;
            };
            let published = line
                .branches
                .iter()
                .any(|b| gh::find(b).ok().flatten().is_some());
            if !published {
                continue;
            }
            if line_queue_name(&line).is_none() {
                eprintln!(
                    "warning: skipping PR reconciliation for the queue ending at `{leaf}` — it \
                     has no name. Run `git queue name <name>` from one of its branches."
                );
                continue;
            }
            let outcome = reconcile_line_prs(&line, false, None, false)?;
            report_line(&line, &outcome, "Reconciled")?;
        }
    }

    if report.conflicted.is_empty() {
        let bases = queue.bases();
        match bases.as_slice() {
            [] => println!("Nothing to sync yet."),
            [one] => println!("Queue is in sync with `{one}`."),
            many => println!(
                "Queues are in sync with their bases: {}.",
                many.iter()
                    .map(|b| format!("`{b}`"))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    } else {
        requeue::warn_conflicts(&report.conflicted);
    }
    Ok(())
}

/// Reparent tracked branches whose parent is gone (not trunk, not tracked, and
/// no such branch exists) onto trunk. Returns the reloaded queue if anything
/// changed.
fn heal_dangling_parents(queue: Queue) -> Result<Queue> {
    let mut changed = false;
    for b in queue.topo_order() {
        let parent = match queue.parent_of(&b) {
            Some(p) => p.to_string(),
            None => continue,
        };
        if queue.is_tracked(&parent) || git::branch_exists(&parent) {
            continue;
        }
        meta::set_parent(&b, &queue.trunk)?;
        eprintln!(
            "note: `{b}`'s parent `{parent}` is gone (merged?); reparented onto `{}`.",
            queue.trunk
        );
        changed = true;
    }
    if changed {
        Queue::load()
    } else {
        Ok(queue)
    }
}

/// Refuse to push a branch whose tip contains an OPEN child PR's head tip.
/// GitHub marks a PR merged the instant its base branch contains its head —
/// permanently — so pushing a collapsed parent (or the parent of a branch
/// whose commits were all moved away) would mislabel a mid-queue PR as merged
/// while the front of the queue is still open. Returns true if pushing is safe.
fn push_would_mislabel_child(queue: &Queue, branch: &str) -> bool {
    for child in queue.children(branch) {
        let (Ok(ct), Ok(bt)) = (git::rev_parse(&child), git::rev_parse(branch)) else {
            continue;
        };
        if !git::is_ancestor(&ct, &bt) {
            continue; // normal queue shape: child extends parent
        }
        let open_pr = gh::find(&child)
            .ok()
            .flatten()
            .is_some_and(|pr| pr.state == "OPEN");
        if open_pr {
            eprintln!(
                "warning: not pushing `{branch}` — its tip contains the head of `{child}`'s \
                 OPEN PR, and GitHub would permanently mark that PR as merged. The queue \
                 looks collapsed (or `{child}` has no commits of its own); untangle it with \
                 `git queue move`, or close the child PR first."
            );
            return true;
        }
    }
    false
}

/// Reparent the children of any MERGED-PR branch onto their nearest surviving
/// ancestor, untrack the merged branches, and return the reloaded queue.
fn prune_merged(queue: Queue) -> Result<Queue> {
    use std::collections::HashSet;
    let mut merged: HashSet<String> = HashSet::new();
    for b in queue.topo_order() {
        // Best-effort: ignore lookup failures (e.g. not a GitHub repo).
        if let Some(pr) = gh::find(&b).ok().flatten() {
            if pr.state == "MERGED" {
                merged.insert(b);
            }
        }
    }
    drop_from_queue(queue, &merged, "has merged")
}

/// Drop branches whose every commit already landed on trunk, detected by
/// Stable-Commit-Id correspondence — which survives squash merges that destroy both
/// SHAs and patch-ids. Only branches where *all* commits carry an id are
/// considered (no guessing). Pure git; needs no GitHub access.
fn prune_landed_by_id(queue: Queue) -> Result<Queue> {
    use std::collections::HashSet;
    let mut landed: HashSet<String> = HashSet::new();
    for b in queue.topo_order() {
        let Some(parent) = queue.parent_of(&b).map(str::to_string) else {
            continue;
        };
        let (Ok(pb), Ok(tb)) = (
            git::merge_base(&parent, &b),
            git::merge_base(&queue.trunk, &b),
        ) else {
            continue;
        };
        let Ok(ids) = git::queue_ids(&format!("{pb}..{b}")) else {
            continue;
        };
        if ids.is_empty() || ids.iter().any(|(_, id)| id.is_none()) {
            continue;
        }
        let Ok(trunk_text) = git::log_messages(&format!("{tb}..{}", queue.trunk)) else {
            continue;
        };
        if ids
            .iter()
            .all(|(_, id)| id.as_deref().is_some_and(|s| trunk_text.contains(s)))
        {
            landed.insert(b);
        }
    }
    drop_from_queue(
        queue,
        &landed,
        "has landed on trunk (Stable-Commit-Ids found)",
    )
}

/// Untrack every branch in `gone`, reparenting survivors onto their nearest
/// surviving ancestor, and return the reloaded queue.
fn drop_from_queue(
    queue: Queue,
    gone: &std::collections::HashSet<String>,
    why: &str,
) -> Result<Queue> {
    if gone.is_empty() {
        return Ok(queue);
    }
    for b in queue.topo_order() {
        if gone.contains(&b) {
            continue;
        }
        let Some(current_parent) = queue.parent_of(&b).map(str::to_string) else {
            continue;
        };
        let mut new_parent = current_parent.clone();
        while gone.contains(&new_parent) {
            new_parent = queue
                .parent_of(&new_parent)
                .map_or_else(|| queue.trunk.clone(), std::string::ToString::to_string);
        }
        if new_parent != current_parent {
            meta::set_parent(&b, &new_parent)?;
        }
    }
    for b in gone {
        meta::untrack(b);
        println!("`{b}` {why} — dropped from the queue, children reparented.");
    }
    Queue::load()
}

enum RemoteAction {
    FastForwarded,
    Pulled(usize),
}

/// Integrate `origin/<branch>` into the local branch, if the remote has commits
/// we don't. Fast-forwards when we have nothing unique; otherwise replays our
/// unique commits onto the remote tip (patch-id dedup, conflict markers
/// persisted). Returns what it did, or `None` if there was nothing to pull.
fn incorporate_remote(branch: &str, remote: &str, current: &str) -> Result<Option<RemoteAction>> {
    let Some(remote_sha) = git::remote_branch(remote, branch) else {
        return Ok(None); // branch not on the remote yet
    };
    let local_sha = git::rev_parse(branch)?;
    if local_sha == remote_sha {
        return Ok(None);
    }
    // If the remote tip is a position this local branch has already been at
    // (it's in the branch's reflog), the remote holds nothing we haven't
    // seen — it's just stale relative to a local rewrite (amend, move, an
    // unpushed requeue). Pulling it back in would re-apply our own commits
    // on top of their old selves and manufacture self-conflicts; the rewrite
    // is authoritative and `--force-with-lease` replaces the remote at push.
    if git::was_previous_position(branch, &remote_sha) {
        return Ok(None);
    }
    if git::is_ancestor(&remote_sha, &local_sha) {
        return Ok(None); // we're ahead; nothing to pull
    }
    if git::is_ancestor(&local_sha, &remote_sha) {
        // Remote strictly ahead: fast-forward.
        if branch == current {
            git::merge_ff_only(&format!("{remote}/{branch}"))?;
        } else {
            git::force_ref(branch, &remote_sha)?;
        }
        return Ok(Some(RemoteAction::FastForwarded));
    }
    // Diverged: pull in only what is genuinely new. Stable-Commit-Id correspondence
    // separates teammate work from stale copies of our own rewritten commits;
    // id-less commits fall back to patch-equivalence (`git cherry`).
    let mb = git::merge_base(&format!("{remote}/{branch}"), branch)?;
    let local_ids: std::collections::HashSet<String> = git::queue_ids(&format!("{mb}..{branch}"))?
        .into_iter()
        .filter_map(|(_, id)| id)
        .collect();
    let patch_fresh: std::collections::HashSet<String> = git::cherry_fresh(branch, &remote_sha)?
        .into_iter()
        .collect();
    let fresh: Vec<String> = git::queue_ids(&format!("{mb}..{remote_sha}"))?
        .into_iter()
        .filter(|(sha, id)| match id {
            Some(id) => !local_ids.contains(id),
            None => patch_fresh.contains(sha),
        })
        .map(|(sha, _)| sha)
        .collect();
    if fresh.is_empty() {
        return Ok(None); // the remote only has stale copies of our own commits
    }
    let n = fresh.len();
    git::cherry_pick_persist(branch, &fresh)?;
    Ok(Some(RemoteAction::Pulled(n)))
}

/// The name of the queue a line belongs to: recorded membership first, then
/// the `queue/<name>/…` branch-naming convention.
fn line_queue_name(line: &Line) -> Option<String> {
    for b in &line.branches {
        if let Some(n) = meta::branch_queue(b) {
            return Some(n);
        }
    }
    for b in &line.branches {
        if let Some(rest) = b.strip_prefix("queue/") {
            if let Some((n, _)) = rest.split_once('/') {
                return Some(n.to_string());
            }
        }
    }
    None
}

/// Ask for (or take) a queue name, mandatorily. Order: explicit flag, TTY
/// prompt, then — non-interactive with no flag — a fallback so scripts keep
/// working, announced loudly.
fn require_queue_name(flag: Option<&str>, fallback: &str) -> Result<(String, bool)> {
    if let Some(n) = flag {
        meta::validate_queue_name(n)?;
        return Ok((n.to_string(), true));
    }
    if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        print!("Name this queue: ");
        use std::io::Write;
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer).ok();
        let answer = answer.trim().to_string();
        if !answer.is_empty() {
            meta::validate_queue_name(&answer)?;
            return Ok((answer, true));
        }
    }
    let fallback = fallback.replace('/', "-");
    meta::validate_queue_name(&fallback)?;
    eprintln!("note: queue named `{fallback}` (rename any time with `git queue name <name>`).");
    Ok((fallback, false))
}

/// Resolve a branch argument, accepting short names inside namespaced queues:
/// an exact branch name wins; otherwise a unique `queue/*/<arg>` match does.
fn resolve_branch_arg(arg: &str) -> Result<String> {
    if git::branch_exists(arg) {
        return Ok(arg.to_string());
    }
    let suffix = format!("/{arg}");
    let matches: Vec<String> = meta::tracked_branches()
        .into_iter()
        .filter(|b| b.ends_with(&suffix))
        .collect();
    match matches.as_slice() {
        [one] => Ok(one.clone()),
        [] => Ok(arg.to_string()), // let the caller produce its natural error
        many => bail!("`{arg}` is ambiguous: {}", many.join(", ")),
    }
}

/// The outcome of reconciling one line's PRs.
struct LinePrs {
    entries: Vec<Entry>,
    prs: Vec<Option<PrRef>>,
}

/// Reconcile a line's PRs with its branches: revive or create missing PRs,
/// then rewrite base, numbered title and the shared nav block on every open
/// one. When `push` names a remote, each active branch is pushed (front-first,
/// so bases exist) before its PR is touched — submit's path; sync passes
/// `None` because it already pushed. `strict` bails on branches with no
/// commits beyond their base (submit); otherwise they are skipped with a note
/// (sync must not die mid-reconciliation).
fn reconcile_line_prs(
    line: &Line,
    draft: bool,
    push: Option<&str>,
    strict: bool,
) -> Result<LinePrs> {
    let Some(queue_name) = line_queue_name(line) else {
        bail!("this queue has no name (needed for its PRs); run `git queue name <name>` first");
    };
    let queue_description = meta::queue_description(&queue_name).unwrap_or_default();
    meta::touch_queue(&queue_name);
    let branches = &line.branches;
    let total = branches.len();
    let base_of = |i: usize| -> String {
        if i == 0 {
            line.base.clone()
        } else {
            branches[i - 1].clone()
        }
    };

    // Look up existing PRs once. A MERGED PR is "frozen": we must not push to
    // it, recreate it, or edit its base. A CLOSED PR is revived below — GitHub
    // closes a queued PR when its base branch is deleted (e.g. `--delete-branch`
    // on the PR below), and we must not skip it.
    let existing: Vec<Option<gh::Pr>> = branches
        .iter()
        .map(|b| gh::find(b))
        .collect::<Result<_>>()?;
    let frozen: Vec<bool> = existing
        .iter()
        .map(|p| p.as_ref().map(|pr| pr.state.as_str()) == Some("MERGED"))
        .collect();

    // Guard: don't open an empty PR (already-landed branches are skipped).
    let mut empty = vec![false; total];
    for (i, b) in branches.iter().enumerate() {
        if frozen[i] {
            continue;
        }
        if git::ahead_count(&base_of(i), b)? == 0 {
            if strict {
                bail!(
                    "`{b}` has no commits beyond `{}`; add a commit before submitting",
                    base_of(i)
                );
            }
            if existing[i].is_none() {
                eprintln!(
                    "note: `{b}` has no commits beyond `{}`; not opening a PR for it.",
                    base_of(i)
                );
                empty[i] = true;
            }
        }
    }

    // Pass 1: (optionally push and) create-or-revive each active branch's PR.
    for (i, b) in branches.iter().enumerate() {
        if frozen[i] || empty[i] {
            continue;
        }
        let base = base_of(i);
        if let Some(remote) = push {
            // Don't hand GitHub a reason to mislabel the next PR as merged:
            // pushing a branch whose tip contains an open child PR's head
            // makes that permanent.
            let collapsed_child = branches.get(i + 1).is_some_and(|child| {
                existing[i + 1]
                    .as_ref()
                    .is_some_and(|pr| pr.state == "OPEN")
                    && match (git::rev_parse(child), git::rev_parse(b)) {
                        (Ok(ct), Ok(bt)) => git::is_ancestor(&ct, &bt),
                        _ => false,
                    }
            });
            if collapsed_child {
                eprintln!(
                    "warning: not pushing `{b}` — its tip contains the head of the next \
                     PR in the queue, and GitHub would permanently mark that PR as merged. \
                     Untangle with `git queue move`, or close the child PR first."
                );
            } else {
                println!("Pushing `{b}`...");
                git::push(remote, b)?;
            }
        }
        let subject = git::tip_subject(b)?;
        let title = render::numbered_title(&subject, i, total);
        let number = match &existing[i] {
            Some(pr) if pr.state == "OPEN" => pr.number,
            // CLOSED (base branch was deleted): reopen it, or open a fresh PR if
            // it can't be reopened (its old base is gone).
            Some(pr) => match gh::reopen(pr.number) {
                Ok(()) => pr.number,
                Err(_) => gh::create(b, &base, &title, "Opening…", draft)?,
            },
            None => {
                let n = gh::create(b, &base, &title, "Opening…", draft)?;
                println!("Opened PR #{n} for `{b}` (base `{base}`).");
                n
            }
        };
        meta::set_pr(b, number)?;
    }

    // Re-read active PRs now that any new ones exist.
    let mut full: Vec<Option<gh::Pr>> = vec![None; total];
    let mut prs: Vec<Option<PrRef>> = vec![None; total];
    for (i, b) in branches.iter().enumerate() {
        if frozen[i] {
            prs[i] = existing[i].as_ref().map(pr_ref); // keep untouched
            continue;
        }
        if let Some(pr) = gh::find(b)? {
            prs[i] = Some(pr_ref(&pr));
            full[i] = Some(pr);
        }
    }

    // Pass 2: write correct base, numbered title and shared nav block on the
    // ACTIVE PRs (frozen ones are left exactly as they are).
    let entries: Vec<Entry> = branches
        .iter()
        .enumerate()
        .map(|(i, b)| Entry {
            branch: b.clone(),
            pr: prs[i].clone(),
            conflicted: git::has_conflict_markers(b),
            conflicts: Vec::new(),
            commits: Vec::new(),
            indent: 0,
        })
        .collect();

    for (i, b) in branches.iter().enumerate() {
        if frozen[i] {
            continue;
        }
        let number = match &prs[i] {
            Some(p) => p.number,
            None => continue,
        };
        // Renumber the PR's existing title rather than imposing the commit
        // subject: titles are review-facing and often hand-written (especially
        // on PRs that predate the queue). New PRs were just created from the
        // tip subject, so this is a no-op for them.
        let subject = match &full[i] {
            Some(pr) if !pr.title.trim().is_empty() => pr.title.clone(),
            _ => git::tip_subject(b)?,
        };
        let title = render::numbered_title(&subject, i, total);
        let nav = render::nav_block(&entries, b, &line.base, &queue_name);
        let description = if let Some(d) = meta::description(b).filter(|d| !d.trim().is_empty()) {
            d
        } else {
            // No local description: adopt the PR's existing body (minus any
            // previous nav block) so updating a PR that predates the queue
            // never wipes what its author wrote.
            let adopted = full[i]
                .as_ref()
                .map(|pr| render::strip_block(&pr.body).trim().to_string())
                .unwrap_or_default();
            let adopted = if adopted == "Opening…" {
                String::new()
            } else {
                adopted
            };
            if !adopted.is_empty() {
                meta::set_description(b, &adopted)?;
            }
            adopted
        };
        let body = render::compose_body(&queue_description, &description, &nav);
        gh::edit(number, &base_of(i), &title, &body)?;
    }

    Ok(LinePrs { entries, prs })
}

/// Apply the status gate (if enabled) and print the line's PR listing.
fn report_line(line: &Line, outcome: &LinePrs, heading: &str) -> Result<()> {
    let gate = meta::gate();
    let gated = gate.as_deref() == Some("status");
    if let Some(other) = gate.as_deref().filter(|g| *g != "status") {
        eprintln!("warning: unknown queue.gate mode `{other}` — no merge gate applied; run `git queue setup` to enable status mode");
    }
    if gated {
        apply_status_gate(&outcome.entries)?;
    }
    let total = line.branches.len();
    println!("\n{heading} {total} PR(s):");
    for (i, b) in line.branches.iter().enumerate() {
        if let Some(p) = &outcome.prs[i] {
            println!("  [{}/{}] {}  {}", i + 1, total, b, p.url);
        }
    }
    if gated {
        println!("Merge gate active: the front PR's `{}` status is \u{2713}; the rest are \u{2717} until it lands.", render::GATE_CONTEXT);
    }
    Ok(())
}

/// `git queue submit [--draft]` — push the current queue line and open/update
/// its numbered PRs.
pub(crate) fn submit(draft: bool) -> Result<()> {
    git::ensure_repo()?;
    if !gh::ready() {
        bail!("`gh` is not installed or not authenticated; run `gh auth login`");
    }
    let queue = Queue::load()?;
    let current = git::current_branch()?;
    if !queue.is_tracked(&current) {
        bail!("`{current}` is not tracked; run `git queue create` or `git queue track` first");
    }
    let line = queue.line_through(&current)?;
    if let Some(fork) = &line.fork_at {
        eprintln!("warning: `{fork}` has multiple children; submitting only this line.");
    }
    let remote = meta::remote();
    let outcome = reconcile_line_prs(&line, draft, Some(&remote), true)?;
    report_line(&line, &outcome, "Submitted")
}

fn pr_ref(pr: &gh::Pr) -> PrRef {
    PrRef {
        number: pr.number,
        url: pr.url.clone(),
        state: pr.state.clone(),
        review: pr.review_decision.clone(),
    }
}

/// Resolve a user-supplied commit-ish for queue commands: a git revision, or
/// a `Stable-Commit-Id` — full, or a unique prefix such as the abbreviated
/// form `git queue log` displays. Id lookup is scoped to the line's commits.
fn resolve_queue_rev(line: &Line, arg: &str) -> Result<String> {
    let arg = arg.trim();
    if arg.starts_with("q-") {
        let top = line.top();
        let ids = git::queue_ids(&format!("{}..{top}", line.base))?;
        let matches: Vec<&(String, Option<String>)> = ids
            .iter()
            .filter(|(_, id)| {
                id.as_deref()
                    .is_some_and(|i| i == arg || i.starts_with(arg))
            })
            .collect();
        match matches.as_slice() {
            [(sha, _)] => return Ok(sha.clone()),
            [] => {
                // Fall through: maybe it's a real revision that happens to
                // start with `q-`.
                if let Ok(sha) = git::rev_parse(arg) {
                    return Ok(sha);
                }
                bail!("no commit in this queue has Stable-Commit-Id `{arg}`");
            }
            many => bail!(
                "Stable-Commit-Id prefix `{arg}` is ambiguous ({} matches); use more characters",
                many.len()
            ),
        }
    }
    git::rev_parse(arg).with_context(|| format!("`{arg}` is not a commit"))
}

/// `git queue move <commit>[..<commit>] --new-parent <commit>` — relocate a
/// commit (or an inclusive range of consecutive commits) to directly follow
/// `--new-parent`, within one PR or across PRs. The whole line is rewritten in
/// place: everything after the removal and insertion points is rebased, branch
/// refs ride along (`--update-refs`), and conflicts are persisted as markers.
/// The moved commits join the branch segment that `--new-parent` belongs to.
pub(crate) fn move_commits(spec: &str, new_parent: &str) -> Result<()> {
    git::ensure_repo()?;
    if git::rebase_in_progress() {
        bail!("a rebase is already in progress; finish it (`git rebase --continue`/`--abort`) then re-run `git queue move`");
    }
    if !git::worktree_clean() {
        bail!("working tree has uncommitted changes; commit or stash them before moving commits");
    }
    std::env::set_var(git::GUARD_ENV, "1");
    let queue = Queue::load()?;
    let original = git::current_branch()?;
    if !queue.is_tracked(&original) {
        bail!("`{original}` is not a queue branch");
    }
    let line = queue.line_through(&original)?;
    if let Some(fork) = &line.fork_at {
        eprintln!("warning: `{fork}` has multiple children; moving within this line only (other lines requeue on the next sync).");
    }
    let top = line.top().to_string();

    // The line's commits, front-first, and their positions.
    let commits = git::commits_between(&line.base, &top)?;
    let pos: std::collections::HashMap<&str, usize> = commits
        .iter()
        .enumerate()
        .map(|(i, (sha, _))| (sha.as_str(), i))
        .collect();
    let resolve = |rev: &str| -> Result<String> { resolve_queue_rev(&line, rev) };

    // <commit> or an inclusive <first>..<last> range.
    let (first, last) = if let Some((a, b)) = spec.split_once("..") {
        (resolve(a)?, resolve(b)?)
    } else {
        let one = resolve(spec)?;
        (one.clone(), one)
    };
    let in_line = |sha: &String, what: &str| -> Result<usize> {
        pos.get(sha.as_str()).copied().ok_or_else(|| {
            anyhow::anyhow!(
                "{what} `{}` is not part of this queue (`{}`..`{top}`)",
                &sha[..8],
                line.base
            )
        })
    };
    let (mut ia, mut ib) = (in_line(&first, "commit")?, in_line(&last, "commit")?);
    if ia > ib {
        std::mem::swap(&mut ia, &mut ib);
    }

    // --new-parent: a queue commit outside the moved range, or the base tip
    // (which moves the range to the very front of the queue).
    let p = resolve(new_parent)?;
    let after = if p == git::rev_parse(&line.base)? {
        None
    } else {
        let ip = in_line(&p, "--new-parent")?;
        if (ia..=ib).contains(&ip) {
            bail!("--new-parent is inside the range being moved");
        }
        Some(ip)
    };

    let already = match after {
        None => ia == 0,
        Some(ip) => ip + 1 == ia,
    };
    if already {
        println!("Nothing to move: the commits already follow `{new_parent}`.");
        return Ok(());
    }

    let move_shas: Vec<String> = commits[ia..=ib].iter().map(|(s, _)| s.clone()).collect();
    let after_sha = after.map(|ip| commits[ip].0.clone());
    let tip_before = git::rev_parse(&top)?;

    git::rebase_reorder_persist(&line.base, &top, &move_shas, after_sha.as_deref())?;

    if git::rev_parse(&top)? == tip_before {
        bail!("the move did not apply (the rebase was aborted); the queue is unchanged");
    }

    // Refresh every branch's rebase anchor to its parent's new tip.
    for (i, br) in line.branches.iter().enumerate() {
        let parent = if i == 0 {
            line.base.clone()
        } else {
            line.branches[i - 1].clone()
        };
        meta::set_parent_sha(br, &git::rev_parse(&parent)?)?;
    }

    // The rebase leaves HEAD on the top branch; go back and refresh the
    // worktree (we required a clean tree above, so this is safe).
    git::checkout_quiet(&original)?;
    git::reset_hard_head()?;

    let dest = match &after {
        None => format!("the front of the queue (directly on `{}`)", line.base),
        Some(ip) => {
            let (sha, subject) = &commits[*ip];
            format!("directly after {} ({subject})", &sha[..8])
        }
    };
    println!("Moved {} commit(s) to {dest}.", move_shas.len());

    let mut conflicted = Vec::new();
    for (i, br) in line.branches.iter().enumerate() {
        if git::has_conflict_markers(br) {
            conflicted.push(br.clone());
        }
        let parent = if i == 0 {
            line.base.clone()
        } else {
            line.branches[i - 1].clone()
        };
        if git::rev_parse(br)? == git::rev_parse(&parent)? {
            eprintln!("note: `{br}` no longer has any commits of its own.");
        }
    }
    if conflicted.is_empty() {
        println!(
            "Run `git queue sync` (or `submit`) to push the rewritten queue and refresh its PRs."
        );
    } else {
        requeue::warn_conflicts(&conflicted);
    }
    Ok(())
}

/// Hidden `stamp-todo` subcommand: `GIT_SEQUENCE_EDITOR` for id stamping.
/// Marks the picks named by `GIT_QUEUE_REWORD_SHAS` as `reword`, so git stops
/// at each one and our `GIT_EDITOR` (add-queue-id) appends the trailer.
/// Untouched picks keep their SHAs where possible.
pub(crate) fn stamp_todo(path: &std::path::Path) -> Result<()> {
    let shas: Vec<String> = std::env::var("GIT_QUEUE_REWORD_SHAS")
        .context("GIT_QUEUE_REWORD_SHAS is not set")?
        .split_whitespace()
        .map(str::to_string)
        .collect();
    let todo = std::fs::read_to_string(path)?;
    let mut rewritten = Vec::new();
    let mut marked = 0usize;
    for line in todo.lines() {
        let mut it = line.split_whitespace();
        let is_target = it.next() == Some("pick")
            && it
                .next()
                .is_some_and(|abbrev| shas.iter().any(|f| f.starts_with(abbrev)));
        if is_target {
            marked += 1;
            rewritten.push(format!("reword{}", &line[4..]));
        } else {
            rewritten.push(line.to_string());
        }
    }
    if marked != shas.len() {
        bail!(
            "todo mismatch: expected {} pick(s) to reword, found {marked}",
            shas.len()
        );
    }
    std::fs::write(path, rewritten.join("\n") + "\n")?;
    Ok(())
}

/// Hidden `reorder-todo` subcommand: the `GIT_SEQUENCE_EDITOR` used by
/// [`git::rebase_reorder_persist`]. Relocates the pick lines named by
/// `GIT_QUEUE_MOVE_SHAS` to directly follow the pick for `GIT_QUEUE_MOVE_AFTER`
/// (or to the top of the todo when it is empty). `update-ref` lines stay put,
/// which is what carries branch membership.
pub(crate) fn reorder_todo(path: &std::path::Path) -> Result<()> {
    let shas: Vec<String> = std::env::var("GIT_QUEUE_MOVE_SHAS")
        .context("GIT_QUEUE_MOVE_SHAS is not set")?
        .split_whitespace()
        .map(str::to_string)
        .collect();
    let after = std::env::var("GIT_QUEUE_MOVE_AFTER").unwrap_or_default();

    let todo = std::fs::read_to_string(path)?;
    let pick_sha = |line: &str| -> Option<String> {
        let mut it = line.split_whitespace();
        (it.next() == Some("pick")).then(|| it.next().unwrap_or("").to_string())
    };
    // Todo picks use abbreviated SHAs of the original commits.
    let matches = |abbrev: &str, full: &str| !abbrev.is_empty() && full.starts_with(abbrev);

    let mut moved = Vec::new();
    let mut rest = Vec::new();
    for line in todo.lines() {
        let is_moved = pick_sha(line).is_some_and(|a| shas.iter().any(|f| matches(&a, f)));
        if is_moved {
            moved.push(line.to_string());
        } else {
            rest.push(line.to_string());
        }
    }
    if moved.len() != shas.len() {
        bail!(
            "todo mismatch: expected {} pick(s) to move, found {}",
            shas.len(),
            moved.len()
        );
    }
    let idx = if after.is_empty() {
        0
    } else {
        match rest
            .iter()
            .position(|l| pick_sha(l).is_some_and(|a| matches(&a, &after)))
        {
            Some(i) => i + 1,
            None => bail!("todo mismatch: --new-parent pick not found"),
        }
    };
    rest.splice(idx..idx, moved);
    std::fs::write(path, rest.join("\n") + "\n")?;
    Ok(())
}

/// Hidden `add-queue-id` subcommand: the commit-msg hook body. Stamps a
/// `Stable-Commit-Id` trailer on the message being committed, but only on tracked
/// queue branches and only for non-empty messages. Silent otherwise — it runs
/// on every commit in a hooked repo.
pub(crate) fn add_queue_id(path: &std::path::Path) -> Result<()> {
    if git::ensure_repo().is_err() {
        return Ok(());
    }
    // During an id-stamping rebase HEAD is detached; the driver vouches for
    // the commits instead of the branch check.
    let stamping = std::env::var("GIT_QUEUE_STAMP_ALL").is_ok();
    if !stamping {
        match git::current_branch() {
            Ok(branch) => {
                if meta::parent(&branch).is_none() {
                    return Ok(());
                }
            }
            // Detached: stamp only inside a queue-editing session, where a
            // plain `git commit` inserts a new queue commit.
            Err(_) => {
                if meta::detached_state().is_none() {
                    return Ok(());
                }
            }
        }
    }
    let msg = std::fs::read_to_string(path).unwrap_or_default();
    let has_content = msg
        .lines()
        .any(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'));
    if !has_content {
        return Ok(());
    }
    git::add_trailer_to_file(path, &ident::new_id())
}

/// `git queue checkout <commit>` — detach HEAD on a commit of the current
/// queue (named by SHA or Stable-Commit-Id) for in-place editing. From there,
/// plain `git commit` INSERTS a new commit after it and `git commit --amend`
/// REVISES it (message — and Stable-Commit-Id — carried over); either way the
/// rest of the queue rebases on top, via the hooks or `git queue requeue`.
pub(crate) fn checkout(arg: &str) -> Result<()> {
    git::ensure_repo()?;
    std::env::set_var(git::GUARD_ENV, "1");
    let queue = Queue::load()?;

    // The line in play: from the current branch, or — already detached via a
    // previous `git queue checkout` — from the recorded top branch.
    let line = if let Ok(current) = git::current_branch() {
        if !queue.is_tracked(&current) {
            bail!("`{current}` is not a queue branch");
        }
        queue.line_through(&current)?
    } else if let Some((_, top)) = meta::detached_state() {
        queue.line_through(&top)?
    } else {
        bail!("HEAD is detached outside a queue-editing session; check out a queue branch first");
    };
    let top = line.top().to_string();

    // Checking out a branch of the line reattaches and ends the session
    // (short names resolve inside namespaced queues).
    let reattach = line
        .branches
        .iter()
        .find(|b| *b == arg || b.ends_with(&format!("/{arg}")))
        .cloned()
        .or_else(|| (arg == line.base).then(|| line.base.clone()));
    if let Some(target) = reattach {
        let arg = target.as_str();
        if !git::tracked_clean() {
            bail!("stage or tracked files have changes; commit or stash them first");
        }
        git::checkout_quiet(arg)?;
        meta::clear_detached_state();
        println!("Back on `{arg}`.");
        return Ok(());
    }

    let sha = resolve_queue_rev(&line, arg)?;
    let commits = git::commits_between(&line.base, &top)?;
    if !commits.iter().any(|(s, _)| s == &sha) {
        bail!(
            "`{arg}` is not a commit of this queue (`{}`..`{top}`)",
            line.base
        );
    }
    if !git::tracked_clean() {
        bail!(
            "stage or tracked files have changes; commit or stash them before `git queue checkout`"
        );
    }

    git::run(&["checkout", "-q", "--detach", &sha])?;
    meta::set_detached_state(&sha, &top)?;
    let subject = git::tip_subject("HEAD")?;
    println!("Detached at {} ({subject}).", &sha[..8]);
    println!("Edit away — `git add` then:");
    println!("  git commit           inserts a NEW commit right after this one");
    println!("  git commit --amend   revises this commit (its Stable-Commit-Id is kept)");
    println!("The rest of the queue rebases on top automatically (with hooks installed);");
    println!("otherwise run `git queue requeue`. Return with `git queue checkout {top}`.");
    Ok(())
}

/// Reintegrate after editing at a detached queue commit: rebase everything
/// that followed the original commit onto the new HEAD (branch refs ride
/// along via --update-refs), re-anchor the line, and stay detached at the
/// new commit so editing can continue.
fn reintegrate_detached(auto: bool, original: &str, top: &str) -> Result<()> {
    let head = git::rev_parse("HEAD")?;
    if head == original {
        if !auto {
            println!("Nothing to reintegrate: HEAD is still the checked-out commit.");
        }
        return Ok(());
    }
    git::rebase_persist(&head, original, top)?;
    // The rebase leaves HEAD on `top`; go back to the edited commit.
    git::run(&["checkout", "-q", "--detach", &head])?;
    meta::set_detached_state(&head, top)?;

    let queue = Queue::load()?;
    let line = queue.line_through(top)?;
    let mut conflicted = Vec::new();
    for (i, br) in line.branches.iter().enumerate() {
        let parent = if i == 0 {
            line.base.clone()
        } else {
            line.branches[i - 1].clone()
        };
        meta::set_parent_sha(br, &git::rev_parse(&parent)?)?;
        if git::has_conflict_markers(br) {
            conflicted.push(br.clone());
        }
    }
    if let Some(qname) = line_queue_name(&line) {
        meta::touch_queue(&qname);
    }
    println!(
        "Reintegrated: the rest of the queue is rebased onto {} — still detached here.",
        &head[..8]
    );
    if conflicted.is_empty() {
        println!(
            "When you're done editing: `git queue checkout {top}` to reattach, then \
             `git queue sync` to push and refresh PRs."
        );
    } else {
        requeue::warn_conflicts(&conflicted);
    }
    Ok(())
}

/// `git queue yank` — close every open (non-merged) PR in the current queue.
/// Merged PRs are left alone; local branches and metadata are untouched.
pub(crate) fn yank() -> Result<()> {
    git::ensure_repo()?;
    if !gh::ready() {
        bail!("`gh` is not installed or not authenticated; run `gh auth login`");
    }
    let queue = Queue::load()?;
    let current = git::current_branch()?;
    if !queue.is_tracked(&current) {
        bail!("`{current}` is not a queue branch");
    }
    let line = queue.line_through(&current)?;
    let mut closed = 0;
    for b in &line.branches {
        if let Some(pr) = gh::find(b)? {
            if pr.state == "OPEN" {
                gh::close(pr.number)?;
                println!("Closed #{} ({b})", pr.number);
                closed += 1;
            }
        }
    }
    match closed {
        0 => println!("No open PRs in this queue to close."),
        n => println!("Closed {n} open PR(s). Merged PRs and local branches are untouched."),
    }
    Ok(())
}

/// `git queue commit [-m <msg>]` — make a NEW commit on the current branch,
/// then requeue all descendants onto the new tip (`git replay`, with a
/// marker-persisting fallback on conflict).
pub(crate) fn commit(message: Option<String>) -> Result<()> {
    git::ensure_repo()?;
    // Suppress our own hooks for the internal git calls; we requeue explicitly.
    std::env::set_var(git::GUARD_ENV, "1");
    let queue = Queue::load()?;
    let current = git::current_branch()?;

    git::commit(message.as_deref())?;

    if !queue.is_tracked(&current) {
        return Ok(()); // not a queue branch; just a normal commit
    }
    // Change identity from birth: if the commit-msg hook isn't installed,
    // stamp the Stable-Commit-Id trailer here (before descendants requeue).
    if git::queue_id_of("HEAD").is_none() {
        git::amend_head_add_queue_id(&ident::new_id())?;
    }
    let report = requeue::propagate(&queue, &current)?;
    finish_requeue(&report, &current);
    Ok(())
}

/// `git queue amend` — fold STAGED changes into the current branch's tip commit
/// via `git history fixup`, atomically updating every descendant.
pub(crate) fn amend() -> Result<()> {
    git::ensure_repo()?;
    std::env::set_var(git::GUARD_ENV, "1");
    let current = git::current_branch()?;
    if !git::staged_changes() {
        bail!("nothing staged — `git add` the changes you want to fold into `{current}` first");
    }
    // `git history fixup` may report a conflict (non-zero), but it can also exit
    // 0 while doing nothing when the fold would conflict with a descendant.
    // Detect BOTH: verify the commit actually changed before claiming success —
    // otherwise we'd falsely tell the user their work was folded.
    let before = git::rev_parse(&current)?;
    let reported_conflict = git::history_fixup("HEAD")?;
    let after = git::rev_parse(&current)?;
    if reported_conflict || before == after {
        bail!(
            "amend could not fold your changes into `{current}`: doing so would conflict with a \
             descendant branch, so nothing was changed (your staged changes are intact).\n\
             Resolve the conflict on the descendant first, or use `git queue commit` to add a \
             separate commit instead."
        );
    }
    refresh_descendant_anchors(&current)?;
    println!("Amended the tip commit of `{current}` and updated all descendants.");
    Ok(())
}

/// `git queue reword [<commit>]` — rewrite a commit message via
/// `git history reword`, atomically updating descendants. Defaults to HEAD.
pub(crate) fn reword(commit: Option<String>) -> Result<()> {
    git::ensure_repo()?;
    std::env::set_var(git::GUARD_ENV, "1");
    let current = git::current_branch()?;
    let target = match commit {
        Some(c) if c.starts_with("q-") => {
            let queue = Queue::load()?;
            if !queue.is_tracked(&current) {
                bail!("`{current}` is not a queue branch; ids can only name queued commits");
            }
            let line = queue.line_through(&current)?;
            resolve_queue_rev(&line, &c)?
        }
        Some(c) => c,
        None => "HEAD".to_string(),
    };
    if git::history_reword(&target)? {
        bail!("reword aborted (rewriting `{target}` would conflict with a descendant); nothing changed");
    }
    refresh_descendant_anchors(&current)?;
    println!("Reworded `{target}` and updated descendants of `{current}`.");
    Ok(())
}

/// `git queue requeue` — requeue descendants of the current branch onto its
/// current tip. `--auto` (used by hooks) stays quiet when there's nothing to do
/// and on non-queue branches.
pub(crate) fn requeue(auto: bool) -> Result<()> {
    git::ensure_repo()?;
    std::env::set_var(git::GUARD_ENV, "1");
    // A queue-editing session (git queue checkout) reintegrates instead.
    if git::current_branch().is_err() {
        if let Some((original, top)) = meta::detached_state() {
            return reintegrate_detached(auto, &original, &top);
        }
        if auto {
            return Ok(());
        }
        bail!("HEAD is detached; check out a branch first");
    }
    let queue = Queue::load()?;
    let current = git::current_branch()?;
    meta::clear_detached_state(); // attached again: any old session is over
    if !queue.is_tracked(&current) && current != queue.trunk {
        if auto {
            return Ok(());
        }
        bail!("`{current}` is not part of a queue");
    }
    let report = requeue::propagate(&queue, &current)?;
    if auto && report.is_empty() && report.conflicted.is_empty() {
        return Ok(());
    }
    finish_requeue(&report, &current);
    Ok(())
}

/// Report the outcome of a requeue (loud warning if markers were persisted).
fn finish_requeue(report: &requeue::Report, branch: &str) {
    if !report.conflicted.is_empty() {
        requeue::warn_conflicts(&report.conflicted);
    } else if !report.is_empty() {
        println!(
            "Requeueed {} descendant branch(es) of `{branch}`.",
            report.requeued.len()
        );
    }
}

/// After git-history rewrote `branch`'s history, its descendants' stored parent
/// anchors are stale; refresh them to the new parent tips.
fn refresh_descendant_anchors(branch: &str) -> Result<()> {
    let queue = Queue::load()?;
    for b in queue.descendants_topo(branch) {
        if let Some(parent) = queue.parent_of(&b) {
            let ptip = git::rev_parse(parent)?;
            meta::set_parent_sha(&b, &ptip)?;
        }
    }
    Ok(())
}

const HOOK_BEGIN: &str = "# >>> git-queue >>>";
const HOOK_END: &str = "# <<< git-queue <<<";

fn hook_snippet(only_amend: bool) -> String {
    let gate = if only_amend {
        "[ \"$1\" = \"amend\" ] || exit 0\n"
    } else {
        ""
    };
    format!(
        "{HOOK_BEGIN}\n\
         [ -n \"$GIT_QUEUE_IN_REQUEUE\" ] && exit 0\n\
         {gate}command -v git-queue >/dev/null 2>&1 && git-queue requeue --auto || true\n\
         {HOOK_END}\n"
    )
}

/// The commit-msg hook: stamp a `Stable-Commit-Id` trailer on commits made on queue
/// branches, so every change has a stable identity from birth.
fn id_hook_snippet() -> String {
    format!(
        "{HOOK_BEGIN}\n\
         command -v git-queue >/dev/null 2>&1 && git-queue add-queue-id \"$1\" || true\n\
         {HOOK_END}\n"
    )
}

/// `git queue hooks install` — make plain `git commit`/amend auto-requeue.
fn hooks_install() -> Result<()> {
    git::ensure_repo()?;
    let dir = std::path::PathBuf::from(git::out(&["rev-parse", "--git-path", "hooks"])?);
    std::fs::create_dir_all(&dir)?;
    install_hook(&dir.join("post-commit"), &hook_snippet(false))?;
    install_hook(&dir.join("post-rewrite"), &hook_snippet(true))?;
    install_hook(&dir.join("commit-msg"), &id_hook_snippet())?;
    println!("Installed git-queue hooks. Plain `git commit` and `git commit --amend` on a");
    println!("queue branch will now auto-requeue descendants.");
    Ok(())
}

/// Remove the git-queue hook blocks (invoked by `git queue setup --undo`).
fn hooks_uninstall() -> Result<()> {
    git::ensure_repo()?;
    let dir = std::path::PathBuf::from(git::out(&["rev-parse", "--git-path", "hooks"])?);
    for name in ["post-commit", "post-rewrite", "commit-msg"] {
        remove_hook(&dir.join(name))?;
    }
    println!("Removed git-queue hooks.");
    Ok(())
}

fn install_hook(path: &std::path::Path, snippet: &str) -> Result<()> {
    let contents = std::fs::read_to_string(path).unwrap_or_default();
    if contents.contains(HOOK_BEGIN) {
        return Ok(()); // already installed
    }
    let new = if contents.trim().is_empty() {
        format!("#!/bin/sh\n{snippet}")
    } else {
        // Append to an existing hook without clobbering it.
        format!("{}\n{snippet}", contents.trim_end())
    };
    std::fs::write(path, new)?;
    make_executable(path)?;
    Ok(())
}

fn remove_hook(path: &std::path::Path) -> Result<()> {
    let Ok(contents) = std::fs::read_to_string(path) else {
        return Ok(());
    };
    let (Some(start), Some(end)) = (contents.find(HOOK_BEGIN), contents.find(HOOK_END)) else {
        return Ok(());
    };
    let after = end + HOOK_END.len();
    let mut stripped = String::new();
    stripped.push_str(&contents[..start]);
    stripped.push_str(contents[after..].trim_start_matches('\n'));
    // If nothing but a shebang/whitespace remains, remove the hook entirely.
    if stripped
        .lines()
        .all(|l| l.trim().is_empty() || l.starts_with("#!"))
    {
        std::fs::remove_file(path)?;
    } else {
        std::fs::write(path, stripped)?;
    }
    Ok(())
}

#[cfg(unix)]
fn make_executable(path: &std::path::Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = std::fs::metadata(path)?.permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms)?;
    Ok(())
}

#[cfg(not(unix))]
fn make_executable(_path: &std::path::Path) -> Result<()> {
    Ok(())
}

/// Assemble render entries (branch + cached PR) for a bottom-first branch list.
fn build_entries(branches: &[String]) -> Result<Vec<Entry>> {
    let mut entries = Vec::with_capacity(branches.len());
    for b in branches {
        let pr = meta::pr(b).map(|number| PrRef {
            number,
            url: String::new(),
            state: "?".to_string(),
            review: None,
        });
        entries.push(Entry {
            branch: b.clone(),
            pr,
            // Detect markers live so `status` can never go stale.
            conflicted: git::has_conflict_markers(b),
            conflicts: Vec::new(),
            commits: Vec::new(),
            indent: 0,
        });
    }
    Ok(entries)
}