omni-dev 0.37.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
//! The worktrees daemon service.
//!
//! A thin adapter that hosts the cross-window [`WorktreesRegistry`] under the
//! daemon's lifecycle and exposes register/heartbeat/unregister/list/tree/open
//! over the control socket, plus a tray submenu with a per-window "focus" action.
//! The `open` op (#1266) focuses/opens an arbitrary worktree folder in VS Code
//! through the **same** launcher path the tray uses, so a socket client (the
//! companion's double-click) shares the tested guard and launcher resolution
//! rather than duplicating them.
//!
//! All registry state and liveness logic (the `Mutex<HashMap>`, TTL reaping, the
//! entry cap/eviction) lives in [`crate::worktrees`]; this adapter only routes
//! ops, renders the menu/status, and drives the VS Code launcher. Like the
//! Snowflake service it is a cheap, in-memory adapter — no async setup, no
//! secret persisted.
//!
//! The adapter also computes the **per-worktree git enrichment** (current
//! branch, ahead/behind counts, and the parent repository a linked worktree
//! belongs to) on read via `git2` (#1186), keeping the companion a thin reporter
//! of raw folder paths (ADR-0040). The engine stores only what the companion
//! sends; disk I/O for the enrichment lives here, alongside the launcher, never
//! under the registry lock.
//!
//! The `tree` op (#1265) inverts the data model for the companion's tree view:
//! from the open windows the adapter derives the **distinct repositories**, then
//! enumerates **all** of each repo's worktrees (main working tree +
//! [`Repository::worktrees`]), enriches each (reusing [`git_status`]), tags the
//! GitHub identity of `origin`, and joins the open windows back on by
//! canonicalized path. The open-window registry stays the liveness source;
//! "is a window open on it?" becomes a per-worktree attribute. All of this is
//! git disk I/O, so it runs on a blocking thread, never under the registry lock.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};

use anyhow::{anyhow, bail, Context, Result};
use chrono::{DateTime, Utc};

use crate::github_rate_limit::{
    resolve_rate_limit_with, RateLimitCache, RateLimitResource, RateLimitSnapshot,
};
use crate::pr_status::{PrBadge, PrCheckState, PrResolution, PrStatusCache, PrTarget};
use async_trait::async_trait;
use git2::{Repository, RepositoryState, Status, StatusOptions, WorktreeLockStatus};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::sync::watch;
use tokio::sync::Mutex as AsyncMutex;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use crate::daemon::service::{
    DaemonService, MenuAction, MenuItem, MenuSnapshot, ServiceStatus, ServiceStream,
};
use crate::worktrees::{RegisterRequest, WindowEntry, WorktreesRegistry};

/// The worktrees service name (the control-socket routing key).
pub const SERVICE_NAME: &str = "worktrees";

/// The tray submenu title.
const SUBMENU_TITLE: &str = "Worktrees";

/// Environment override for the VS Code launcher used by the "focus" tray
/// action, for when the daemon runs under launchd with a minimal `PATH`.
const VSCODE_BIN_ENV: &str = "OMNI_DEV_VSCODE_BIN";

/// Environment override for [`menu_refresh_interval`] (whole seconds; a blank,
/// non-numeric, or `0` value falls back to [`DEFAULT_MENU_REFRESH_INTERVAL`]).
const ENV_MENU_REFRESH_INTERVAL: &str = "OMNI_DEV_DAEMON_MENU_REFRESH";

/// Default cadence at which the background task recomputes the tray menu snapshot
/// off the main thread when `OMNI_DEV_DAEMON_MENU_REFRESH` is unset. The macOS
/// tray polls `menu()` ~1 Hz and always serves this cache, never doing git I/O on
/// the GUI thread (which would peg a core and stall shutdown — the #1186
/// regression); the interval only governs how stale that cached branch/sync state
/// may be when the menu is opened.
///
/// Raised from 2 s to 10 s (#1305): this refresh is an independent per-window git
/// walk that the subscription-stream coalescing (#1303) never touched — it was
/// the dominant idle-CPU cost — so relaxing it cuts that cost ~5× while leaving
/// menu open-latency unchanged (the cache still serves instantly).
const DEFAULT_MENU_REFRESH_INTERVAL: Duration = Duration::from_secs(10);

/// The resolved tray menu-refresh cadence: `OMNI_DEV_DAEMON_MENU_REFRESH` (whole
/// seconds) when valid, else [`DEFAULT_MENU_REFRESH_INTERVAL`].
fn menu_refresh_interval() -> Duration {
    crate::daemon::server::duration_secs_from_env(
        ENV_MENU_REFRESH_INTERVAL,
        DEFAULT_MENU_REFRESH_INTERVAL,
    )
}

/// Environment override for [`pr_poll_interval`] — the cadence at which the PR
/// badge poller re-asks GitHub **while a badge is still pending** (whole seconds;
/// a blank, non-numeric, or `0` value falls back to [`DEFAULT_PR_POLL_INTERVAL`]).
const ENV_PR_POLL_INTERVAL: &str = "OMNI_DEV_DAEMON_PR_POLL";

/// Default cadence for the PR badge poller while CI is in flight (#1337).
///
/// Matches `gh pr checks --watch`, which uses 10 s when a human is actively
/// watching a run — which is exactly this situation. It is affordable because the
/// poll costs **1 point** regardless of how many repos, worktrees, or windows are
/// open: 10 s sustained is ~360 points/hour against a 5,000/hour budget, and only
/// while something is actually pending.
const DEFAULT_PR_POLL_INTERVAL: Duration = Duration::from_secs(10);

/// The ceiling the poller backs off to once every badge is terminal.
///
/// Nothing is expected to change, so this is a liveness heartbeat, not a watch.
/// The 30-minute figure is the cross-tool consensus for background PR polling
/// (vscode-pull-request-github's backoff ceiling, gh-dash's and GitLens's
/// defaults). The backoff exists for battery and wakeups rather than budget — at
/// 1 point per poll the budget never binds.
const MAX_PR_POLL_INTERVAL: Duration = Duration::from_secs(30 * 60);

/// How long after fresh work (a push, or an added target) the poller holds its
/// fast [`DEFAULT_PR_POLL_INTERVAL`] cadence before escalating *within* pending
/// (#1389, fix 5). Two minutes covers the window where a just-pushed run is most
/// likely to report; past it, a still-pending badge (a long build, a zombie suite)
/// is watched more cheaply. See [`next_pr_poll_delay`].
const PENDING_FAST_WINDOW: Duration = Duration::from_secs(2 * 60);

/// The ceiling the poller escalates to *while still pending* once
/// [`PENDING_FAST_WINDOW`] has passed (#1389, fix 5). Below the terminal
/// [`MAX_PR_POLL_INTERVAL`] because a pending badge is expected to change soon,
/// just not soon enough to justify pinning `base` — 60 s caps a 20-minute CI run
/// at ~50 calls instead of ~120.
const PENDING_MAX_INTERVAL: Duration = Duration::from_secs(60);

/// The cadence floor the poller is held to while the shared GitHub budget is
/// at/over [`WARN_PERCENT`](crate::github_rate_limit::WARN_PERCENT) (#1389, fix 6).
/// Five minutes makes the daemon's contribution to an already-strained budget
/// negligible while still recovering promptly once the window resets — a pause in
/// all but name. See [`budget_throttled_delay`].
const BUDGET_THROTTLE_INTERVAL: Duration = Duration::from_secs(5 * 60);

/// Environment override for [`pr_debounce_interval`] — the settle window the PR
/// poller waits after the change-notify fires before snapshotting (whole seconds;
/// a blank, non-numeric, or `0` value falls back to [`DEFAULT_PR_DEBOUNCE`]).
const ENV_PR_DEBOUNCE: &str = "OMNI_DEV_DAEMON_PR_DEBOUNCE";

/// Default settle window for the PR-poll change-notify debounce (#1389, fix 2).
///
/// A VS Code restart unregisters then re-registers its windows one-by-one over
/// several seconds, each bump waking the poller; a daemon restart re-registers the
/// same way. Waiting for ~2 s of quiet before snapshotting collapses the whole
/// storm into **one** fetch on the final watch set instead of one per window.
const DEFAULT_PR_DEBOUNCE: Duration = Duration::from_secs(2);

/// The resolved PR-poll cadence: `OMNI_DEV_DAEMON_PR_POLL` (whole seconds) when
/// valid, else [`DEFAULT_PR_POLL_INTERVAL`].
fn pr_poll_interval() -> Duration {
    crate::daemon::server::duration_secs_from_env(ENV_PR_POLL_INTERVAL, DEFAULT_PR_POLL_INTERVAL)
}

/// The resolved PR-poll debounce settle window: `OMNI_DEV_DAEMON_PR_DEBOUNCE`
/// (whole seconds) when valid, else [`DEFAULT_PR_DEBOUNCE`].
fn pr_debounce_interval() -> Duration {
    crate::daemon::server::duration_secs_from_env(ENV_PR_DEBOUNCE, DEFAULT_PR_DEBOUNCE)
}

/// Environment override for [`open_pr_ttl`] — how long the daemon reuses a repo's
/// `gh pr list` result before re-fetching (whole seconds; a blank, non-numeric, or
/// `0` value falls back to [`DEFAULT_OPEN_PR_TTL`]).
const ENV_OPEN_PR_TTL: &str = "OMNI_DEV_DAEMON_OPEN_PR_TTL";

/// Default TTL for the shared open-PR cache (#1389, fix 7). Matches the extension's
/// former per-window `gh pr list` cache (#1296): serving "Open Pull Request…" — and
/// the extension's transient badge fallback — from the daemon means N windows now
/// dedupe to **one** counted `gh` per repo per TTL, rather than one per window.
const DEFAULT_OPEN_PR_TTL: Duration = Duration::from_secs(60);

/// The `--json` fields the daemon requests from `gh pr list`, mirroring the
/// extension's `PR_JSON_FIELDS` so the forwarded array parses into its
/// `PullRequest` shape unchanged.
const OPEN_PR_JSON_FIELDS: &str = "number,title,url,headRefName,baseRefName,isDraft,state,author";

/// The `gh pr list --limit` cap — high enough to list a repo's open PRs in one call
/// (parity with the extension's `PR_LIST_LIMIT`).
const OPEN_PR_LIST_LIMIT: &str = "100";

/// The resolved open-PR cache TTL: `OMNI_DEV_DAEMON_OPEN_PR_TTL` (whole seconds)
/// when valid, else [`DEFAULT_OPEN_PR_TTL`].
fn open_pr_ttl() -> Duration {
    crate::daemon::server::duration_secs_from_env(ENV_OPEN_PR_TTL, DEFAULT_OPEN_PR_TTL)
}

/// Environment override for [`rate_limit_poll_interval`] — the cadence at which
/// the GitHub rate-limit monitor re-reads `/rate_limit` (whole seconds; a blank,
/// non-numeric, or `0` value falls back to [`DEFAULT_RATE_LIMIT_POLL_INTERVAL`]).
const ENV_RATE_LIMIT_POLL_INTERVAL: &str = "OMNI_DEV_DAEMON_RATE_LIMIT_POLL";

/// Default cadence for the GitHub rate-limit monitor (#1375).
///
/// A fixed 60 s is fine and simple: querying `/rate_limit` is **exempt** — it
/// spends nothing against any budget — so unlike the PR poller this cadence has no
/// budget concern and needs no adaptive backoff. One free `gh` subprocess a minute
/// keeps `daemon status` current enough to catch a slow drain.
const DEFAULT_RATE_LIMIT_POLL_INTERVAL: Duration = Duration::from_secs(60);

/// The resolved rate-limit-poll cadence: `OMNI_DEV_DAEMON_RATE_LIMIT_POLL` (whole
/// seconds) when valid, else [`DEFAULT_RATE_LIMIT_POLL_INTERVAL`].
fn rate_limit_poll_interval() -> Duration {
    crate::daemon::server::duration_secs_from_env(
        ENV_RATE_LIMIT_POLL_INTERVAL,
        DEFAULT_RATE_LIMIT_POLL_INTERVAL,
    )
}

/// A running background menu-refresh task and the token that stops it.
struct RefreshTask {
    /// Cancelled by `shutdown` to end the refresh loop.
    token: CancellationToken,
    /// The spawned loop, awaited on shutdown so it fully unwinds.
    handle: JoinHandle<()>,
}

/// Whether this tick should spend a `gh` call.
///
/// The poller wakes far more often than it fetches — waking is a cached snapshot
/// read, fetching is a subprocess and a network round trip. Two things justify the
/// call: the watch set **grew** (a target was added, or a branch's upstream moved —
/// a push, invisible to the change-notify, so only looking finds it), or the
/// **backoff elapsed** and it is simply time to look again.
///
/// A pure *removal* is deliberately not a reason (#1389): a window closing, a
/// worktree going away, a lease lapsing, or a TTL reap can never change any
/// **surviving** badge, so `grew` is false and the poll skips — see
/// [`pr_watch_grew`]. That kills the close-side of every burn scenario.
///
/// Pure so the policy is testable directly: from outside, the only evidence of it
/// is *when* a subprocess runs, which a test cannot pin down without either flaking
/// or passing for the wrong reason.
fn pr_should_fetch(grew: bool, since_last_fetch: Option<Duration>, backoff: Duration) -> bool {
    // `map_or(true, ..)` rather than `is_none_or`: the latter is stable only
    // since 1.82 and this crate's MSRV is 1.80.
    grew || since_last_fetch.map_or(true, |elapsed| elapsed >= backoff)
}

/// Whether `next` holds a watch the poller has not already resolved for its
/// current upstream — an **addition** (a new (repo, branch) target) or an
/// **upstream that moved** (a push — the #1344 case that starts the CI run a badge
/// reports). Either warrants asking GitHub *now*.
///
/// A pure removal is never "grew": [`PrWatch`] equality is `(target, upstream_sha)`
/// only, so a shrunk `next` that is otherwise a subset of `prev` returns `false`
/// and the poll coalesces (#1389). Head-only moves are excluded by construction —
/// [`PrWatch`] carries no head — because a local commit GitHub has not seen returns
/// exactly the cached verdict, and the badge stays correctly stale through
/// [`PrBadge::is_stale_for`](crate::pr_status::PrBadge::is_stale_for) with no
/// network call (#1389, fix 3).
///
/// Pure so the fetch trigger is testable without driving a live subprocess.
fn pr_watch_grew(prev: &[PrWatch], next: &[PrWatch]) -> bool {
    next.iter().any(|w| !prev.contains(w))
}

/// The next PR-poll delay.
///
/// - **Terminal** (`pending` false): double `current` up to [`MAX_PR_POLL_INTERVAL`]
///   — nothing is expected to change, so this is a slow liveness heartbeat. A failed
///   poll passes `pending: false`, so a persistent failure backs off here rather
///   than being retried hard.
/// - **Pending** (`pending` true): hold `base` (~10 s) for the first
///   [`PENDING_FAST_WINDOW`] after the watch last moved, then escalate — double
///   `current` up to [`PENDING_MAX_INTERVAL`] (#1389, fix 5). A single 20-minute CI
///   run used to pin `base` for its whole duration (360 calls/hour); escalating
///   *within* pending caps that while a verdict arriving a cadence-tick late stays
///   invisible in the tray. `since_moved` is time since fresh work was last seen (a
///   push or an added target), or `None` when nothing has moved yet — treated as
///   past the fast window so a stale-from-boot pending state does not pin `base`.
///
/// A pure function rather than copies inline, because the cadence is only
/// observable from outside as timing, which a test cannot assert without flaking.
fn next_pr_poll_delay(
    current: Duration,
    base: Duration,
    pending: bool,
    since_moved: Option<Duration>,
) -> Duration {
    if !pending {
        return current.saturating_mul(2).min(MAX_PR_POLL_INTERVAL);
    }
    match since_moved {
        // Fresh work: watch it closely at `base` while it is likely to resolve.
        Some(elapsed) if elapsed < PENDING_FAST_WINDOW => base,
        // Still pending well after the move (a long CI run, or a zombie suite):
        // escalate so the cadence stops burning, bounded below the terminal ceiling.
        _ => current.saturating_mul(2).min(PENDING_MAX_INTERVAL),
    }
}

/// Stretches a computed poll delay when the shared GitHub budget is under pressure.
///
/// The daemon is the **single** `gh` choke point for every open window, so this is
/// the one place a machine-wide cap can actually be enforced (#1389, fix 6). When
/// any tracked resource is at/over
/// [`WARN_PERCENT`](crate::github_rate_limit::WARN_PERCENT), the cadence is held at
/// no less than [`BUDGET_THROTTLE_INTERVAL`] so a runaway in this class cannot drain
/// the budget the whole machine shares — structurally, not just by convention. Below
/// the threshold (or with no reading yet) the delay is returned unchanged.
///
/// Pure so the throttle is testable without a live rate-limit poll.
fn budget_throttled_delay(delay: Duration, rate_limit: Option<&RateLimitSnapshot>) -> Duration {
    if rate_limit.is_some_and(RateLimitSnapshot::over_warn) {
        delay.max(BUDGET_THROTTLE_INTERVAL)
    } else {
        delay
    }
}

/// Whether the rate-limit poller should emit a WARN this poll: `true` only when a
/// resource **crosses** the [`WARN_PERCENT`](crate::github_rate_limit::WARN_PERCENT)
/// threshold upward since the previous reading (or is already over on the first
/// poll, when `prev` is `None`). Keying on the rising edge means the log fires once
/// per crossing rather than every poll while usage stays high.
///
/// Pure so the policy is testable without driving a live poll.
fn rate_limit_crossed_warn(prev: Option<&RateLimitSnapshot>, next: &RateLimitSnapshot) -> bool {
    let over = |res: Option<RateLimitResource>| res.is_some_and(|r| r.over_warn());
    // Per-resource so a *different* resource crossing (while another recovers) is
    // still caught — `graphql` dropping below while `core` climbs over would look
    // unchanged to a whole-snapshot `over_warn` comparison.
    [
        (prev.and_then(|p| p.graphql), next.graphql),
        (prev.and_then(|p| p.core), next.core),
        (prev.and_then(|p| p.search), next.search),
    ]
    .into_iter()
    .any(|(before, after)| over(after) && !over(before))
}

/// A running background PR-badge poll task and the token that stops it.
struct PollerTask {
    /// Cancelled by `shutdown` to end the poll loop.
    token: CancellationToken,
    /// The spawned loop, awaited on shutdown so it fully unwinds.
    handle: JoinHandle<()>,
}

/// One thing the PR poller watches: a badge target and the commit its upstream
/// points at.
///
/// The upstream OID is what makes a **push** observable to the poller. A window
/// opening bumps the registry's change-notify, but nothing notifies the daemon
/// when you push — so the poller compares this against the previous tick's and
/// treats an added target or a moved upstream as "go and ask now" (see
/// [`pr_watch_grew`]). A push moves **only** the upstream (#1344), and it is the
/// very thing that starts the CI run a badge reports, so the upstream must be here.
///
/// The local HEAD is deliberately **not** watched (#1389, fix 3): a local commit
/// GitHub has not seen would return exactly the cached verdict, so asking wastes a
/// call, and the badge stays correctly stale through
/// [`PrBadge::is_stale_for`](crate::pr_status::PrBadge::is_stale_for) — a local
/// comparison, no network — until the branch is actually pushed. Equality is thus
/// `(target, upstream_sha)`, which is exactly the key [`pr_watch_grew`] compares.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct PrWatch {
    /// The (repo, branch) to resolve a badge for.
    target: PrTarget,
    /// That branch's upstream tip, or `None` when it tracks no upstream.
    upstream_sha: Option<String>,
}

/// Extracts what the poller watches — the badge targets and their local heads and
/// upstream tips — from a `tree` snapshot.
///
/// Reading them back off the snapshot — rather than walking git again — means the
/// poller reuses the coalescing [`TreeSnapshotCache`] build instead of adding a
/// second independent per-worktree git walk, which is the idle-CPU cost #1305 went
/// out of its way to remove. Only GitHub repos with a branch contribute; the result
/// is sorted and deduped so N worktrees of one repo on one branch ask once.
fn pr_watch_from_snapshot(snapshot: &Value) -> Vec<PrWatch> {
    let mut out = Vec::new();
    for repo in snapshot
        .get("repos")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        // The zero-`gh` guarantee (#1376): a repo the user has not enabled
        // contributes no watch, so the poll's `gh api graphql` never mentions it.
        // The snapshot this reads is already `stamp_polling`-stamped, so this one
        // check is the single filter point — default-off means an absent flag skips.
        if repo.get("polling_enabled").and_then(Value::as_bool) != Some(true) {
            continue;
        }
        let Some(github) = repo.get("github") else {
            continue;
        };
        let (Some(owner), Some(name)) = (
            github.get("owner").and_then(Value::as_str),
            github.get("name").and_then(Value::as_str),
        ) else {
            continue;
        };
        for wt in repo
            .get("worktrees")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            if let Some(branch) = wt.get("branch").and_then(Value::as_str) {
                out.push(PrWatch {
                    upstream_sha: wt
                        .get("upstream_sha")
                        .and_then(Value::as_str)
                        .map(str::to_string),
                    target: PrTarget {
                        owner: owner.to_string(),
                        name: name.to_string(),
                        branch: branch.to_string(),
                    },
                });
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

/// The (repo, branch) pairs to resolve badges for — [`pr_watch_from_snapshot`]
/// without the heads.
#[cfg(test)]
fn pr_targets_from_snapshot(snapshot: &Value) -> Vec<PrTarget> {
    pr_watch_from_snapshot(snapshot)
        .into_iter()
        .map(|w| w.target)
        .collect()
}

/// Hosts the cross-window [`WorktreesRegistry`] as a [`DaemonService`].
pub struct WorktreesService {
    /// The cross-window registry this adapter routes ops to. Behind an `Arc` so
    /// the background menu-refresh task can read it off the main thread.
    registry: Arc<WorktreesRegistry>,
    /// The most recent tray menu snapshot, recomputed off the main thread by
    /// [`start_menu_refresh`](Self::start_menu_refresh). `menu()` serves a clone
    /// of this so it never blocks on git enrichment. `None` until the first
    /// refresh lands — or when no runtime started a task (e.g. unit tests) — in
    /// which case `menu()` falls back to a one-off inline compute.
    menu_cache: Arc<Mutex<Option<Vec<MenuItem>>>>,
    /// The background refresh task, once started (`None` in tests / no runtime).
    refresh: Mutex<Option<RefreshTask>>,
    /// PR badges resolved by the background poller and read by the tree snapshot
    /// build (#1337). Behind an `Arc` so the poll task and the snapshot builder
    /// share the one cache. Empty until the first poll lands — and always empty
    /// when no poller runs (unit tests), in which case the tree simply carries no
    /// `pr` field, exactly as a pre-#1337 daemon did.
    pr_cache: Arc<PrStatusCache>,
    /// The background PR-badge poll task, once started (`None` in tests / no
    /// runtime).
    poller: Mutex<Option<PollerTask>>,
    /// The GitHub API rate-limit snapshot the [`rate-limit poller`] writes and the
    /// tray menu build / built-in `status` op read (#1375). Behind an `Arc` so the
    /// poll task, the tray refresh, and the daemon's registry share the one cache.
    /// Empty until the first poll lands; the daemon hands a clone to the registry
    /// so `status` can report machine-wide GitHub budget usage.
    ///
    /// [`rate-limit poller`]: Self::start_rate_limit_poller
    rate_limit_cache: Arc<RateLimitCache>,
    /// The background rate-limit poll task, once started (`None` in tests / no
    /// runtime).
    rate_limit_poller: Mutex<Option<PollerTask>>,
    /// The shared, coalescing tree-snapshot cache every `subscribe` stream reads
    /// through, so N open windows perform **one** `build_tree` per tick instead
    /// of N (#1303). Behind an `Arc` so each stream holds a cheap handle to the
    /// one cache. The one-shot `tree` op deliberately bypasses it and computes
    /// fresh (it is a rare manual refresh, not part of the per-tick fan-out).
    tree_cache: Arc<TreeSnapshotCache>,
    /// Serializes [`remove_worktree`] across concurrent `close` executes (#1359).
    ///
    /// The extension fans a multi-select delete out into one `close` op per
    /// target, so two executes can reach the prune at once. Their heartbeat waits
    /// overlap freely — that is the point — but the prunes themselves should not:
    /// each op enumerates the repo's worktrees ([`worktree_name_for_path`]) and
    /// then prunes an entry out of that same `.git/worktrees`, so concurrent ops
    /// read a directory a sibling is midway through removing from, and `git2`
    /// promises nothing about that. Precautionary rather than a fix for an
    /// observed corruption — the window is narrow enough that it has not been
    /// reproduced — but serializing costs nothing measurable (the prune is a
    /// directory delete; the wait it follows is seconds) and keeps the fan-out
    /// safe at the source rather than relying on every caller to stay sequential.
    ///
    /// A `tokio` mutex rather than a `std` one: it is held across the
    /// `spawn_blocking` join, which is an `.await`.
    prune_lock: tokio::sync::Mutex<()>,
    /// Where the per-repo PR-poll enable set is persisted (#1376), so a user's
    /// choice survives a daemon restart. `None` disables persistence entirely —
    /// the default from [`new`](Self::new), which keeps the bare service cheap
    /// and I/O-free for unit tests; the daemon wires it via
    /// [`load_polling_prefs`](Self::load_polling_prefs) at startup. Behind a
    /// `std::Mutex` only so `load_polling_prefs` can set it on `&self`; read
    /// briefly and never held across an `.await`.
    polling_prefs_path: Mutex<Option<PathBuf>>,
    /// Where the resolved PR-badge cache is persisted (#1389, fix 4), so badges
    /// survive a daemon restart and the poller can skip its immediate re-poll when
    /// they are still fresh. `None` disables persistence — the default from
    /// [`new`](Self::new), keeping the bare service I/O-free for unit tests; the
    /// daemon wires it via [`load_pr_cache`](Self::load_pr_cache) at startup. Same
    /// `std::Mutex`-only-to-set-on-`&self` role as [`Self::polling_prefs_path`].
    pr_cache_path: Mutex<Option<PathBuf>>,
    /// The warm-start state restored from the persisted cache (#1389, fix 4),
    /// taken by [`start_pr_poller_with`](Self::start_pr_poller_with) when the loop
    /// spawns. `None` on a cold start (no file, or persistence disabled), in which
    /// case the poller does its normal first fetch.
    pr_warm_start: Mutex<Option<PrWarmStart>>,
    /// Shared TTL cache of `gh pr list` results per repo, backing the daemon-served
    /// `open-prs` op (#1389, fix 7) so N windows' "Open Pull Request…" lookups
    /// dedupe to one counted `gh` per repo instead of one per window. Behind an
    /// `Arc` for parity with the other caches.
    open_pr_cache: Arc<OpenPrCache>,
}

impl WorktreesService {
    /// Creates the service with an empty registry. Cheap — no I/O and no task;
    /// the daemon calls [`start_menu_refresh`](Self::start_menu_refresh) to begin
    /// off-thread menu caching, while tests use the bare service (menu computed
    /// inline on demand).
    #[must_use]
    pub fn new() -> Self {
        let registry = Arc::new(WorktreesRegistry::new());
        let pr_cache = Arc::new(PrStatusCache::new());
        Self {
            registry: registry.clone(),
            menu_cache: Arc::new(Mutex::new(None)),
            refresh: Mutex::new(None),
            pr_cache: pr_cache.clone(),
            poller: Mutex::new(None),
            rate_limit_cache: Arc::new(RateLimitCache::new()),
            rate_limit_poller: Mutex::new(None),
            tree_cache: Arc::new(TreeSnapshotCache::new(registry, pr_cache)),
            prune_lock: tokio::sync::Mutex::new(()),
            polling_prefs_path: Mutex::new(None),
            pr_cache_path: Mutex::new(None),
            pr_warm_start: Mutex::new(None),
            open_pr_cache: Arc::new(OpenPrCache::new(open_pr_ttl())),
        }
    }

    /// Seeds the per-repo PR-poll enable set from the persisted `0600` prefs file
    /// and remembers `path` so later [`set-polling`](Self::handle) changes persist
    /// back to it (#1376). Called once by the daemon at startup, before any window
    /// subscribes — so [`seed_polling`](WorktreesRegistry::seed_polling) needs no
    /// bump. Best-effort throughout: a missing file is the first-run default (no
    /// repos enabled), and a corrupt/unreadable one is logged and treated as
    /// empty rather than wedging the service — the user simply re-enables. The
    /// path is stored regardless, so the next change rewrites a clean file.
    pub fn load_polling_prefs(&self, path: PathBuf) {
        match std::fs::read(&path) {
            Ok(bytes) => match serde_json::from_slice::<PollingPrefs>(&bytes) {
                Ok(prefs) => self
                    .registry
                    .seed_polling(prefs.enabled.into_iter().map(|l| (l.repo, l.expires_at))),
                Err(err) => tracing::warn!(
                    "ignoring unreadable worktrees polling prefs at {}: {err:#}",
                    path.display()
                ),
            },
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => tracing::warn!(
                "could not read worktrees polling prefs at {}: {err:#}",
                path.display()
            ),
        }
        *self
            .polling_prefs_path
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = Some(path);
    }

    /// Writes the current enable set to the `0600` prefs file, if persistence is
    /// configured ([`load_polling_prefs`](Self::load_polling_prefs) set a path).
    /// Best-effort: a write failure is logged at WARN and swallowed, since the
    /// in-memory set is authoritative for the running daemon — the user's toggle
    /// still took effect, it just would not survive a restart. A no-op (returns
    /// early) in unit tests, which never configure a path.
    fn persist_polling_prefs(&self) {
        let Some(path) = self
            .polling_prefs_path
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
        else {
            return;
        };
        let prefs = PollingPrefs {
            enabled: self
                .registry
                .polling_snapshot()
                .into_iter()
                .map(|(repo, expires_at)| PollingLease { repo, expires_at })
                .collect(),
        };
        if let Err(err) = write_polling_prefs(&path, &prefs) {
            tracing::warn!(
                "could not persist worktrees polling prefs to {}: {err:#}",
                path.display()
            );
        }
    }

    /// Seeds the resolved PR-badge cache from the persisted `0600` file and
    /// remembers `path` so each poll persists back to it (#1389, fix 4). Called
    /// once by the daemon at startup, before any window subscribes and before the
    /// poller spawns, so restored badges render on the first tree snapshot and the
    /// poller can skip its immediate re-poll for verdicts still fresh.
    ///
    /// Best-effort throughout (the [`load_polling_prefs`](Self::load_polling_prefs)
    /// contract): a missing file is the cold-start default, and a corrupt/unreadable
    /// one is logged and treated as empty — the poller simply re-resolves. The path
    /// is stored regardless, so the next poll rewrites a clean file. Restores both
    /// the badges (into [`pr_cache`](Self::pr_cache)) and the
    /// [`PrWarmStart`](PrWarmStart) the poller reads at spawn.
    pub fn load_pr_cache(&self, path: PathBuf) {
        match std::fs::read(&path) {
            Ok(bytes) => match serde_json::from_slice::<PrCachePrefs>(&bytes) {
                Ok(prefs) => {
                    self.pr_cache.seed(
                        prefs
                            .entries
                            .into_iter()
                            .map(|e| (e.target, e.resolution.into_resolution())),
                    );
                    // A warm start needs both a watch set to compare against and a
                    // poll time to age it; without `polled_at` the file is too old a
                    // shape to trust, so treat it as a cold start (badges still
                    // render, the poller just re-polls immediately).
                    if let Some(polled_at) = prefs.polled_at {
                        let watched = prefs
                            .watched
                            .into_iter()
                            .map(|w| PrWatch {
                                target: w.target,
                                upstream_sha: w.upstream_sha,
                            })
                            .collect();
                        *self
                            .pr_warm_start
                            .lock()
                            .unwrap_or_else(PoisonError::into_inner) =
                            Some(PrWarmStart { watched, polled_at });
                    }
                }
                // Bind the path so it is formatted whenever the branch runs — not
                // only when a WARN subscriber is installed — so coverage sees it
                // (the `let summary = …` pattern the rate-limit warn uses).
                Err(err) => {
                    let at = path.display();
                    tracing::warn!("ignoring unreadable worktrees PR cache at {at}: {err:#}");
                }
            },
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => {
                let at = path.display();
                tracing::warn!("could not read worktrees PR cache at {at}: {err:#}");
            }
        }
        *self
            .pr_cache_path
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = Some(path);
    }

    /// Resolves a repo's open pull requests for the `open-prs` op (#1389, fix 7),
    /// served from the shared TTL cache when fresh, else **one** counted `gh pr
    /// list`. The `gh` runs on a blocking thread (never an async worker), routed
    /// through the #1387-counted [`run_gh`](crate::github_metrics::run_gh) choke
    /// point so the call is still counted exactly once — the constraint the whole
    /// of #1389 preserves. The result is forwarded to the extension verbatim.
    async fn open_prs(&self, owner: &str, name: &str) -> Result<Vec<Value>> {
        // The `gh` binary is resolved once here (the env read is process-stable),
        // then handed to the seam below — the poller's "bin as a param" pattern, so
        // a test injects a stub without mutating the process environment (#1030).
        self.open_prs_with(owner, name, crate::pr_status::resolve_gh_binary())
            .await
    }

    /// [`open_prs`](Self::open_prs) with an explicit `gh` binary, so a test drives
    /// the cache against a stub without touching the environment.
    async fn open_prs_with(&self, owner: &str, name: &str, bin: PathBuf) -> Result<Vec<Value>> {
        let key = format!("{owner}/{name}");
        if let Some(prs) = self.open_pr_cache.fresh(&key) {
            return Ok(prs);
        }
        let slug = key.clone();
        let prs = tokio::task::spawn_blocking(move || open_pr_list(&bin, &slug))
            .await
            .unwrap_or_else(|err| Err(anyhow!("blocking open-prs task failed: {err}")))?;
        self.open_pr_cache.store(key, prs.clone());
        Ok(prs)
    }

    /// A handle to the GitHub rate-limit snapshot cache (#1375), so the daemon can
    /// share it with the [`ServiceRegistry`](crate::daemon::registry::ServiceRegistry)
    /// for the built-in `status` op to read.
    #[must_use]
    pub fn rate_limit_cache(&self) -> Arc<RateLimitCache> {
        self.rate_limit_cache.clone()
    }

    /// Starts the background task that recomputes the tray menu snapshot every
    /// [`menu_refresh_interval`] **off the main thread** — git enrichment is
    /// blocking disk I/O — and stores it in [`menu_cache`](Self::menu_cache), so
    /// the macOS tray's `menu()` serves a cache instead of running git on the GUI
    /// event loop. Idempotent, and a no-op outside a tokio runtime (mirroring the
    /// Snowflake keep-alive heartbeat), so unit tests that build a bare service
    /// keep computing the menu inline.
    pub fn start_menu_refresh(&self) {
        if tokio::runtime::Handle::try_current().is_err() {
            tracing::debug!("no tokio runtime; worktrees menu refresh not started");
            return;
        }
        let mut guard = self.refresh.lock().unwrap_or_else(PoisonError::into_inner);
        if guard.is_some() {
            return;
        }
        let token = CancellationToken::new();
        let loop_token = token.clone();
        let registry = self.registry.clone();
        let cache = self.menu_cache.clone();
        let rate_limit_cache = self.rate_limit_cache.clone();
        // Resolved once at spawn: the interval is process-stable env config, and
        // re-reading it every loop would be wasted work.
        let interval = menu_refresh_interval();
        let handle = tokio::spawn(async move {
            loop {
                // Snapshot the registry (a cheap lock), then build the menu —
                // which opens repos and parses git config — on a blocking thread,
                // never on this async worker or the tray's main thread.
                let entries = registry.list();
                // The rate-limit reading (a cheap lock, `Copy`) prepends a status
                // line; read it here and hand it to the blocking build (#1375).
                let rate_limit = rate_limit_cache.get();
                if let Ok(items) = tokio::task::spawn_blocking(move || {
                    menu_items_for(&entries, rate_limit.as_ref())
                })
                .await
                {
                    *cache.lock().unwrap_or_else(PoisonError::into_inner) = Some(items);
                }
                tokio::select! {
                    () = loop_token.cancelled() => break,
                    () = tokio::time::sleep(interval) => {}
                }
            }
        });
        *guard = Some(RefreshTask { token, handle });
    }

    /// Starts the background task that keeps PR check badges fresh (#1337).
    ///
    /// This is the half of the badge nothing else can do. Badges used to be
    /// resolved extension-side on repo-expand, so they were recomputed only when a
    /// repo node's children were rebuilt — and the streamed snapshot carries
    /// worktree topology, not CI. While CI ran and no window opened or closed,
    /// nothing re-asked GitHub and a badge stayed wrong indefinitely.
    ///
    /// The loop resolves **every** (repo, branch) pair in one `gh api graphql` call
    /// (cost 1, independent of repo/worktree/window count), writes the cache the
    /// tree snapshot reads, and bumps the registry's change-notify **only when a
    /// verdict actually moved** — so the server's diff pushes to every open window
    /// exactly when CI state changes, and never otherwise.
    ///
    /// Cadence adapts: [`pr_poll_interval`] (~10 s) while a badge is pending and
    /// fresh, escalating to [`PENDING_MAX_INTERVAL`] once a pending phase runs long
    /// (#1389, fix 5) and doubling to [`MAX_PR_POLL_INTERVAL`] once everything is
    /// terminal; it polls nothing at all while no window is registered.
    ///
    /// It spends a `gh` call only when the watch set **grows** — a target added or
    /// an upstream pushed (#1389, fixes 1/3) — or the backoff elapses; a pure
    /// removal (window close, VS Code/daemon shutdown, TTL reap, lease lapse) never
    /// fetches. A change-notify storm is debounced ([`pr_debounce_interval`],
    /// #1389 fix 2) into one fetch, restored badges survive a restart (#1389 fix
    /// 4), and the cadence is capped when the shared GitHub budget is strained
    /// (#1389 fix 6).
    ///
    /// Idempotent, and a no-op outside a tokio runtime (mirroring
    /// [`start_menu_refresh`](Self::start_menu_refresh) and the Snowflake keep-alive
    /// heartbeat), so unit tests build a bare service that never spawns `gh`.
    pub fn start_pr_poller(&self) {
        // Resolved once at spawn: process-stable env config (the menu-refresh
        // precedent), never re-read per poll.
        self.start_pr_poller_with(
            pr_poll_interval(),
            pr_debounce_interval(),
            crate::pr_status::resolve_gh_binary(),
        );
    }

    /// [`start_pr_poller`](Self::start_pr_poller) with an explicit cadence,
    /// debounce settle window, and `gh` binary, so tests drive the loop at
    /// millisecond speed against a stub **without mutating the process
    /// environment** — one global env var cannot serve two parallel tests pointing
    /// at different fakes. Mirrors the [`TreeSnapshotCache::with_ttl`] seam and the
    /// Snowflake heartbeat's "interval via config, not env" rule.
    ///
    /// Reads the rate-limit cache, the persistence path, and the warm-start state
    /// off `self` at spawn (all `#1389` inputs), so its signature stays close to
    /// the original two-cadence seam.
    fn start_pr_poller_with(&self, base: Duration, debounce: Duration, gh_bin: PathBuf) {
        if tokio::runtime::Handle::try_current().is_err() {
            tracing::debug!("no tokio runtime; worktrees PR poller not started");
            return;
        }
        let mut guard = self.poller.lock().unwrap_or_else(PoisonError::into_inner);
        if guard.is_some() {
            return;
        }
        let token = CancellationToken::new();
        let loop_token = token.clone();
        let registry = self.registry.clone();
        let tree_cache = self.tree_cache.clone();
        let pr_cache = self.pr_cache.clone();
        // The shared budget reading (#1389, fix 6) and the `0600` persistence path +
        // restored warm start (#1389, fix 4). The warm start is *taken* — it seeds
        // the loop once and must not be reused by a later restart of the poller.
        let rate_limit_cache = self.rate_limit_cache.clone();
        let pr_cache_path = self
            .pr_cache_path
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        let warm_start = self
            .pr_warm_start
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        // Captured here, before the task's first sleep, so a window that registers
        // while the loop is starting still wakes it rather than being missed.
        let mut changes = self.registry.subscribe_changes();
        let handle = tokio::spawn(async move {
            // Two independent cadences. The loop *wakes* every `base` — cheap: a read
            // of the coalescing snapshot cache, no subprocess, no network. It only
            // *asks GitHub* when there is reason to: the watch set grew (a target
            // added, or an upstream pushed), or the backoff has elapsed.
            //
            // They have to be separate because the two things that should trigger a
            // fetch arrive by different routes. A window opening bumps the registry's
            // change-notify, but **a push does not** — nothing in the daemon is
            // notified when you `git push`. The only way to notice is to look, so the
            // loop looks often and cheaply, and pays only when something grew.
            let mut backoff = base;
            // Warm start (#1389, fix 4): resume what the previous daemon last
            // resolved and when, so a restart within the backoff window skips the
            // immediate re-poll for verdicts already restored into `pr_cache`.
            // `last_poll` is reconstructed as an `Instant` that many seconds ago; a
            // reboot (monotonic epoch reset) or a future timestamp collapses to
            // "never polled", which just re-polls — the safe direction.
            let (mut watched, mut last_poll): (Option<Vec<PrWatch>>, Option<Instant>) =
                match warm_start {
                    Some(ws) => {
                        let elapsed = (Utc::now() - ws.polled_at)
                            .to_std()
                            .unwrap_or(Duration::ZERO);
                        (Some(ws.watched), Instant::now().checked_sub(elapsed))
                    }
                    None => (None, None),
                };
            // When fresh work (a push or an added target) was last seen, so the
            // pending cadence can escalate once it goes quiet (#1389, fix 5).
            let mut moved_at: Option<Instant> = None;
            'poll: loop {
                // Wait first: at startup no window has registered yet, and the
                // first snapshot would be empty anyway.
                tokio::select! {
                    () = loop_token.cancelled() => break,
                    () = tokio::time::sleep(base) => {}
                    // A window opened or closed — look now rather than at the next
                    // tick, but debounce first.
                    result = changes.changed() => {
                        // Unreachable today: this task owns an `Arc` of the registry
                        // that holds the sender, so it cannot be dropped while we are
                        // here. Kept anyway because the alternative is worse — a
                        // closed channel makes `changed()` return `Ready` forever, so
                        // ignoring the error would spin this loop at full speed,
                        // re-snapshotting and re-running `gh` every iteration.
                        if result.is_err() {
                            break;
                        }
                        // Debounce (#1389, fix 2): a VS Code restart unregisters then
                        // re-registers its windows one-by-one over several seconds,
                        // each bump waking us; a daemon restart re-registers the same
                        // way. Wait for `debounce` of quiet before snapshotting so the
                        // whole storm collapses to **one** fetch on the final watch
                        // set. Bounded by an overall deadline so a steady drip of
                        // changes cannot postpone the poll forever.
                        let overall_deadline = Instant::now() + debounce.saturating_mul(4);
                        loop {
                            tokio::select! {
                                () = loop_token.cancelled() => break 'poll,
                                () = tokio::time::sleep(debounce) => break,
                                r = changes.changed() => {
                                    if r.is_err() {
                                        break 'poll;
                                    }
                                    if Instant::now() >= overall_deadline {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                // Off the coalescing snapshot cache, so this reuses the tick's
                // `build_tree` rather than walking git a second time.
                let snapshot = tree_cache.snapshot().await;
                let watch = pr_watch_from_snapshot(&snapshot);
                if watch.is_empty() {
                    // No windows, or nothing on GitHub: ask nothing, and forget any
                    // backoff so the next tree starts fresh. But **keep** `watched`
                    // (#1389, fix 4): a VS Code restart momentarily empties the watch
                    // mid-storm, and nulling it here would make the re-registered set
                    // look brand-new and re-fetch. A genuinely gone tree simply has
                    // nothing to compare against on the next non-empty tick.
                    backoff = base;
                    last_poll = None;
                    moved_at = None;
                    continue;
                }
                // Did the watched set **grow** (an addition, or an upstream pushed)?
                // A pure removal is not a reason to fetch (#1389, fix 1); a local
                // commit is not either (#1389, fix 3, `PrWatch` carries no head).
                let grew = pr_watch_grew(watched.as_deref().unwrap_or(&[]), &watch);
                // Prune verdicts for targets that vanished, so a closed worktree's
                // badge does not linger in the cache (#1389, fix 1) — local, no
                // network, and correct whether or not this tick goes on to fetch.
                let keep: HashSet<PrTarget> = watch.iter().map(|w| w.target.clone()).collect();
                pr_cache.retain_targets(&keep);
                // Budget-aware cap (#1389, fix 6): the daemon is the single `gh`
                // choke point, so throttling here is the one place a machine-wide cap
                // works. Over WARN_PERCENT, hold the stretched cadence *and* ignore an
                // immediate `grew`, so no runaway in this class can drain the shared
                // budget — structurally, not by convention.
                let rate_limit = rate_limit_cache.get();
                let over_budget = rate_limit.is_some_and(|s| s.over_warn());
                let effective_backoff = budget_throttled_delay(backoff, rate_limit.as_ref());
                let trigger = grew && !over_budget;
                if !pr_should_fetch(trigger, last_poll.map(|at| at.elapsed()), effective_backoff) {
                    // Not fetching this tick. Advance `watched` only for a pure shrink
                    // or a quiet identical tick — an addition/push (`grew`) must stay
                    // unresolved so it is still fetched once the cadence or budget
                    // allows, rather than being silently consumed here.
                    if !grew {
                        watched = Some(watch);
                    }
                    continue;
                }
                if grew {
                    // Fresh work: watch it closely and restart the escalation clock
                    // rather than serving out a backoff earned while it was quiet.
                    backoff = base;
                    moved_at = Some(Instant::now());
                }
                let targets: Vec<PrTarget> = watch.iter().map(|w| w.target.clone()).collect();
                // `gh` is a blocking subprocess: never on an async worker. A join
                // failure (the task panicked, or the runtime is going down) folds
                // into the same error channel as a `gh` failure — both mean "no
                // badges this round", and neither deserves its own handling.
                let bin = gh_bin.clone();
                let resolved = tokio::task::spawn_blocking(move || {
                    crate::pr_status::resolve_with_budget(&bin, &targets)
                })
                .await
                .unwrap_or_else(|err| Err(anyhow!("blocking poll task failed: {err}")));
                // Best-effort decoration: a missing/unauthenticated `gh`, a network
                // blip, or a rate limit must never sink the tree. A failed poll
                // leaves the last good resolutions in place — badges *and* explicit
                // negatives, and it mints no new negatives (#1370) — rather than
                // blanking every row, and is not "pending", so it backs off rather
                // than hammers.
                let (pending, resolved_ok) = match resolved {
                    Ok((resolutions, budget)) => {
                        // Fold the free budget reading this poll carried into the
                        // shared cache (#1389, fix 8): the graphql figure stays fresh
                        // whenever polling is active, which lets the standalone
                        // `/rate_limit` poller idle (fix 8b), and the poll's `cost`
                        // reveals the real per-call point price.
                        if let Some(b) = budget {
                            tracing::debug!(
                                "PR poll cost {} point(s); graphql {}/{} used, {} remaining",
                                b.cost,
                                b.used,
                                b.limit,
                                b.remaining
                            );
                            rate_limit_cache.observe_graphql(RateLimitResource::new(
                                b.used,
                                b.limit,
                                b.remaining,
                                b.reset,
                            ));
                        }
                        // Bump only on a real change, or the server's diff-and-drop
                        // is defeated and every window re-renders on every poll.
                        if pr_cache.replace(resolutions) {
                            registry.bump();
                        }
                        (pr_cache.any_pending(), true)
                    }
                    Err(err) => {
                        tracing::debug!("PR badge poll failed: {err:#}");
                        (false, false)
                    }
                };
                last_poll = Some(Instant::now());
                // Record what this verdict was about, so the *next* tick can tell a
                // genuine change from a quiet tree.
                watched = Some(watch);
                let since_moved = moved_at.map(|at| at.elapsed());
                backoff = next_pr_poll_delay(backoff, base, pending, since_moved);
                // Persist the fresh verdicts (#1389, fix 4) so the next restart
                // serves them and can skip its immediate re-poll. Only on a real
                // resolution — a failed poll must not advance the persisted poll time
                // past the last *good* one. Best-effort; a write failure costs at
                // most one extra poll after the next restart.
                if resolved_ok {
                    if let Some(path) = &pr_cache_path {
                        persist_pr_cache(
                            path,
                            &pr_cache,
                            watched.as_deref().unwrap_or(&[]),
                            Utc::now(),
                        );
                    }
                }
            }
        });
        *guard = Some(PollerTask { token, handle });
    }

    /// Starts the background task that keeps the GitHub API rate-limit reading
    /// fresh (#1375).
    ///
    /// The daemon's PR-badge poller shells out to `gh`, spending the same GitHub
    /// budget as every other tool sharing the user's token; when that drains, `gh`
    /// rate-limits machine-wide with no warning until commands start failing. This
    /// loop polls `gh api rate_limit` — an endpoint GitHub documents (and this
    /// project verified) as **exempt**, spending nothing against any budget — so
    /// `daemon status`, the JSON payload, and the tray can show the used-percentage
    /// *trend* and warn before exhaustion, at zero cost to the budget watched.
    ///
    /// A plain fixed cadence ([`rate_limit_poll_interval`], ~60 s): no adaptive
    /// backoff and no window-gating, because the endpoint is free and a current
    /// reading is wanted whenever an operator checks `status`. Idempotent, and a
    /// no-op outside a tokio runtime (mirroring [`start_pr_poller`](Self::start_pr_poller)
    /// and [`start_menu_refresh`](Self::start_menu_refresh)), so unit tests build a
    /// bare service that never spawns `gh`.
    pub fn start_rate_limit_poller(&self) {
        // Both resolved once at spawn: process-stable env config, never re-read per
        // poll (the PR-poller precedent).
        self.start_rate_limit_poller_with(
            rate_limit_poll_interval(),
            crate::pr_status::resolve_gh_binary(),
        );
    }

    /// [`start_rate_limit_poller`](Self::start_rate_limit_poller) with an explicit
    /// cadence and `gh` binary, so tests drive the loop at millisecond speed
    /// against a stub **without mutating the process environment** (the
    /// [`start_pr_poller_with`](Self::start_pr_poller_with) seam).
    fn start_rate_limit_poller_with(&self, interval: Duration, gh_bin: PathBuf) {
        if tokio::runtime::Handle::try_current().is_err() {
            tracing::debug!("no tokio runtime; worktrees rate-limit poller not started");
            return;
        }
        let mut guard = self
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if guard.is_some() {
            return;
        }
        let token = CancellationToken::new();
        let loop_token = token.clone();
        let cache = self.rate_limit_cache.clone();
        let registry = self.registry.clone();
        let handle = tokio::spawn(async move {
            // Remembers the previous reading so a WARN fires only on the *rising*
            // edge across the threshold, not every poll while usage stays high.
            let mut prev: Option<RateLimitSnapshot> = None;
            loop {
                // Gate the poll on activity (#1389, fix 8b): a fully-idle daemon —
                // no window registered and no polling lease active — has nothing to
                // watch, so it spends no `/rate_limit` subprocess and lets the last
                // reading stand. The read is free against the budget, but the
                // wakeups are not; and while polling *is* active the graphql figure
                // stays fresh from every PR poll's folded-in budget (fix 8a), so the
                // standalone poll is only topping up `core`/`search`.
                if !registry.list().is_empty() || !registry.polling_snapshot().is_empty() {
                    // Poll first, so `status` has a reading soon after a window
                    // appears rather than one interval later. `gh` is a blocking
                    // subprocess: never on an async worker. A join failure folds into
                    // the same channel as a `gh` failure — both mean "no fresh
                    // reading this round".
                    let bin = gh_bin.clone();
                    let resolved =
                        tokio::task::spawn_blocking(move || resolve_rate_limit_with(&bin))
                            .await
                            .unwrap_or_else(|err| {
                                Err(anyhow!("blocking rate-limit poll task failed: {err}"))
                            });
                    match resolved {
                        Ok(snap) => {
                            if rate_limit_crossed_warn(prev.as_ref(), &snap) {
                                // Bound to a local (rather than inlined into the
                                // macro) so it is computed whenever the branch is
                                // taken, not only when a WARN-level subscriber is
                                // installed — `tracing` skips evaluating macro args
                                // otherwise.
                                let summary = snap.summary_line();
                                tracing::warn!(
                                    "GitHub API rate limit high: {summary} (querying \
                                     /rate_limit is free; the daemon's gh usage is not)"
                                );
                            }
                            // Update the cache only; deliberately no `registry.bump()`
                            // — the rate limit is not tree topology, and bumping would
                            // re-push an unchanged tree to every window. The tray
                            // re-polls `menu()` at ~1 Hz and `status` reads on demand.
                            cache.replace(snap);
                            prev = Some(snap);
                        }
                        // Best-effort decoration: a missing/unauthenticated `gh` or a
                        // network blip leaves the last good reading in place rather
                        // than blanking the line, and never affects the budget (the
                        // read is free).
                        Err(err) => tracing::debug!("GitHub rate-limit poll failed: {err:#}"),
                    }
                }
                tokio::select! {
                    () = loop_token.cancelled() => break,
                    () = tokio::time::sleep(interval) => {}
                }
            }
        });
        *guard = Some(PollerTask { token, handle });
    }

    /// Handles the `close` op: close a worktree's window and, for a **linked**
    /// worktree, delete it. The flow has two phases keyed off `confirmed`:
    ///
    /// - **Phase 1** (`remove:true`, `confirmed:false`) — a pure, side-effect-free
    ///   [`git_safety`] check returning the risks of deleting, so the extension can
    ///   show a modal confirm only when something would actually be lost.
    /// - **Phase 2** (`confirmed:true`, or any `remove:false`) — execute: signal
    ///   the owning window(s) to close, then (for `remove:true`) `git2`-prune the
    ///   worktree. The main working tree is refused defensively.
    ///
    /// Cross-window signalling (another window has the target open) is a
    /// fast-follow: this core handles the **no-window** and **self-close**
    /// (`requester_key == target_key`) cases, and errors clearly when another
    /// window owns the target so the destructive path is never taken blind.
    async fn close(&self, req: CloseRequest) -> Result<Value> {
        // Which live windows currently have the target open. The canonical-path
        // compare is disk I/O, so run it (with the safety check below) on a
        // blocking thread, never under the registry lock or on the async worker.
        let entries = self.registry.list();
        let scan_path = req.path.clone();
        let open_windows =
            tokio::task::spawn_blocking(move || windows_with_path(&entries, &scan_path))
                .await
                .unwrap_or_default();
        let open = !open_windows.is_empty();
        let window_key = open_windows.first().map(|(k, _)| k.clone());
        let window_folder_count = open_windows.first().map_or(0, |(_, c)| *c);

        // Phase 1: the safety check runs only for a delete request awaiting
        // confirmation. A "Close Window" (remove:false) never inspects git and
        // has nothing to confirm, so it skips straight to execute.
        if req.remove && !req.confirmed {
            let path = req.path.clone();
            let git = tokio::task::spawn_blocking(move || git_safety(&path))
                .await
                .map_err(|e| anyhow!("safety check task panicked: {e}"))??;
            return Ok(serde_json::to_value(SafetyReport {
                removable: git.removable,
                is_main: git.is_main,
                open,
                window_key,
                window_folder_count,
                risks: git.risks,
                info: git.info,
            })
            .unwrap_or_else(|_| json!({})));
        }

        // Phase 2: execute. Signal every owning window *other than the
        // requester* (which closes itself on our `ok:true` reply, avoiding the
        // ext-host-dies-mid-op race) and wait for each to unregister before
        // touching the worktree. The directive reaches a cross-window target via
        // its heartbeat reply — the only channel the daemon has to a window it
        // can reply to but never call.
        let others: Vec<String> = open_windows
            .iter()
            .map(|(k, _)| k.clone())
            .filter(|k| req.requester_key.as_deref() != Some(k))
            .collect();
        for key in &others {
            self.registry.mark_close_pending(key);
        }
        if !others.is_empty() {
            await_windows_closed(
                &self.registry,
                &req.path,
                req.requester_key.as_deref(),
                CLOSE_WAIT_TIMEOUT,
                CLOSE_WAIT_POLL,
            )
            .await?;
        }

        if req.remove {
            let path = req.path.clone();
            // Taken *after* the wait above, so concurrent executes still overlap
            // their heartbeat waits (#1359) and only the prune itself serializes.
            // Load-bearing placement, not incidental: hoisting this above
            // `await_windows_closed` would restack the waits and undo the whole
            // point. Pinned by `concurrent_closes_overlap_their_heartbeat_waits`.
            let _guard = self.prune_lock.lock().await;
            tokio::task::spawn_blocking(move || remove_worktree(&path))
                .await
                .map_err(|e| anyhow!("worktree removal task panicked: {e}"))??;
            Ok(json!({ "removed": true }))
        } else {
            // "Close Window" with no owning window is a no-op success; a
            // self-close replies and the extension closes its own window.
            Ok(json!({ "closed": true }))
        }
    }
}

impl Default for WorktreesService {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DaemonService for WorktreesService {
    fn name(&self) -> &'static str {
        SERVICE_NAME
    }

    async fn handle(&self, op: &str, payload: Value) -> Result<Value> {
        match op {
            "register" => {
                let req: RegisterRequest =
                    serde_json::from_value(payload).context("invalid `register` payload")?;
                if req.key.trim().is_empty() {
                    bail!("`register` requires a non-empty `key`");
                }
                self.registry.register(req);
                Ok(json!({ "ok": true }))
            }
            "heartbeat" => {
                let key = require_str(&payload, "key", "heartbeat")?;
                let known = self.registry.heartbeat(key);
                // A pending close directive (#1277) rides the reply as an
                // additive `close` field, taken-and-cleared here so it fires
                // exactly once. Omitted when false to keep older windows — which
                // read only `known` — byte-identical on the wire.
                let mut reply = json!({ "known": known });
                if self.registry.take_close_pending(key) {
                    reply["close"] = Value::Bool(true);
                }
                Ok(reply)
            }
            "unregister" => {
                let key = require_str(&payload, "key", "unregister")?;
                Ok(json!({ "removed": self.registry.unregister(key) }))
            }
            "list" => Ok(json!({ "windows": enriched_windows(self.registry.list()).await })),
            "tree" => {
                // The same `{ repos, show_closed }` snapshot the `subscribe`
                // stream pushes, so a one-shot `tree` fetch and the live stream
                // agree byte-for-byte (the git enumeration runs off-lock on a
                // blocking thread inside the helper). Computed fresh here — the
                // `tree` op is a rare manual refresh, deliberately bypassing the
                // stream's coalescing cache so it never returns a stale view
                // (#1303).
                Ok(tree_snapshot(&self.registry, self.pr_cache.clone()).await)
            }
            "ahead-behind" => {
                // Lazy per-worktree divergence (#1306). The `tree`/`subscribe`
                // snapshot no longer carries ahead/behind — the dominant
                // per-worktree cost when computed eagerly every tick — so a client
                // (the extension on expand, `worktrees tree`) asks for it here only
                // for the worktrees it is about to show. Batched by path, one op per
                // repo expand; the git walks run on a blocking thread.
                let paths = payload
                    .get("paths")
                    .and_then(Value::as_array)
                    .map(|arr| {
                        arr.iter()
                            .filter_map(Value::as_str)
                            .map(PathBuf::from)
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default();
                Ok(json!({ "results": ahead_behind_results(paths).await }))
            }
            "set-show-closed" => {
                // The daemon-backed show/hide-closed toggle (#1301). Setting it
                // bumps the change-notify, so every subscribed window re-pushes a
                // snapshot carrying the new `show_closed` — reliable cross-window
                // sync `context.globalState` could not do.
                let show_closed = payload
                    .get("show_closed")
                    .and_then(Value::as_bool)
                    .ok_or_else(|| anyhow!("`set-show-closed` requires a boolean `show_closed`"))?;
                self.registry.set_show_closed(show_closed);
                Ok(json!({ "ok": true }))
            }
            "set-polling" => {
                // Per-repo PR-poll toggle (#1376). Enabling a repo starts the
                // poller resolving its badges (default is off — zero `gh`);
                // disabling stops it and drops its badges. `set_polling` bumps the
                // change-notify on a real change, so every subscribed window
                // re-pushes a `tree` snapshot carrying the new per-repo
                // `polling_enabled` — the reliable cross-window sync the
                // `set-show-closed` precedent relies on. A changed value is
                // persisted so it survives a daemon restart.
                let owner = require_str(&payload, "owner", "set-polling")?;
                let name = require_str(&payload, "name", "set-polling")?;
                let enabled = payload
                    .get("enabled")
                    .and_then(Value::as_bool)
                    .ok_or_else(|| anyhow!("`set-polling` requires a boolean `enabled`"))?;
                if owner.trim().is_empty() || name.trim().is_empty() {
                    bail!("`set-polling` requires a non-empty `owner` and `name`");
                }
                if self.registry.set_polling(owner, name, enabled) {
                    self.persist_polling_prefs();
                }
                Ok(json!({ "ok": true }))
            }
            "open-prs" => {
                // Serve "Open Pull Request…" (and the extension's transient badge
                // fallback) from the daemon (#1389, fix 7): one shared, TTL-cached,
                // #1387-counted `gh pr list` per repo, so N windows dedupe to one
                // call instead of each shelling its own (the per-window burn
                // #1370/#1389 target). Repo-wide; the client filters by branch for a
                // worktree-scoped lookup, and answers a badged branch straight from
                // the snapshot (zero `gh`) without ever reaching here.
                let owner = require_str(&payload, "owner", "open-prs")?;
                let name = require_str(&payload, "name", "open-prs")?;
                if owner.trim().is_empty() || name.trim().is_empty() {
                    bail!("`open-prs` requires a non-empty `owner` and `name`");
                }
                Ok(json!({ "pull_requests": self.open_prs(owner, name).await? }))
            }
            "open" => {
                // Focus (or open — VS Code reuses an already-open window) an
                // arbitrary worktree folder supplied by a socket client, reusing
                // the tray's launcher path: `focus_window` resolves the launcher
                // (`OMNI_DEV_VSCODE_BIN` → well-known paths → `code`) and applies
                // the absolute-existing-directory guard (which also blocks a
                // `-`-leading path being parsed by `code` as a flag). This is the
                // one op a socket *writer* can use to spawn `code`; see the
                // ADR-0040 threat model (#1266).
                let path = require_str(&payload, "path", "open")?;
                focus_window(Path::new(path))?;
                Ok(json!({ "ok": true }))
            }
            "close" => {
                // Close a worktree's window and (for a linked worktree)
                // **delete** it. Destructive, so all git logic stays in the
                // daemon (git2, never a shell) and the main working tree is
                // refused defensively — the UI gating is not the only guard.
                // See ADR-0049 and docs/worktrees-service.md.
                let req: CloseRequest =
                    serde_json::from_value(payload).context("invalid `close` payload")?;
                self.close(req).await
            }
            other => bail!("unknown worktrees op: {other}"),
        }
    }

    fn subscribe(&self, op: &str, _payload: &Value) -> Option<Box<dyn ServiceStream>> {
        // The single streaming op: a live push of the repo/worktree `tree`
        // snapshot. Every other op falls through to the request→reply `handle`.
        if op != "subscribe" {
            return None;
        }
        Some(Box::new(WorktreesStream {
            // Every stream reads through the one shared cache, so N windows
            // sampling the same tick build the tree once, not N times (#1303).
            cache: self.tree_cache.clone(),
            // Capture the change source *now* — before the server takes its
            // initial snapshot — so a change racing that snapshot still wakes us.
            changes: self.registry.subscribe_changes(),
        }))
    }

    fn menu(&self) -> MenuSnapshot {
        // Serve the snapshot the background task maintains off the main thread;
        // fall back to a one-off inline compute only before the first refresh
        // lands (or with no runtime — the unit tests). Never blocks on git here
        // in the daemon, honouring the trait's "cheap, must not block" contract.
        let cached = self
            .menu_cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        let items = cached.unwrap_or_else(|| {
            menu_items_for(&self.registry.list(), self.rate_limit_cache.get().as_ref())
        });
        MenuSnapshot {
            title: SUBMENU_TITLE.to_string(),
            items,
        }
    }

    async fn menu_action(&self, action_id: &str) -> Result<()> {
        if let Some(key) = action_id.strip_prefix("focus:") {
            // The registry resolves the folder under its own lock and clones it
            // out, so the mutex is never held across the process launch.
            let folder = self
                .registry
                .first_folder(key)
                .ok_or_else(|| anyhow!("no open window with key {key} (it may have closed)"))?;
            focus_window(&folder)?;
            return Ok(());
        }
        bail!("unknown worktrees menu action: {action_id}")
    }

    async fn status(&self) -> ServiceStatus {
        let entries = self.registry.list();
        let repos: BTreeSet<&str> = entries.iter().filter_map(|e| e.repo.as_deref()).collect();
        let summary = format!("{} window(s) across {} repo(s)", entries.len(), repos.len());
        let windows = enriched_windows(entries).await;
        ServiceStatus {
            name: SERVICE_NAME.to_string(),
            healthy: true,
            summary,
            detail: json!({ "windows": windows }),
        }
    }

    async fn shutdown(&self) {
        // Stop the background menu-refresh task; the registry itself is in-memory
        // with nothing to drain or persist. Take the task out from under the lock
        // first so the `std::Mutex` is never held across the `.await`.
        let task = self
            .refresh
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        if let Some(task) = task {
            task.token.cancel();
            let _ = task.handle.await;
        }
        // Same discipline for the PR badge poller (#1337): take it out from under
        // its lock before awaiting, so no `std::Mutex` is held across the `.await`.
        let poller = self
            .poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        if let Some(poller) = poller {
            poller.token.cancel();
            let _ = poller.handle.await;
        }
        // And the GitHub rate-limit poller (#1375), same discipline.
        let rate_limit_poller = self
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        if let Some(poller) = rate_limit_poller {
            poller.token.cancel();
            let _ = poller.handle.await;
        }
    }
}

/// Extracts a required string `field` from an op payload, erroring with the op
/// name when it is absent or not a string. Shared by `heartbeat`/`unregister`
/// (`key`) and `open` (`path`).
fn require_str<'a>(payload: &'a Value, field: &str, op: &str) -> Result<&'a str> {
    payload
        .get(field)
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("`{op}` requires `{field}`"))
}

/// The live git state of a worktree folder: the checked-out branch and how far
/// it has diverged from its upstream. Computed on read from the on-disk repo
/// (#1186), so `list`/`status`/`menu` reflect the current branch rather than a
/// snapshot taken at registration.
///
/// Every field is optional and degrades independently: a folder that is not a
/// git repo, is on a detached HEAD, or whose branch tracks no upstream is still
/// listed — just without the fields it cannot supply. The `skip_serializing_if`
/// attributes let it flatten cleanly onto an entry (see [`EnrichedEntry`]),
/// omitting each absent field on the wire.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
struct GitStatus {
    /// The checked-out branch, or `None` when detached or not in a repo.
    #[serde(skip_serializing_if = "Option::is_none")]
    branch: Option<String>,
    /// The commit HEAD points at, or `None` when unborn or not in a repo. Present
    /// even on a detached HEAD, which has a commit but no branch. Rides the
    /// streamed snapshot so a new commit is a real delta the server's diff cannot
    /// drop — without it, a push serialises byte-identically and no client
    /// re-renders (#1337).
    #[serde(skip_serializing_if = "Option::is_none")]
    head_sha: Option<String>,
    /// The commit the branch's configured upstream ref points at, or `None`
    /// without an upstream (or when detached, unborn, or not in a repo). Rides
    /// the streamed snapshot for the same reason as `head_sha`, one ref over: a
    /// **push** moves only `refs/remotes/<remote>/<branch>`, leaving every other
    /// field — `head_sha` included — byte-identical, so without this the frame
    /// serialised the same, the server's diff dropped it, and the lazily-fetched
    /// ahead/behind was never re-asked (#1344).
    #[serde(skip_serializing_if = "Option::is_none")]
    upstream_sha: Option<String>,
    /// Commits the branch is ahead of its upstream (`None` without an upstream).
    #[serde(skip_serializing_if = "Option::is_none")]
    ahead: Option<usize>,
    /// Commits the branch is behind its upstream (`None` without an upstream).
    #[serde(skip_serializing_if = "Option::is_none")]
    behind: Option<usize>,
    /// The main repository's directory name — the parent repo for a linked
    /// worktree, the checkout's own directory otherwise. Derived from git's
    /// common dir so a worktree names the repo it belongs to rather than its
    /// worktree-folder basename. `None` when not in a repo.
    #[serde(skip_serializing_if = "Option::is_none")]
    main_repo: Option<String>,
    /// Whether the enriched folder is a **linked** git worktree rather than the
    /// repository's main working tree. Omitted (false) for a normal checkout.
    #[serde(skip_serializing_if = "is_false")]
    is_worktree: bool,
}

/// `skip_serializing_if` predicate for a `bool` defaulting to `false`, so the
/// field is dropped on the wire unless set — keeping older clients byte-identical
/// (the protocol's forward-compatibility convention).
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
    !*b
}

/// One persisted PR-poll lease: the GitHub repo (`"owner/name"`) and when its
/// lease expires (#1376). Storing the expiry — not just the repo — is what lets a
/// daemon restart within the lease window keep the *remaining* time rather than
/// resetting the 15-minute clock; an already-expired entry is dropped on load.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PollingLease {
    repo: String,
    expires_at: DateTime<Utc>,
}

/// The on-disk shape of the per-repo PR-poll prefs (#1376): the live leases whose
/// PR badges the daemon polls. Only **enabled** (leased) repos are stored —
/// absence means not-polled (the default-off model) — so the file stays small (a
/// handful of active repos out of many open). `#[serde(default)]` so an
/// empty/older file decodes to "nothing enabled".
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PollingPrefs {
    #[serde(default)]
    enabled: Vec<PollingLease>,
}

/// Writes `prefs` to `path` as pretty JSON with `0600` perms, creating the
/// parent runtime dir (`0700`) if needed — the bridge-token persistence pattern
/// (`BridgeService`), reusing the same [`crate::daemon::paths`] helpers.
fn write_polling_prefs(path: &Path, prefs: &PollingPrefs) -> Result<()> {
    if let Some(parent) = path.parent() {
        crate::daemon::paths::ensure_dir_0700(parent)?;
    }
    let json = serde_json::to_vec_pretty(prefs).context("failed to serialize polling prefs")?;
    crate::daemon::paths::write_file_0600(path, &json)
}

// --- PR-badge cache persistence (#1389, fix 4) -----------------------------

/// A persisted badge — the disk twin of [`PrBadge`](crate::pr_status::PrBadge).
///
/// A distinct DTO rather than reusing `PrBadge`'s derive because the two shapes
/// disagree: `PrBadge` renders onto the **tree wire**, where `head_oid` is
/// `#[serde(skip)]` (it is a local staleness key, never sent) and `is_draft` is
/// `isDraft`. The cache file must round-trip `head_oid` — a restored verdict is
/// compared against the worktree's current HEAD via
/// [`PrBadge::is_stale_for`](crate::pr_status::PrBadge::is_stale_for), and a lost
/// `head_oid` would render every restored badge stale — so it carries the field
/// explicitly under a stable snake_case name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PersistedBadge {
    number: u64,
    is_draft: bool,
    checks: PrCheckState,
    url: String,
    head_oid: String,
}

/// A persisted resolution — the disk twin of
/// [`PrResolution`](crate::pr_status::PrResolution). Externally tagged so the
/// no-PR negative (#1370) round-trips as a plain `"NoPr"` and a badge as
/// `{ "Pr": { … } }`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
enum PersistedResolution {
    Pr(PersistedBadge),
    NoPr,
}

/// One persisted cache entry: which target, and the verdict last resolved for it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PersistedEntry {
    target: PrTarget,
    resolution: PersistedResolution,
}

/// A persisted watch — the `(target, upstream_sha)` the poller compared at the
/// last fetch. Lets a warm start tell "same set, verdicts still fresh → skip the
/// immediate re-poll" from "a target was added or a branch pushed while we were
/// down → fetch" (the [`pr_watch_grew`] comparison, restored across a restart).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PersistedWatch {
    target: PrTarget,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    upstream_sha: Option<String>,
}

/// The on-disk shape of the resolved PR-badge cache (#1389, fix 4): the badges,
/// the watch set they were resolved for, and when. `#[serde(default)]` throughout
/// so an empty/older/partial file decodes to "nothing restored" rather than
/// failing the load — best-effort, exactly like [`PollingPrefs`].
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PrCachePrefs {
    #[serde(default)]
    entries: Vec<PersistedEntry>,
    #[serde(default)]
    watched: Vec<PersistedWatch>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    polled_at: Option<DateTime<Utc>>,
}

impl PersistedResolution {
    /// The disk form of a live resolution.
    fn from_resolution(r: &PrResolution) -> Self {
        match r {
            PrResolution::Pr(b) => Self::Pr(PersistedBadge {
                number: b.number,
                is_draft: b.is_draft,
                checks: b.checks,
                url: b.url.clone(),
                head_oid: b.head_oid.clone(),
            }),
            PrResolution::NoPr => Self::NoPr,
        }
    }

    /// The live form of a restored resolution.
    fn into_resolution(self) -> PrResolution {
        match self {
            Self::Pr(b) => PrResolution::Pr(PrBadge {
                number: b.number,
                is_draft: b.is_draft,
                checks: b.checks,
                url: b.url,
                head_oid: b.head_oid,
            }),
            Self::NoPr => PrResolution::NoPr,
        }
    }
}

/// Assembles the on-disk cache from the live cache entries, the watch they were
/// resolved for, and the poll time.
fn pr_cache_prefs_from(
    entries: Vec<(PrTarget, PrResolution)>,
    watched: &[PrWatch],
    polled_at: DateTime<Utc>,
) -> PrCachePrefs {
    let mut entries: Vec<PersistedEntry> = entries
        .into_iter()
        .map(|(target, resolution)| PersistedEntry {
            target,
            resolution: PersistedResolution::from_resolution(&resolution),
        })
        .collect();
    // Stable on-disk order so the file does not churn on rewrite from `HashMap`
    // iteration order alone (the same reason `PollingPrefs` sorts).
    entries.sort_by(|a, b| a.target.cmp(&b.target));
    let mut watched: Vec<PersistedWatch> = watched
        .iter()
        .map(|w| PersistedWatch {
            target: w.target.clone(),
            upstream_sha: w.upstream_sha.clone(),
        })
        .collect();
    watched.sort_by(|a, b| a.target.cmp(&b.target));
    PrCachePrefs {
        entries,
        watched,
        polled_at: Some(polled_at),
    }
}

/// Writes `prefs` to `path` as pretty JSON with `0600` perms, creating the parent
/// runtime dir (`0700`) if needed — the [`write_polling_prefs`] pattern.
fn write_pr_cache(path: &Path, prefs: &PrCachePrefs) -> Result<()> {
    if let Some(parent) = path.parent() {
        crate::daemon::paths::ensure_dir_0700(parent)?;
    }
    let json = serde_json::to_vec_pretty(prefs).context("failed to serialize PR cache")?;
    crate::daemon::paths::write_file_0600(path, &json)
}

/// Persists the current PR-badge cache to `path` (best-effort). Reads the live
/// entries off `pr_cache`, pairs them with the `watched` set and `polled_at`, and
/// writes the `0600` file; a failure is logged at WARN and swallowed, since the
/// in-memory cache is authoritative for the running daemon and losing the warm
/// start only costs one extra poll after the next restart.
fn persist_pr_cache(
    path: &Path,
    pr_cache: &PrStatusCache,
    watched: &[PrWatch],
    polled_at: DateTime<Utc>,
) {
    let prefs = pr_cache_prefs_from(pr_cache.entries(), watched, polled_at);
    if let Err(err) = write_pr_cache(path, &prefs) {
        let at = path.display();
        tracing::warn!("could not persist worktrees PR cache to {at}: {err:#}");
    }
}

/// Warm-start state restored from the persisted PR-badge cache (#1389, fix 4):
/// the watch set the previous daemon last resolved and when it last polled. The
/// poller seeds its loop from this so a restart within the backoff window skips
/// the immediate re-poll for verdicts it already holds, instead of spending a `gh`
/// call to re-derive what the `0600` file already carries.
#[derive(Debug, Clone)]
struct PrWarmStart {
    /// The `(target, upstream_sha)` set the persisted verdicts describe.
    watched: Vec<PrWatch>,
    /// When those verdicts were resolved, used to age the warm start against the
    /// backoff (a stale-enough file just re-polls).
    polled_at: DateTime<Utc>,
}

// --- Shared open-PR cache for the daemon-served "Open PR" op (#1389, fix 7) -----

/// One cached `gh pr list` result: the forwarded JSON PR array and when it was
/// fetched, for TTL expiry.
#[derive(Debug, Clone)]
struct OpenPrEntry {
    at: Instant,
    prs: Vec<Value>,
}

/// A shared, TTL'd cache of `gh pr list` results per repo (#1389, fix 7).
///
/// Serving "Open Pull Request…" — and the extension's transient badge fallback —
/// from the daemon means N windows asking about one repo dedupe to a single counted
/// `gh pr list` within the TTL, instead of each window shelling its own (the
/// per-window burn #1370/#1389 target). A plain temporal cache, **no single-flight**:
/// the access pattern is a manual action (or a brief post-enable transient), so two
/// exactly-concurrent misses for the same repo — costing one extra `gh` — are rare
/// and harmless, while the common repeat-within-TTL is served for free. The lock is
/// never held across an `.await`.
#[derive(Debug)]
struct OpenPrCache {
    entries: Mutex<HashMap<String, OpenPrEntry>>,
    ttl: Duration,
}

impl OpenPrCache {
    fn new(ttl: Duration) -> Self {
        Self {
            entries: Mutex::new(HashMap::new()),
            ttl,
        }
    }

    /// The cached PRs for `key` (`owner/name`) while still within the TTL, else
    /// `None` (a miss that the caller resolves with a fresh `gh`).
    fn fresh(&self, key: &str) -> Option<Vec<Value>> {
        self.entries
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(key)
            .filter(|e| e.at.elapsed() < self.ttl)
            .map(|e| e.prs.clone())
    }

    /// Records a freshly-fetched PR list for `key`.
    fn store(&self, key: String, prs: Vec<Value>) {
        self.entries
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(
                key,
                OpenPrEntry {
                    at: Instant::now(),
                    prs,
                },
            );
    }
}

/// Runs `gh pr list` for `slug` (`owner/name`) through the #1387-counted `run_gh`
/// choke point and parses the JSON array of open PRs. **Blocking** (a subprocess) —
/// call on a blocking thread, never an async worker. The array is forwarded to the
/// extension verbatim, which parses it into its `PullRequest` shape.
fn open_pr_list(bin: &Path, slug: &str) -> Result<Vec<Value>> {
    let output = crate::github_metrics::run_gh(
        bin,
        [
            "pr",
            "list",
            "--repo",
            slug,
            "--state",
            "open",
            "--json",
            OPEN_PR_JSON_FIELDS,
            "--limit",
            OPEN_PR_LIST_LIMIT,
        ],
        "pr list",
        None,
    )
    .with_context(|| {
        format!(
            "failed to run {} (is the GitHub CLI installed?)",
            bin.display()
        )
    })?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("gh pr list failed: {}", stderr.trim());
    }
    match serde_json::from_slice(&output.stdout).context("gh pr list returned invalid JSON")? {
        Value::Array(arr) => Ok(arr),
        _ => bail!("gh pr list did not return a JSON array"),
    }
}

/// Computes the **full** [`GitStatus`] of `folder` — branch, repo identity, and
/// the ahead/behind divergence from upstream. Used by the one-shot `list`/`status`
/// op and the tray menu, both bounded to the (few) open windows, where the extra
/// `graph_ahead_behind` walk is negligible. The streamed `tree` snapshot uses the
/// cheaper [`git_status_cheap`] instead and fetches divergence on demand (#1306).
fn git_status(folder: &Path) -> GitStatus {
    git_status_impl(folder, true)
}

/// Computes the **cheap** [`GitStatus`] of `folder` — branch and repo identity
/// only, skipping the (expensive) `graph_ahead_behind` upstream revwalk. Used by
/// the `tree`/`subscribe` snapshot, which is rebuilt for **every** worktree on
/// **every** tick: divergence there is computed lazily via the `ahead-behind` op
/// only for the worktrees a client actually looks at (#1306). The `ahead`/`behind`
/// fields stay `None`, so they are omitted on the wire exactly as for a branch
/// with no upstream.
fn git_status_cheap(folder: &Path) -> GitStatus {
    git_status_impl(folder, false)
}

/// The shared body of [`git_status`] / [`git_status_cheap`]: discovers the
/// repository that contains `folder` — so a subdirectory or a linked worktree both
/// resolve — reads HEAD, and (only when `with_ahead_behind`) walks the upstream
/// divergence. Every failure mode degrades to an empty status rather than
/// erroring: the enrichment is best-effort and must never sink a `list` or a tree.
fn git_status_impl(folder: &Path, with_ahead_behind: bool) -> GitStatus {
    let Ok(repo) = Repository::discover(folder) else {
        return GitStatus::default();
    };
    // Repo identity applies even when HEAD is unborn or detached, so a worktree
    // still names its parent repo (and is flagged as a worktree) in those states.
    let base = GitStatus {
        main_repo: main_repo_name(repo.commondir()),
        is_worktree: repo.is_worktree(),
        ..GitStatus::default()
    };
    let Ok(head) = repo.head() else {
        // An unborn branch (fresh repo, no commits) or an unreadable HEAD.
        return base;
    };
    // Resolved here — before the branch filter below, so a detached HEAD still
    // reports its commit, and before `Branch::wrap` consumes `head`. `target()` is
    // a refs read: no revwalk and no object lookup, so unlike the divergence walk
    // it is cheap enough for the streamed snapshot's every-worktree-every-tick
    // rebuild (#1306's bar).
    let base = GitStatus {
        head_sha: head.target().map(|oid| oid.to_string()),
        ..base
    };
    // A branch HEAD has a UTF-8 shorthand; anything else — a detached HEAD
    // (mid-rebase or a checked-out tag/commit), or the rare non-UTF-8 branch
    // name — degrades to no branch through this one path.
    let Some(name) = head
        .shorthand()
        .ok()
        .filter(|_| head.is_branch())
        .map(str::to_string)
    else {
        return base;
    };
    // Consumes `head`, so it has to follow the `shorthand()` read above. A pure
    // type wrapper — no I/O — so hoisting it out of the `with_ahead_behind` arm
    // below costs the cheap path nothing, and is what gives it a handle to
    // resolve the upstream from.
    let branch = git2::Branch::wrap(head);
    // Unlike the divergence walk, this rides both paths: it is what makes a push
    // a visible delta (#1344).
    let upstream_sha = upstream_target(&branch);
    // The divergence walk is the dominant per-worktree cost, so the cheap path
    // skips it and leaves ahead/behind absent.
    let (ahead, behind) = if with_ahead_behind {
        match upstream_ahead_behind(&repo, &branch) {
            Some((ahead, behind)) => (Some(ahead), Some(behind)),
            None => (None, None),
        }
    } else {
        (None, None)
    };
    GitStatus {
        branch: Some(name),
        upstream_sha,
        ahead,
        behind,
        ..base
    }
}

/// The commit `branch`'s configured upstream ref points at, or `None` when it
/// tracks no upstream (or the ref is unresolvable).
///
/// Costs a config lookup (`branch.<name>.remote` + `.merge`) and a
/// remote-tracking refs read — more than [`git_status_impl`]'s single `head`
/// refs read, but still **no revwalk and no object lookup**, which is the bar
/// #1306 set for the snapshot's every-worktree-every-tick rebuild and the one
/// `graph_ahead_behind` fails. [`upstream_ahead_behind`] already resolves the
/// same OID, so it is proven reachable.
fn upstream_target(branch: &git2::Branch<'_>) -> Option<String> {
    Some(branch.upstream().ok()?.get().target()?.to_string())
}

/// The ahead/behind divergence of `folder`'s checked-out branch versus its
/// upstream, computed on demand for the lazy `ahead-behind` op (#1306). Mirrors the
/// branch resolution in [`git_status_impl`] but does **only** the upstream walk
/// [`git_status_cheap`] omits. `None` when `folder` is not a repo, is on a detached
/// or unborn HEAD, or tracks no upstream — every case the tree renders without a
/// sync indicator.
fn folder_ahead_behind(folder: &Path) -> Option<(usize, usize)> {
    let repo = Repository::discover(folder).ok()?;
    let head = repo.head().ok()?;
    if !head.is_branch() {
        return None;
    }
    let branch = git2::Branch::wrap(head);
    upstream_ahead_behind(&repo, &branch)
}

/// The main repository's directory name from git's common dir. For the usual
/// `<repo>/.git` layout — shared by a checkout and all its linked worktrees —
/// that is the working-tree directory's name; for a bare repo (`<name>.git`) it
/// is that directory with a trailing `.git` stripped. Best-effort: `None` when
/// no name can be derived.
fn main_repo_name(commondir: &Path) -> Option<String> {
    let file_name = commondir.file_name()?.to_string_lossy().into_owned();
    if file_name == ".git" {
        // Normal layout: the repo is the directory that contains `.git`.
        commondir
            .parent()
            .and_then(Path::file_name)
            .map(|n| n.to_string_lossy().into_owned())
    } else {
        // A bare repo: use its own directory name, without any `.git` suffix.
        Some(
            file_name
                .strip_suffix(".git")
                .unwrap_or(&file_name)
                .to_string(),
        )
    }
}

/// Ahead/behind commit counts of `branch` versus its configured upstream, or
/// `None` when the branch tracks no upstream (or either tip is unresolvable).
fn upstream_ahead_behind(repo: &Repository, branch: &git2::Branch<'_>) -> Option<(usize, usize)> {
    let upstream = branch.upstream().ok()?;
    let local_oid = branch.get().target()?;
    let upstream_oid = upstream.get().target()?;
    repo.graph_ahead_behind(local_oid, upstream_oid).ok()
}

/// The wire shape of an enriched window: the stored entry fields plus the
/// daemon-computed git state, flattened into one JSON object. Serializing
/// through a single struct (rather than mutating a `Value`) keeps every present
/// field on one code path and lets `skip_serializing_if` on [`GitStatus`] drop
/// the absent git fields — no manual per-field insertion.
#[derive(Serialize)]
struct EnrichedEntry<'a> {
    #[serde(flatten)]
    entry: &'a WindowEntry,
    #[serde(flatten)]
    git: GitStatus,
}

/// Serializes a registry entry and folds in the live [`git_status`] of its
/// primary (first) folder, producing the JSON object served on the wire
/// (`list`/`status`) and read by the extension UI. Only the primary folder is
/// enriched — it is the one the table shows and the "focus" action opens.
fn enriched_entry(entry: &WindowEntry) -> Value {
    let git = entry
        .folders
        .first()
        .map(|folder| git_status(folder))
        .unwrap_or_default();
    serde_json::to_value(EnrichedEntry { entry, git }).unwrap_or_else(|_| json!({}))
}

/// Enriches a batch of entries with their git state on a blocking thread, since
/// `git2` does synchronous disk I/O and this runs inside the async control-socket
/// handler. A join failure degrades to an empty list rather than erroring.
async fn enriched_windows(entries: Vec<WindowEntry>) -> Vec<Value> {
    tokio::task::spawn_blocking(move || entries.iter().map(enriched_entry).collect())
        .await
        .unwrap_or_default()
}

// --- Repo/worktree tree (#1265) ----------------------------------------------

/// A GitHub `owner/name` identity parsed from a repository's `origin` remote.
/// Present on a repo in the `tree` payload only for `github.com` remotes; a
/// non-GitHub (or remote-less) repo omits it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct GithubIdentity {
    /// The repository owner (user or org) — the first path segment.
    owner: String,
    /// The repository name, with any `.git` suffix stripped.
    name: String,
}

/// One worktree of a repository in the `tree` payload: its path, live git state,
/// whether it is the main working tree, and whether a VS Code window currently
/// has it open (with that window's key, for the focus action). Optional git
/// fields degrade independently, exactly like [`GitStatus`].
///
/// Ahead/behind **divergence** is deliberately absent from this snapshot: it was
/// the dominant per-worktree cost when computed eagerly for every worktree on
/// every tick, so it is now fetched lazily via the `ahead-behind` op only for the
/// worktrees a client actually shows (#1306).
///
/// The two **OIDs** the divergence is computed from — `head_sha` and
/// `upstream_sha` — do ride the snapshot, which is not a contradiction: each is a
/// refs read rather than a commit-graph walk, and between them they are what makes
/// a commit (#1337) or a push (#1344) a *visible delta*, so a client knows to
/// re-ask for the counts it left behind.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct TreeWorktree {
    /// Absolute path to the worktree's working directory.
    path: String,
    /// The checked-out branch, or `None` when detached or unborn.
    #[serde(skip_serializing_if = "Option::is_none")]
    branch: Option<String>,
    /// The commit HEAD points at, or `None` when unborn. Unlike ahead/behind this
    /// **does** ride the snapshot: it costs a refs read, and it is what makes a new
    /// commit a visible delta, so a push re-renders instead of being dropped by the
    /// server's snapshot diff (#1337).
    #[serde(skip_serializing_if = "Option::is_none")]
    head_sha: Option<String>,
    /// The commit the branch's upstream ref points at, or `None` without an
    /// upstream. The push counterpart of `head_sha`: a push moves only
    /// `refs/remotes/<remote>/<branch>`, so this is the *one* field that moves —
    /// making the snapshot a real delta the server's diff cannot drop, which is
    /// what re-fetches the lazy ahead/behind (#1344).
    #[serde(skip_serializing_if = "Option::is_none")]
    upstream_sha: Option<String>,
    /// Whether this is the repository's main working tree (vs a linked worktree).
    is_main: bool,
    /// Whether a live VS Code window currently has this worktree open.
    open: bool,
    /// The open window's registry key, when `open` — the handle a focus action
    /// resolves. Absent for a worktree with no open window.
    #[serde(skip_serializing_if = "Option::is_none")]
    window_key: Option<String>,
    /// The open PR whose head is this worktree's branch, with its CI verdict
    /// (#1337). Resolved by the daemon's background poller and folded on as the
    /// snapshot is built, so every open window sees the same live state without
    /// each running its own `gh`. Absent for a detached/non-GitHub worktree, one
    /// with no open PR (see `pr_none`), or until the first poll lands.
    #[serde(skip_serializing_if = "Option::is_none")]
    pr: Option<PrBadge>,
    /// Set when the daemon **checked GitHub and found no open PR** for this
    /// worktree's branch — the explicit negative (#1370), mutually exclusive
    /// with `pr`. Omitted (false) whenever `pr` is present, for a branchless or
    /// non-GitHub worktree, and — crucially — while the branch is simply **not
    /// yet resolved** (before the first poll lands, or ever, on a failed one):
    /// `pr` absent *and* `pr_none` absent still means "not resolved", so an
    /// older client stays byte-identical (ADR-0053). Clients use it to keep
    /// their degraded per-window `gh pr list` fallback quiet for branches the
    /// daemon has already answered for.
    #[serde(skip_serializing_if = "is_false")]
    pr_none: bool,
}

/// One repository (with **all** its worktrees) in the `tree` payload. Repos are
/// derived from the distinct open windows; a repo leaves the tree when its last
/// window closes (the open-window-derived model, ADR-0040 / #1264).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct TreeRepo {
    /// The main repository's directory name (see [`main_repo_name`]).
    main_repo: String,
    /// The GitHub identity of `origin`, when it is a `github.com` remote.
    #[serde(skip_serializing_if = "Option::is_none")]
    github: Option<GithubIdentity>,
    /// Absolute path to the main working tree — the repo's root.
    root: String,
    /// Whether the daemon polls this repo's PR badges (#1376). Stamped from the
    /// registry's per-repo enable set, which defaults **off**, so it is omitted
    /// (false) for the common not-polled repo — keeping older clients
    /// byte-identical — and present (`true`) only for a repo the user has
    /// explicitly enabled. The extension colours the repo icon green when set and
    /// gates the "Disable PR Polling" menu on it; the daemon's own poller filters
    /// on it so a not-polled repo issues zero `gh`.
    #[serde(skip_serializing_if = "is_false")]
    polling_enabled: bool,
    /// Every worktree of the repo: the main working tree first, then linked
    /// worktrees sorted by path.
    worktrees: Vec<TreeWorktree>,
}

/// Parses a git remote URL into its GitHub `owner/name`, or `None` for any
/// non-GitHub host. Handles the common forms: `https://github.com/o/r(.git)`,
/// `http://…`, `ssh://git@github.com/o/r(.git)`, `git://github.com/o/r(.git)`,
/// and the SCP-like `git@github.com:o/r(.git)`. A trailing `.git` and trailing
/// slashes are stripped; anything with an empty or extra path segment is
/// rejected (best-effort, never panics).
fn github_identity(url: &str) -> Option<GithubIdentity> {
    let url = url.trim();
    // Reduce every supported form to the `owner/name…` tail after the host.
    let rest = [
        "https://github.com/",
        "http://github.com/",
        "ssh://git@github.com/",
        "git://github.com/",
        "git@github.com:",
    ]
    .iter()
    .find_map(|prefix| url.strip_prefix(prefix))?;
    let rest = rest.strip_suffix(".git").unwrap_or(rest);
    let rest = rest.trim_end_matches('/');
    let mut parts = rest.splitn(2, '/');
    let owner = parts.next()?.trim();
    let name = parts.next()?.trim();
    // A well-formed identity has exactly two non-empty segments.
    if owner.is_empty() || name.is_empty() || name.contains('/') {
        return None;
    }
    Some(GithubIdentity {
        owner: owner.to_string(),
        name: name.to_string(),
    })
}

/// The GitHub identity of `repo`: `origin`'s URL first, else the first
/// `github.com` remote found. `None` when no remote is a GitHub remote.
fn remote_github_identity(repo: &Repository) -> Option<GithubIdentity> {
    if let Ok(origin) = repo.find_remote("origin") {
        if let Some(id) = origin.url().ok().and_then(github_identity) {
            return Some(id);
        }
    }
    // `remotes()` yields `Result<Option<&str>, _>` per name; the first flatten
    // drops the (per-name) errors, the second the non-UTF-8 `None`s. `names` is
    // bound so `iter()` can borrow it (only `&StringArray` is `IntoIterator`).
    let names = repo.remotes().ok();
    names
        .iter()
        .flat_map(|arr| arr.iter())
        .flatten()
        .flatten()
        .filter_map(|name| repo.find_remote(name).ok())
        .find_map(|remote| remote.url().ok().and_then(github_identity))
}

/// Canonicalizes a path for stable comparison (resolving symlinks and `..`),
/// falling back to the path as-given when it cannot be canonicalized (e.g. it
/// no longer exists) so the join still degrades gracefully.
fn canonical(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// Indexes the open windows by canonicalized workspace-folder path → window key,
/// so a worktree path can be joined back to the window (if any) that has it open.
/// The first window wins a shared folder; `entries` arrive in a deterministic
/// (repo, key) order, so the choice is stable.
fn open_window_index(entries: &[WindowEntry]) -> HashMap<PathBuf, String> {
    let mut index = HashMap::new();
    for entry in entries {
        for folder in &entry.folders {
            index
                .entry(canonical(folder))
                .or_insert_with(|| entry.key.clone());
        }
    }
    index
}

/// Builds a [`TreeWorktree`] for `path`: reuses [`git_status_cheap`] for the live
/// git state (branch + repo identity, **no** ahead/behind walk — that is lazy per
/// #1306) and joins the open-window index for `open`/`window_key`. `is_main` is set
/// by the caller from the enumeration (main working tree vs linked).
fn worktree_entry(
    path: &Path,
    is_main: bool,
    open_index: &HashMap<PathBuf, String>,
) -> TreeWorktree {
    let status = git_status_cheap(path);
    let window_key = open_index.get(&canonical(path)).cloned();
    TreeWorktree {
        path: path.display().to_string(),
        branch: status.branch,
        head_sha: status.head_sha,
        upstream_sha: status.upstream_sha,
        is_main,
        open: window_key.is_some(),
        window_key,
        // Folded on afterwards by `fold_pr_badges`, which needs the repo's GitHub
        // identity — known one level up, in `repo_tree`.
        pr: None,
        pr_none: false,
    }
}

/// Folds the poller's cached PR resolutions onto each worktree of each repo
/// (#1337).
///
/// Runs after [`build_tree`] because a resolution is keyed by (repo GitHub
/// identity, branch) and the identity is only known once the repo is assembled.
/// Purely a cache read — no I/O, no network — so it is safe on the snapshot's hot
/// path. A non-GitHub repo, a branchless worktree, or an unresolved branch simply
/// keeps `pr: None`/`pr_none: false` and renders nothing.
///
/// A verdict computed for a **different commit** than the worktree has checked out
/// is downgraded to pending here rather than shown as-is. That is what makes a push
/// invalidate the badge the moment it happens: the cache still holds the previous
/// commit's verdict, and this fold — which runs on every snapshot — notices without
/// waiting for a poll. Without it the previous head's `✓` stands until the poller
/// next runs, which is up to the full backoff.
///
/// A **negative** ([`PrResolution::NoPr`], #1370) is deliberately *not* dropped
/// when `head_sha` moves: it has no commit to be stale against, and dropping it
/// would re-arm every client's `gh` fallback on every local commit. The poller's
/// `moved` trigger re-checks the branch within one fast poll anyway.
/// Stamps each repo's `polling_enabled` flag from the registry's per-repo PR-poll
/// enable set (#1376).
///
/// Runs after [`build_tree`] (which knows the GitHub identity) and **before**
/// [`fold_pr_badges`] (which skips a not-polled repo), so a repo the user has not
/// enabled carries neither the flag nor any badge. Purely a set membership check —
/// no I/O — so it is safe on the snapshot's hot path. A non-GitHub repo has no key
/// and stays `false`; it never polls anyway.
fn stamp_polling(repos: &mut [TreeRepo], enabled: &HashSet<String>) {
    for repo in repos {
        if let Some(github) = &repo.github {
            repo.polling_enabled = enabled.contains(&format!("{}/{}", github.owner, github.name));
        }
    }
}

fn fold_pr_badges(repos: &mut [TreeRepo], pr_cache: &PrStatusCache) {
    for repo in repos {
        // A not-polled repo (#1376) never carries a badge: skip it so a repo the
        // user disabled drops its `pr`/`pr_none` the moment `stamp_polling` clears
        // the flag, and so the icon greys cross-window on the next pushed snapshot.
        if !repo.polling_enabled {
            continue;
        }
        let Some(github) = repo.github.clone() else {
            continue;
        };
        for worktree in &mut repo.worktrees {
            let Some(branch) = &worktree.branch else {
                continue;
            };
            match pr_cache.get(&github.owner, &github.name, branch) {
                Some(PrResolution::Pr(mut badge)) => {
                    if badge.is_stale_for(worktree.head_sha.as_deref()) {
                        badge.checks = PrCheckState::Pending;
                    }
                    worktree.pr = Some(badge);
                }
                Some(PrResolution::NoPr) => worktree.pr_none = true,
                None => {}
            }
        }
    }
}

/// Enumerates a repository and all its worktrees into a [`TreeRepo`], given a
/// handle discovered from one of its folders. Opens the **main** repo from the
/// shared common dir's parent so the main working tree and every linked worktree
/// are enumerated regardless of which one seeded the discovery. `None` for a
/// bare or otherwise root-less repo (no working tree to show).
fn repo_tree(discovered: &Repository, open_index: &HashMap<PathBuf, String>) -> Option<TreeRepo> {
    // The common dir (`…/<root>/.git`) is shared by the main checkout and all
    // linked worktrees; its parent is the main working tree.
    let commondir = canonical(discovered.commondir());
    let main_root = commondir.parent()?.to_path_buf();
    let main_repo = Repository::open(&main_root).ok()?;

    // Main working tree first.
    let mut worktrees = vec![worktree_entry(&main_root, true, open_index)];
    // Then every linked worktree, sorted by path for deterministic output. The
    // `StringArray` of names is bound so `iter()` can borrow it (only
    // `&StringArray` is `IntoIterator`); a name that no longer resolves to a
    // worktree is skipped.
    let names = main_repo.worktrees().ok();
    let mut linked: Vec<PathBuf> = names
        .iter()
        .flat_map(|arr| arr.iter())
        .flatten() // Result<Option<&str>, _> → Option<&str> (drop per-name errors)
        .flatten() // Option<&str> → &str (drop non-UTF-8 names)
        .filter_map(|name| main_repo.find_worktree(name).ok())
        .map(|wt| wt.path().to_path_buf())
        .collect();
    linked.sort();
    worktrees.extend(
        linked
            .iter()
            .map(|path| worktree_entry(path, false, open_index)),
    );

    Some(TreeRepo {
        main_repo: main_repo_name(&commondir)?,
        github: remote_github_identity(&main_repo),
        root: main_root.display().to_string(),
        // Defaults off; `stamp_polling` sets it from the registry's enable set
        // once the repo (and thus its GitHub identity) is assembled.
        polling_enabled: false,
        worktrees,
    })
}

/// Resolves the seed `folders` to their distinct repositories and enumerates
/// each repo's worktrees. Dedupes repos by their common dir (shared across a
/// repo's worktrees) via a `BTreeMap` for deterministic ordering; a folder that
/// is not in a git repo is skipped. Pure blocking git I/O — call it via
/// [`tree_repos`], never under the registry lock.
fn build_tree(folders: Vec<PathBuf>, windows: Vec<WindowEntry>) -> Vec<TreeRepo> {
    let open_index = open_window_index(&windows);
    let mut repos: BTreeMap<PathBuf, TreeRepo> = BTreeMap::new();
    for folder in &folders {
        let Ok(repo) = Repository::discover(folder) else {
            continue;
        };
        let key = canonical(repo.commondir());
        if repos.contains_key(&key) {
            continue;
        }
        if let Some(tree) = repo_tree(&repo, &open_index) {
            repos.insert(key, tree);
        }
    }
    repos.into_values().collect()
}

/// Enumerates and enriches the repo/worktree tree on a blocking thread (`git2`
/// does synchronous disk I/O and this runs inside the async control-socket
/// handler), returning the serialized `repos` array. A join failure degrades to
/// an empty list rather than erroring, matching [`enriched_windows`].
async fn tree_repos(
    folders: Vec<PathBuf>,
    windows: Vec<WindowEntry>,
    pr_cache: Arc<PrStatusCache>,
    enabled_polling: HashSet<String>,
) -> Vec<Value> {
    tokio::task::spawn_blocking(move || {
        let mut repos = build_tree(folders, windows);
        // Stamp per-repo poll state first so `fold_pr_badges` can skip a
        // not-polled repo — a disabled repo carries neither the flag nor a badge.
        stamp_polling(&mut repos, &enabled_polling);
        fold_pr_badges(&mut repos, &pr_cache);
        repos
            .iter()
            .map(|repo| serde_json::to_value(repo).unwrap_or_else(|_| json!({})))
            .collect()
    })
    .await
    .unwrap_or_default()
}

// --- Lazy ahead/behind (#1306) -----------------------------------------------

/// Computes the ahead/behind divergence for a batch of worktree `paths` on demand,
/// returning a JSON object keyed by the **requested** path string:
/// `{ "<path>": { "ahead": n, "behind": m }, … }`. A path with no upstream (or that
/// is not a repo / is detached) is **omitted** — the client renders it without a
/// sync indicator, exactly as the tree does for an absent `ahead`/`behind`.
///
/// Backs the `ahead-behind` op, which exists precisely so the streamed `tree`
/// snapshot can stay cheap: a client fetches divergence only for the worktrees it
/// shows (the extension on expand), not for every worktree on every tick. The git
/// walks are blocking disk I/O, so they run on a blocking thread; a join failure
/// degrades to an empty object rather than erroring.
async fn ahead_behind_results(paths: Vec<PathBuf>) -> Value {
    tokio::task::spawn_blocking(move || {
        let mut results = serde_json::Map::new();
        for path in paths {
            if let Some((ahead, behind)) = folder_ahead_behind(&path) {
                results.insert(
                    path.display().to_string(),
                    json!({ "ahead": ahead, "behind": behind }),
                );
            }
        }
        Value::Object(results)
    })
    .await
    .unwrap_or_else(|_| json!({}))
}

// --- Push subscription (#1267) -----------------------------------------------

/// The [`ServiceStream`] backing the worktrees `subscribe` op: a live push of
/// the same `{ repos: [...] }` snapshot the `tree` op returns (#1265). The
/// server drives it — awaiting [`changed`](ServiceStream::changed) plus its own
/// periodic tick, then diffing [`snapshot`](ServiceStream::snapshot) — so this
/// type only has to (a) relay the registry's change-notify and (b) read the
/// tree snapshot on demand.
///
/// Every window's stream shares one [`TreeSnapshotCache`] (#1303): the snapshot
/// is built at most once per tick and fanned out, rather than each stream
/// rebuilding the identical tree. This type holds only cheap handles — a clone
/// of the shared cache and its own change-notify receiver.
struct WorktreesStream {
    /// The shared coalescing cache the snapshot is read through, so every
    /// stream's tick/change re-sample hits one shared `build_tree` (#1303).
    cache: Arc<TreeSnapshotCache>,
    /// Wakes on each visible-set change (a `register`, a removing `unregister`,
    /// or a mutation-driven reap). A burst coalesces into one wakeup; the
    /// server's diff drops any snapshot that ends up identical.
    changes: watch::Receiver<u64>,
}

#[async_trait]
impl ServiceStream for WorktreesStream {
    async fn changed(&mut self) {
        // `watch::Receiver::changed` marks the newest version seen, so a burst of
        // bumps collapses into a single wakeup. If every sender is gone (the
        // registry — and thus the daemon — is tearing down) it returns `Err`;
        // park instead of returning, so this arm can never spin the server's
        // `select!` (the tick and shutdown arms still drive teardown).
        if self.changes.changed().await.is_err() {
            std::future::pending::<()>().await;
        }
    }

    async fn snapshot(&self) -> Value {
        // Read through the shared coalescing cache. The value is built by the
        // same `tree_snapshot` the `tree` op runs, so a one-shot fetch and this
        // live push agree byte-for-byte — but here it is built once per tick and
        // shared across every subscriber rather than rebuilt per stream (#1303).
        self.cache.snapshot().await
    }
}

/// A coalescing cache for the global tree snapshot (#1303).
///
/// Every open VS Code window holds one persistent [`WorktreesStream`], and the
/// server re-samples each on its own `STREAM_TICK` and on every registry change
/// — so with N windows the *identical* global tree was being built N times per
/// tick. This cache collapses that to **one** build: all streams share it, and
/// it rebuilds at most once per `ttl` (the stream tick) per registry
/// change-generation.
///
/// Two conditions gate reuse, and **both** must hold, so freshness is preserved
/// exactly as before:
/// - the registry's [`change_generation`](WorktreesRegistry::change_generation)
///   still matches — a `register`/`unregister`/toggle bumps it and forces a
///   fresh build, so subscribers never see a stale visible set; and
/// - the cached value is younger than `ttl` — so a pure on-disk git change (a
///   branch switch, new commits), which fires no registry event, still surfaces
///   within one tick.
///
/// Concurrency is single-flight: the `.await`-held [`AsyncMutex`] serializes
/// callers, so a burst of N streams waking on the same tick/change performs one
/// build while the rest wait and read the shared result. The one-shot `tree` op
/// bypasses this and computes fresh — it is a rare manual refresh, not part of
/// the per-tick fan-out.
struct TreeSnapshotCache {
    /// The registry every snapshot is built from, and whose change-generation
    /// gates cache reuse.
    registry: Arc<WorktreesRegistry>,
    /// PR badges folded onto each worktree as the snapshot is built (#1337).
    /// Written by the background poller; read here. A miss simply omits `pr`.
    pr_cache: Arc<PrStatusCache>,
    /// How long a built snapshot stays fresh before a tick-driven read rebuilds
    /// it. Defaults to the server's `STREAM_TICK` (via [`new`](Self::new)) so the
    /// coalesced build runs at most once per tick; tests inject a shorter value.
    ttl: Duration,
    /// The single-flight guard and cached result. A `tokio` mutex (not `std`)
    /// because it is deliberately held across the `.await` of the git
    /// enumeration, so concurrent callers serialize onto one build rather than
    /// each computing their own.
    state: AsyncMutex<Option<CachedTree>>,
    /// How many times the tree was actually (re)built — so tests can assert the
    /// coalescing collapses an N-stream burst into one build. Cheap and always
    /// maintained; only read under `#[cfg(test)]`.
    computes: AtomicU64,
}

/// One cached tree snapshot: the shared value plus the two freshness stamps
/// [`TreeSnapshotCache`] checks before reusing it.
struct CachedTree {
    /// The registry change-generation captured *before* the build, so a change
    /// racing the build advances the generation and the next read rebuilds
    /// (conservative: it may rebuild once needlessly, but never serves stale).
    generation: u64,
    /// When the value was built, for the `ttl` staleness check.
    computed_at: Instant,
    /// The already-built `{ repos, show_closed }` snapshot, fanned out to every
    /// subscriber by cloning the `Arc`'s inner value.
    value: Arc<Value>,
}

impl TreeSnapshotCache {
    /// Creates a cache over `registry` with the default TTL — the server's
    /// [`stream_tick`](crate::daemon::server::stream_tick), so the coalesced
    /// build runs at most once per tick.
    fn new(registry: Arc<WorktreesRegistry>, pr_cache: Arc<PrStatusCache>) -> Self {
        Self::with_ttl(registry, pr_cache, crate::daemon::server::stream_tick())
    }

    /// Creates a cache with an explicit `ttl`, for tests that need a short (or
    /// long) freshness window without waiting a real tick.
    fn with_ttl(
        registry: Arc<WorktreesRegistry>,
        pr_cache: Arc<PrStatusCache>,
        ttl: Duration,
    ) -> Self {
        Self {
            registry,
            pr_cache,
            ttl,
            state: AsyncMutex::new(None),
            computes: AtomicU64::new(0),
        }
    }

    /// The current tree snapshot, built at most once per `ttl` per registry
    /// change-generation and shared across all callers. See the type docs for
    /// the freshness and single-flight semantics.
    async fn snapshot(&self) -> Value {
        // Hold the lock across the whole check-and-build so concurrent callers
        // serialize onto one build (single-flight); reading the generation here
        // (before the build) means a change racing the build forces the *next*
        // read to rebuild rather than serving this now-stale value.
        let mut state = self.state.lock().await;
        let generation = self.registry.change_generation();
        // Reuse the cached value only while it matches the current generation
        // *and* is within the TTL; either failing forces a rebuild.
        let fresh = state.as_ref().and_then(|cached| {
            (cached.generation == generation && cached.computed_at.elapsed() < self.ttl)
                .then(|| Arc::clone(&cached.value))
        });
        let value = if let Some(value) = fresh {
            value
        } else {
            let value = Arc::new(tree_snapshot(&self.registry, self.pr_cache.clone()).await);
            self.computes.fetch_add(1, Ordering::Relaxed);
            *state = Some(CachedTree {
                generation,
                computed_at: Instant::now(),
                value: Arc::clone(&value),
            });
            value
        };
        // Release the lock before the (deeper) clone of the shared value out.
        drop(state);
        (*value).clone()
    }

    /// How many times the tree was actually built — the coalescing assertion in
    /// tests (N reads within one tick/generation should build once).
    #[cfg(test)]
    fn compute_count(&self) -> u64 {
        self.computes.load(Ordering::Relaxed)
    }
}

/// Builds the `{ repos, show_closed }` snapshot shared by the `tree` op and the
/// `subscribe` stream, so the two never drift (#1301). Two cheap registry locks
/// (the seed folders to derive repos from, and the live windows to join on) and
/// a lock-free read of the toggle, then the git enumeration/enrichment off the
/// lock on a blocking thread inside [`tree_repos`].
async fn tree_snapshot(registry: &WorktreesRegistry, pr_cache: Arc<PrStatusCache>) -> Value {
    let folders = registry.open_folders();
    let windows = registry.list();
    let show_closed = registry.show_closed();
    let enabled_polling = registry.enabled_polling_repos();
    json!({
        "repos": tree_repos(folders, windows, pr_cache, enabled_polling).await,
        "show_closed": show_closed,
    })
}

/// A short human name for a window: its repo, else its first folder's basename,
/// else a placeholder.
fn display_name(entry: &WindowEntry) -> String {
    if let Some(repo) = &entry.repo {
        return repo.clone();
    }
    if let Some(folder) = entry.folders.first() {
        return folder.file_name().map_or_else(
            || folder.display().to_string(),
            |n| n.to_string_lossy().into_owned(),
        );
    }
    "(no folder)".to_string()
}

/// Separator between the repo name and branch for a normal working tree.
const REPO_SEP: char = '·';
/// Separator marking a **linked worktree** (a git "fork" glyph), so a worktree
/// line is distinguishable at a glance from its parent repo's main checkout.
const WORKTREE_SEP: char = '';

/// The full tray item list for a window set: the "No open windows" placeholder
/// when empty, else one line per window via [`window_menu_items`]. Does the git
/// enrichment (blocking disk I/O), so it runs on a blocking thread from the
/// background refresh task — and inline only as a cold-start fallback in `menu`.
fn menu_items_for(
    entries: &[WindowEntry],
    rate_limit: Option<&RateLimitSnapshot>,
) -> Vec<MenuItem> {
    let mut items = Vec::new();
    // Prepend the GitHub rate-limit reading (#1375) as a non-clickable status line
    // above the windows, so an approaching exhaustion is visible in the tray before
    // it bites. Absent (unpolled `gh`, or no resources) → no line and no separator.
    if let Some(label) = rate_limit.map(RateLimitSnapshot::tray_label) {
        if !label.is_empty() {
            items.push(MenuItem::Label(label));
            items.push(MenuItem::Separator);
        }
    }
    if entries.is_empty() {
        items.push(MenuItem::Label("No open windows".to_string()));
    } else {
        items.extend(window_menu_items(entries));
    }
    items
}

/// Builds the tray items for a non-empty window list: **one clickable line per
/// window** whose label carries the live git state and whose click focuses that
/// window. A window with no workspace folder has nothing for `code` to open, so
/// it stays a non-clickable status line. The labels read each worktree from disk
/// (via [`window_label`]) — cheap for a realistic window count and consistent
/// with reap-on-read.
fn window_menu_items(entries: &[WindowEntry]) -> Vec<MenuItem> {
    entries
        .iter()
        .map(|entry| {
            let label = window_label(entry);
            if entry.folders.is_empty() {
                MenuItem::Label(label)
            } else {
                MenuItem::Action(MenuAction {
                    id: format!("focus:{}", entry.key),
                    label,
                    enabled: true,
                })
            }
        })
        .collect()
}

/// The tray label for one window: the **main repository** name, then live branch
/// state (`omni-dev · branch (+2 -1)`) when the primary folder is a git repo. A
/// linked worktree is set off with the [`WORKTREE_SEP`] fork glyph
/// (`omni-dev ⑂ branch`) so it reads distinctly from the main checkout; a folder
/// that is not a repo falls back to its reported title.
fn window_label(entry: &WindowEntry) -> String {
    let status = entry
        .folders
        .first()
        .map(|folder| git_status(folder))
        .unwrap_or_default();
    // Prefer the git-derived main repo so a linked worktree names its parent
    // repository rather than its worktree-folder basename.
    let name = status
        .main_repo
        .clone()
        .unwrap_or_else(|| display_name(entry));
    if let Some(branch) = &status.branch {
        let sep = if status.is_worktree {
            WORKTREE_SEP
        } else {
            REPO_SEP
        };
        return match sync_indicator(status.ahead, status.behind) {
            Some(sync) => format!("{name} {sep} {branch} {sync}"),
            None => format!("{name} {sep} {branch}"),
        };
    }
    // No git branch (not a repo / detached): fall back to the reported title.
    match &entry.title {
        Some(title) if title != &name => format!("{name} {REPO_SEP} {title}"),
        _ => name,
    }
}

/// A compact `(+ahead -behind)` divergence indicator, or `None` when the branch
/// has no upstream to compare against.
fn sync_indicator(ahead: Option<usize>, behind: Option<usize>) -> Option<String> {
    match (ahead, behind) {
        (Some(ahead), Some(behind)) => Some(format!("(+{ahead} -{behind})")),
        _ => None,
    }
}

/// Well-known absolute locations for the VS Code launcher, tried in order so a
/// daemon running under launchd (with a minimal `PATH`) still finds it.
const CODE_BINARY_CANDIDATES: &[&str] = &[
    "/usr/local/bin/code",
    "/opt/homebrew/bin/code",
    "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
    "/usr/bin/code",
];

/// Focuses (or opens, since VS Code reuses an already-open window) `folder` in
/// VS Code by spawning its CLI, resolved via [`resolve_code_binary`]. Shared
/// with the sessions service's tray "focus" action, which resolves a session to
/// its VS Code window folder and opens it through this same guarded launcher.
pub(crate) fn focus_window(folder: &Path) -> Result<()> {
    focus_window_with(&resolve_code_binary(), folder)
}

/// Spawns `program` on `folder` after validating the folder. Split out from
/// [`focus_window`] so the validation and spawn paths are testable with an
/// explicit launcher (no environment or installed-editor dependency).
///
/// Best-effort and non-blocking: the spawned child is reaped on a detached
/// thread so a long-lived daemon does not accumulate zombies one per focus.
fn focus_window_with(program: &Path, folder: &Path) -> Result<()> {
    // The tray path passes an absolute workspace folder, but the socket `open`
    // op (#1266) passes an arbitrary client-supplied path, so this guard is a
    // real check there, not just an assertion: requiring an absolute path also
    // rules out a `-`-leading path being parsed by `code` as a flag.
    if !folder.is_absolute() {
        bail!(
            "refusing to focus a non-absolute folder path: {}",
            folder.display()
        );
    }
    if !folder.is_dir() {
        bail!("worktree folder no longer exists: {}", folder.display());
    }
    // Detach the launcher's stdio so its output never interleaves into the
    // long-lived daemon's own stdout/stderr (or the test harness's).
    let child = Command::new(program)
        .arg(folder)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .with_context(|| {
            format!(
                "failed to launch `{}` to focus {}",
                program.display(),
                folder.display()
            )
        })?;
    // Reap the child without blocking so it never lingers as a zombie.
    std::thread::spawn(move || {
        let mut child = child;
        let _ = child.wait();
    });
    Ok(())
}

/// Resolves the VS Code launcher from the real environment: the
/// `OMNI_DEV_VSCODE_BIN` override, then [`CODE_BINARY_CANDIDATES`], then bare
/// `code` on `PATH`. The pure resolution logic lives in
/// [`resolve_code_binary_from`] for testing.
fn resolve_code_binary() -> PathBuf {
    resolve_code_binary_from(std::env::var_os(VSCODE_BIN_ENV), CODE_BINARY_CANDIDATES)
}

/// Pure launcher resolution: `env_override` wins; otherwise the first existing
/// `candidate`; otherwise bare `code`.
fn resolve_code_binary_from(
    env_override: Option<std::ffi::OsString>,
    candidates: &[&str],
) -> PathBuf {
    if let Some(path) = env_override {
        return PathBuf::from(path);
    }
    for candidate in candidates {
        let path = Path::new(candidate);
        if path.exists() {
            return path.to_path_buf();
        }
    }
    PathBuf::from("code")
}

// --- Close op (#1277) --------------------------------------------------------

/// The `close` op payload: close a worktree's window and (for a linked worktree)
/// delete it. Symmetric to `open`, but destructive, so it carries the
/// two-phase-confirm and self-close routing fields.
#[derive(Debug, Clone, Deserialize)]
struct CloseRequest {
    /// Absolute path of the target worktree's working directory.
    path: PathBuf,
    /// The requesting window's key, so a self-close (`requester_key` owns the
    /// target) removes-then-replies and lets the extension close its own window,
    /// rather than waiting on a window that is blocked awaiting this reply.
    #[serde(default)]
    requester_key: Option<String>,
    /// Whether to **delete** the worktree (linked "Close Worktree") rather than
    /// only close its window (main "Close Window"). A delete is refused on the
    /// main working tree regardless of this flag.
    #[serde(default)]
    remove: bool,
    /// Set on the phase-2 execute call. Absent/false with `remove:true` is the
    /// phase-1, side-effect-free safety check; ignored for `remove:false`.
    #[serde(default)]
    confirmed: bool,
}

/// One risk or informational note in a [`SafetyReport`]: a machine-readable
/// `kind` and a human-readable `detail`. Shared by both the blocking `risks`
/// (data would be lost) and the non-blocking `info` (context, e.g. unpushed
/// commits that survive because the branch is kept).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct Note {
    /// A stable machine slug for the condition (e.g. `dirty`, `untracked`).
    kind: String,
    /// A human-readable one-line explanation for the confirm dialog.
    detail: String,
}

impl Note {
    fn new(kind: &str, detail: impl Into<String>) -> Self {
        Self {
            kind: kind.to_string(),
            detail: detail.into(),
        }
    }
}

/// The phase-1 safety report the extension reads to decide whether to prompt.
/// `removable && risks.is_empty()` → proceed with **no** dialog; any `risks`
/// entry → show a modal confirm listing them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct SafetyReport {
    /// Whether the target is a deletable (linked) worktree at all — `false` for
    /// the main working tree, which the daemon never removes.
    removable: bool,
    /// Whether the target is the repository's main working tree.
    is_main: bool,
    /// Whether a live VS Code window currently has the target open.
    open: bool,
    /// The owning window's key, when `open` (the first, for the wait/close).
    #[serde(skip_serializing_if = "Option::is_none")]
    window_key: Option<String>,
    /// How many workspace folders the owning window has — so the extension can
    /// warn "this window has N folders open; all will close" (failure mode #10).
    window_folder_count: usize,
    /// Conditions that would lose data on removal; a non-empty list forces a
    /// confirm dialog.
    risks: Vec<Note>,
    /// Non-blocking context shown for awareness (e.g. unpushed commits that
    /// survive because the branch is kept).
    info: Vec<Note>,
}

/// The git-only half of the safety check, before the registry's open-window
/// facts are folded in. Pure disk I/O; computed on a blocking thread.
#[derive(Debug, Clone, PartialEq, Eq)]
struct GitSafety {
    is_main: bool,
    removable: bool,
    risks: Vec<Note>,
    info: Vec<Note>,
}

/// Live windows (key, workspace-folder count) that currently have `path` open,
/// matched by canonicalized path so a symlinked or `..`-laden report still
/// joins. Disk I/O (canonicalization), so it runs on a blocking thread.
fn windows_with_path(entries: &[WindowEntry], path: &Path) -> Vec<(String, usize)> {
    let target = canonical(path);
    entries
        .iter()
        .filter(|e| e.folders.iter().any(|f| canonical(f) == target))
        .map(|e| (e.key.clone(), e.folders.len()))
        .collect()
}

/// How long the execute phase waits for a signalled window to close
/// (`unregister`) before giving up. Deliberately generous against the ~10s
/// heartbeat interval the close directive rides — a window may have just
/// heartbeated, so the directive is only picked up on the *next* one — plus the
/// window's own close/save latency. The keyed-push responsiveness upgrade
/// (#1277 fast-follow) removes this wait entirely.
const CLOSE_WAIT_TIMEOUT: Duration = Duration::from_secs(20);

/// How often the execute phase re-checks whether the signalled windows have
/// unregistered.
const CLOSE_WAIT_POLL: Duration = Duration::from_millis(250);

/// Waits up to `timeout` for every window *other than* `requester` that has
/// `path` open to unregister (close), polling the live registry every `poll`.
/// A window whose `last_seen` has already gone stale is reaped by `list()` and
/// so counts as closed. Returns an error naming the still-open windows on
/// timeout, so the caller can surface "window did not close" and leave the
/// worktree untouched (failure modes #4/#5).
async fn await_windows_closed(
    registry: &WorktreesRegistry,
    path: &Path,
    requester: Option<&str>,
    timeout: Duration,
    poll: Duration,
) -> Result<()> {
    let deadline = std::time::Instant::now() + timeout;
    loop {
        // The registry read is cheap CPU, but the path canonicalization in
        // `windows_with_path` is disk I/O — do the whole check on a blocking
        // thread, never on the async worker.
        let entries = registry.list();
        let path = path.to_path_buf();
        let requester = requester.map(str::to_string);
        let remaining: Vec<String> = tokio::task::spawn_blocking(move || {
            windows_with_path(&entries, &path)
                .into_iter()
                .map(|(k, _)| k)
                .filter(|k| requester.as_deref() != Some(k))
                .collect()
        })
        .await
        .unwrap_or_default();

        if remaining.is_empty() {
            return Ok(());
        }
        if std::time::Instant::now() >= deadline {
            bail!("window(s) did not close in time: {}", remaining.join(", "));
        }
        tokio::time::sleep(poll).await;
    }
}

/// Computes the [`GitSafety`] of a worktree at `path`: whether it is the main
/// working tree (never removable) and, for a linked worktree, what a removal
/// would lose. Best-effort per-check but the overall open must succeed — a path
/// that is not a git worktree is a hard error (we refuse to delete an unknown
/// directory). A path that no longer exists is treated as an already-removed
/// linked worktree so the idempotent execute path can proceed with no dialog.
fn git_safety(path: &Path) -> Result<GitSafety> {
    if !path.exists() {
        return Ok(GitSafety {
            is_main: false,
            removable: true,
            risks: vec![],
            info: vec![Note::new("already-removed", "worktree no longer exists")],
        });
    }
    let repo = Repository::open(path)
        .with_context(|| format!("not a git worktree: {}", path.display()))?;
    // The one structural fact deletability keys off — never the branch name.
    if !repo.is_worktree() {
        return Ok(GitSafety {
            is_main: true,
            removable: false,
            risks: vec![],
            info: vec![Note::new(
                "main-working-tree",
                "the repository's main working tree is never deleted",
            )],
        });
    }

    let mut risks = Vec::new();
    let mut info = Vec::new();

    let (dirty, untracked) = count_dirty_untracked(&repo);
    if dirty > 0 {
        risks.push(Note::new(
            "dirty",
            format!("{dirty} modified tracked file(s) would be lost"),
        ));
    }
    if untracked > 0 {
        risks.push(Note::new(
            "untracked",
            format!("{untracked} untracked file(s) would be lost"),
        ));
    }

    // An in-progress rebase/merge/cherry-pick etc. is lost on removal.
    let state = repo.state();
    if state != RepositoryState::Clean {
        risks.push(Note::new(
            "in-progress",
            format!("an in-progress {state:?} operation would be lost"),
        ));
    }

    // Commits reachable only from a detached HEAD are GC'd once the worktree —
    // and its HEAD ref — are gone. A HEAD still reachable from any ref (a branch
    // or tag) loses nothing, so it is not flagged.
    if repo.head_detached().unwrap_or(false) {
        let lost = unreachable_commit_count(&repo).unwrap_or(0);
        if lost > 0 {
            risks.push(Note::new(
                "unreachable-commits",
                format!("{lost} commit(s) on a detached HEAD will be permanently lost"),
            ));
        }
    }

    // Unpushed commits on a *named* branch survive: removal never deletes the
    // branch. Informational only — it must not block or prompt.
    if let Some(ahead) = current_branch_ahead(&repo) {
        if ahead > 0 {
            info.push(Note::new(
                "unpushed",
                format!("{ahead} unpushed commit(s) on the branch (kept — the branch survives)"),
            ));
        }
    }

    Ok(GitSafety {
        is_main: false,
        removable: true,
        risks,
        info,
    })
}

/// Counts a worktree's `(dirty tracked, untracked)` files. Tracked covers any
/// staged or unstaged modification (including conflicts and deletions);
/// untracked is `WT_NEW`. `.gitignore`d files are excluded — they are
/// regenerable and must not force a prompt — via `include_ignored(false)`, so no
/// status entry ever carries the `IGNORED` bit. A failed status read degrades to
/// `(0, 0)` rather than sinking the whole safety check.
fn count_dirty_untracked(repo: &Repository) -> (usize, usize) {
    let mut opts = StatusOptions::new();
    opts.include_untracked(true)
        .recurse_untracked_dirs(true)
        .include_ignored(false)
        .exclude_submodules(true);
    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
        return (0, 0);
    };
    // Any staged or unstaged change to a tracked path (WT_NEW is untracked, so
    // it is deliberately excluded from this mask).
    let tracked = Status::INDEX_NEW
        | Status::INDEX_MODIFIED
        | Status::INDEX_DELETED
        | Status::INDEX_RENAMED
        | Status::INDEX_TYPECHANGE
        | Status::WT_MODIFIED
        | Status::WT_DELETED
        | Status::WT_TYPECHANGE
        | Status::WT_RENAMED
        | Status::CONFLICTED;
    let mut dirty = 0;
    let mut untracked = 0;
    for entry in statuses.iter() {
        let s = entry.status();
        if s.contains(Status::WT_NEW) {
            untracked += 1;
        }
        if s.intersects(tracked) {
            dirty += 1;
        }
    }
    (dirty, untracked)
}

/// Counts commits reachable from the (detached) HEAD but from no other ref —
/// the commits git would garbage-collect once the worktree's HEAD is gone.
/// `None` if HEAD or the revwalk cannot be resolved. The literal `HEAD` ref is
/// skipped (hiding it would hide the very commits we are counting); every real
/// branch/tag/remote ref is hidden, so a tip that any branch also points at
/// yields `0` (nothing is actually lost).
fn unreachable_commit_count(repo: &Repository) -> Option<usize> {
    let head_oid = repo.head().ok()?.target()?;
    let mut walk = repo.revwalk().ok()?;
    walk.push(head_oid).ok()?;
    for reference in repo.references().ok()? {
        let Ok(reference) = reference else { continue };
        // Skip the literal HEAD ref — hiding it would hide the very commits we
        // are counting; every real branch/tag/remote ref is hidden below.
        if matches!(reference.name(), Ok("HEAD")) {
            continue;
        }
        if let Some(oid) = reference.target() {
            let _ = walk.hide(oid);
        }
    }
    Some(walk.flatten().count())
}

/// Commits the worktree's current branch is ahead of its upstream, or `None`
/// when HEAD is detached or the branch tracks no upstream. Reuses
/// [`upstream_ahead_behind`]; only the ahead count matters here (unpushed work).
fn current_branch_ahead(repo: &Repository) -> Option<usize> {
    let head = repo.head().ok()?;
    if !head.is_branch() {
        return None;
    }
    let branch = git2::Branch::wrap(head);
    upstream_ahead_behind(repo, &branch).map(|(ahead, _behind)| ahead)
}

/// Resolves the linked worktree whose working directory canonicalizes to
/// `target` to its registered name in `main_repo`. Errors when `target` is not
/// one of the repo's worktrees — the defensive guard against removing a path
/// that opened as a worktree but is not enumerated. Split out so that guard is
/// unit-testable without corrupting git's worktree admin state.
fn worktree_name_for_path(main_repo: &Repository, target: &Path) -> Result<String> {
    let names = main_repo.worktrees()?;
    names
        .iter()
        .flatten() // Result<Option<&str>, _> → Option<&str> (drop per-name errors)
        .flatten() // Option<&str> → &str (drop non-UTF-8 names)
        .find(|name| {
            main_repo
                .find_worktree(name)
                .is_ok_and(|wt| canonical(wt.path()) == target)
        })
        .map(str::to_string)
        .ok_or_else(|| {
            anyhow!(
                "worktree {} is not registered in {}",
                target.display(),
                main_repo.path().display()
            )
        })
}

/// Backoff delays between recursive-removal retries (#1315). A concurrent
/// writer — a just-closed window's language server (Metals/Bloop) or
/// `rust-analyzer`/`cargo` still flushing build artifacts into `target/` — can
/// create a file between our directory scan and its `rmdir`, making the removal
/// fail with `ENOTEMPTY` ("Directory not empty"). Each retry re-sweeps and
/// waits longer, giving the winding-down process time to quiesce. Total wait
/// ~2.75s across four retries; the window teardown the caller already waited on
/// dominates it.
const WORKTREE_RMDIR_BACKOFF: &[Duration] = &[
    Duration::from_millis(250),
    Duration::from_millis(500),
    Duration::from_secs(1),
    Duration::from_secs(1),
];

/// Whether `e` is the transient "directory re-populated under us" race we retry
/// (see [`WORKTREE_RMDIR_BACKOFF`]) rather than a hard failure (permission
/// denied, read-only filesystem) we must surface immediately. Matches the raw
/// errno — `std::io::ErrorKind::DirectoryNotEmpty` is only stable from Rust 1.83,
/// past our MSRV — including the `EEXIST`/`EBUSY` siblings libgit2 lumps in.
fn is_transient_rmdir_error(e: &std::io::Error) -> bool {
    matches!(
        e.raw_os_error(),
        Some(nix::libc::ENOTEMPTY | nix::libc::EEXIST | nix::libc::EBUSY)
    )
}

/// Recursively removes `dir`, retrying on the transient concurrent-writer race
/// (see [`is_transient_rmdir_error`]) and treating an already-absent directory
/// as success. Non-transient errors surface immediately with the original
/// message. Runs on a blocking thread (called only from [`remove_worktree`], via
/// `spawn_blocking`), so the between-retry `sleep` is fine.
fn remove_dir_all_retrying(dir: &Path) -> Result<()> {
    remove_dir_all_retrying_with(dir, WORKTREE_RMDIR_BACKOFF, || std::fs::remove_dir_all(dir))
}

/// [`remove_dir_all_retrying`] with the schedule and the removal itself injected.
/// Provoking the real race requires a concurrent writer to lose a timing window,
/// so only an injected sequence of errors can drive every branch of the loop —
/// exhausting the backoff especially — deterministically and without sleeping out
/// the production schedule.
fn remove_dir_all_retrying_with(
    dir: &Path,
    backoff: &[Duration],
    mut remove: impl FnMut() -> std::io::Result<()>,
) -> Result<()> {
    let mut backoff = backoff.iter();
    loop {
        match remove() {
            Ok(()) => return Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => {
                if is_transient_rmdir_error(&e) {
                    if let Some(delay) = backoff.next() {
                        std::thread::sleep(*delay);
                        continue;
                    }
                }
                return Err(e).with_context(|| {
                    format!("failed to remove worktree directory {}", dir.display())
                });
            }
        }
    }
}

/// Whether `path` is a **half-removed** linked worktree: its `.git` gitlink
/// still points at an admin directory a prior failed removal already deleted.
/// libgit2's combined prune deletes the admin metadata *before* it rmdirs the
/// working tree, so a working-tree rmdir failure (#1315) leaves exactly this
/// orphan — the directory on disk with a dangling gitlink, no longer tracked by
/// git. Safe to delete outright: a live worktree's gitlink resolves (its repo
/// opens) and a normal checkout has a `.git` *directory*, so this matches
/// neither.
fn is_orphaned_worktree(path: &Path) -> bool {
    // `read_to_string` fails on a `.git` directory (a normal checkout), so only
    // a linked worktree's gitlink file gets past here.
    let Ok(contents) = std::fs::read_to_string(path.join(".git")) else {
        return false;
    };
    let Some(admin) = contents.strip_prefix("gitdir:").map(str::trim) else {
        return false;
    };
    let admin = Path::new(admin);
    // A linked-worktree admin path (`…/worktrees/<name>`) whose target is gone.
    admin.components().any(|c| c.as_os_str() == "worktrees") && !admin.exists()
}

/// Removes a **linked** worktree at `path` via `git2` (no shell — avoiding the
/// daemon-`PATH` problem the launcher fights): deletes both the checked-out
/// directory and the admin metadata. Refuses the main working tree (the
/// defensive backstop behind the UI gating) and a locked worktree (surfacing
/// "unlock first" rather than forcing past the lock). Idempotent: an
/// already-removed path is a success.
///
/// The working tree is removed **first** (retrying to absorb the
/// concurrent-writer race, #1315), and only then is the admin metadata pruned.
/// This is deliberately the reverse of libgit2's combined
/// `prune(working_tree: true)`, which deletes the admin dir first and, when the
/// working-tree rmdir then fails, leaves a **half-removed orphan** git no longer
/// tracks (and which a naive prune-retry cannot recover, since its admin gitdir
/// is already gone). Doing the directory first means a transient failure leaves
/// the worktree fully tracked and cleanly retryable; a pre-existing orphan from
/// the old ordering is detected and its leftover directory cleaned up directly.
fn remove_worktree(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let repo = match Repository::open(path) {
        Ok(repo) => repo,
        // Admin metadata already gone (a prior failed removal); git no longer
        // tracks this path, so no prune applies — just delete the leftover.
        Err(_) if is_orphaned_worktree(path) => return remove_dir_all_retrying(path),
        Err(e) => return Err(e).context(format!("not a git worktree: {}", path.display())),
    };
    if !repo.is_worktree() {
        bail!(
            "refusing to delete the main working tree: {}",
            path.display()
        );
    }
    // The Worktree handle lives on the *main* repo (the common dir's parent),
    // keyed by name; find it by matching the target path.
    let commondir = canonical(repo.commondir());
    let main_root = commondir
        .parent()
        .ok_or_else(|| anyhow!("no repository root for {}", path.display()))?
        .to_path_buf();
    // Drop the worktree-scoped handle before we delete its directory.
    drop(repo);
    let main_repo = Repository::open(&main_root)
        .with_context(|| format!("failed to open repository at {}", main_root.display()))?;
    let name = worktree_name_for_path(&main_repo, &canonical(path))?;
    let worktree = main_repo.find_worktree(&name)?;

    // Never silently force past a lock (failure mode #6).
    if let WorktreeLockStatus::Locked(reason) = worktree.is_locked()? {
        let because = reason.map(|r| format!(" ({r})")).unwrap_or_default();
        bail!("worktree is locked{because}; unlock it first (git worktree unlock)");
    }

    // Delete the checked-out directory ourselves, retrying past the
    // concurrent-writer race (#1315).
    remove_dir_all_retrying(path)?;

    // The directory is gone; prune only the admin metadata. working_tree(false)
    // keeps git2 from re-attempting (and failing on) the now-absent directory;
    // valid(true) prunes even though the worktree was valid; locked stays false,
    // so a lock (re-checked above) is never forced.
    let mut opts = git2::WorktreePruneOptions::new();
    opts.valid(true).working_tree(false);
    worktree
        .prune(Some(&mut opts))
        .with_context(|| format!("failed to prune worktree metadata for {}", path.display()))?;
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::test_support::shim::{shim_lock, write_exec_script};
    use std::sync::MutexGuard;

    fn register_payload(key: &str, repo: Option<&str>, folder: &str) -> Value {
        json!({
            "key": key,
            "folders": [folder],
            "repo": repo,
            "title": format!("{key}-title"),
            "pid": 1234,
        })
    }

    /// Pulls the `windows` array out of a `list`/`status` payload.
    fn windows_of(payload: &Value) -> &Vec<Value> {
        payload
            .get("windows")
            .and_then(Value::as_array)
            .expect("windows array")
    }

    #[tokio::test]
    async fn name_and_unknown_op() {
        let svc = WorktreesService::new();
        assert_eq!(svc.name(), "worktrees");
        assert!(svc.handle("frobnicate", Value::Null).await.is_err());
    }

    #[tokio::test]
    async fn handle_routes_ops_and_shapes_payloads() {
        let svc = WorktreesService::new();
        // Empty to start.
        let payload = svc.handle("list", Value::Null).await.unwrap();
        assert_eq!(payload, json!({ "windows": [] }));

        // register → { ok: true }, then it shows up in list.
        let reply = svc
            .handle("register", register_payload("w1", Some("repo-a"), "/tmp/a"))
            .await
            .unwrap();
        assert_eq!(reply, json!({ "ok": true }));
        let windows = windows_of(&svc.handle("list", Value::Null).await.unwrap()).clone();
        assert_eq!(windows.len(), 1);
        assert_eq!(windows[0].get("key").and_then(Value::as_str), Some("w1"));
        assert!(windows[0].get("last_seen").is_some());

        // heartbeat known/unknown.
        let known = svc
            .handle("heartbeat", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(known, json!({ "known": true }));
        let unknown = svc
            .handle("heartbeat", json!({ "key": "nope" }))
            .await
            .unwrap();
        assert_eq!(unknown, json!({ "known": false }));

        // unregister removes, then repeats as a no-op success.
        let gone = svc
            .handle("unregister", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(gone, json!({ "removed": true }));
        let again = svc
            .handle("unregister", json!({ "key": "w1" }))
            .await
            .unwrap();
        assert_eq!(again, json!({ "removed": false }));
    }

    #[tokio::test]
    async fn handle_rejects_missing_or_empty_key() {
        let svc = WorktreesService::new();
        // register validates a present, non-blank key.
        assert!(svc.handle("register", json!({})).await.is_err());
        assert!(svc
            .handle("register", json!({ "key": "  " }))
            .await
            .is_err());
        // heartbeat/unregister require the key via `require_str`.
        assert!(svc.handle("heartbeat", json!({})).await.is_err());
        assert!(svc.handle("unregister", json!({})).await.is_err());
    }

    #[test]
    fn display_name_prefers_repo_then_folder_basename() {
        let base = WindowEntry {
            key: "k".to_string(),
            folders: vec![PathBuf::from("/home/me/project")],
            repo: Some("my-repo".to_string()),
            title: None,
            pid: None,
            last_seen: Utc::now(),
        };
        assert_eq!(display_name(&base), "my-repo");

        let no_repo = WindowEntry {
            repo: None,
            ..base.clone()
        };
        assert_eq!(display_name(&no_repo), "project");

        let nothing = WindowEntry {
            repo: None,
            folders: vec![],
            ..base.clone()
        };
        assert_eq!(display_name(&nothing), "(no folder)");

        // A folder with no basename (the filesystem root) falls back to its
        // displayed path rather than panicking or yielding an empty name.
        let rootish = WindowEntry {
            repo: None,
            folders: vec![PathBuf::from("/")],
            ..base
        };
        assert_eq!(display_name(&rootish), "/");
    }

    #[test]
    fn window_menu_items_merge_stats_and_focus_into_one_clickable_line() {
        let now = Utc::now();
        let entries = vec![
            // A folderless window has nothing to focus, so it stays a plain
            // Label; a title equal to the name collapses to just the name. It
            // leads the list so the focus-action lookup below is exercised
            // against a leading non-Action item it has to skip.
            WindowEntry {
                key: "k2".to_string(),
                folders: vec![],
                repo: Some("solo".to_string()),
                title: Some("solo".to_string()),
                pid: None,
                last_seen: now,
            },
            // A folder-bearing, non-repo window: one clickable Action whose label
            // is the stats line ("name · title", since /tmp is not a git repo).
            WindowEntry {
                key: "k1".to_string(),
                folders: vec![PathBuf::from("/tmp/a")],
                repo: Some("repo".to_string()),
                title: Some("a branch".to_string()),
                pid: None,
                last_seen: now,
            },
        ];
        let items = window_menu_items(&entries);
        // Exactly one item per window — no duplicate label, no separator.
        assert_eq!(items.len(), 2);
        assert!(!items.iter().any(|i| matches!(i, MenuItem::Separator)));

        // The folder-bearing window is a single clickable action carrying the
        // stats label (the old label + Focus action, merged).
        let action = items
            .iter()
            .find_map(|i| match i {
                MenuItem::Action(a) => Some(a),
                _ => None,
            })
            .expect("a focus action");
        assert_eq!(action.id, "focus:k1");
        assert_eq!(action.label, "repo · a branch");

        // The folderless window is a non-clickable label (not "solo · solo").
        let labels: Vec<&str> = items
            .iter()
            .filter_map(|i| match i {
                MenuItem::Label(t) => Some(t.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(labels, vec!["solo"]);
    }

    #[tokio::test]
    async fn menu_and_status_shapes() {
        let svc = WorktreesService::new();
        // Empty.
        let menu = svc.menu();
        assert_eq!(menu.title, "Worktrees");
        assert!(matches!(
            menu.items.first(),
            Some(MenuItem::Label(text)) if text == "No open windows"
        ));
        let status = svc.status().await;
        assert_eq!(status.name, "worktrees");
        assert!(status.healthy);
        assert_eq!(status.summary, "0 window(s) across 0 repo(s)");

        // Two folder-bearing windows in the same repo, plus one folderless
        // window that shares the repo but has nothing for `code` to open.
        svc.handle("register", register_payload("w1", Some("repo-a"), "/tmp/a"))
            .await
            .unwrap();
        svc.handle("register", register_payload("w2", Some("repo-a"), "/tmp/b"))
            .await
            .unwrap();
        svc.handle(
            "register",
            json!({ "key": "w3", "repo": "repo-a", "folders": [] }),
        )
        .await
        .unwrap();
        let status = svc.status().await;
        assert_eq!(status.summary, "3 window(s) across 1 repo(s)");

        let menu = svc.menu();
        // One line per window — no separator, no duplicate label.
        assert_eq!(menu.items.len(), 3);
        assert!(!menu.items.iter().any(|i| matches!(i, MenuItem::Separator)));
        let action_ids: Vec<&str> = menu
            .items
            .iter()
            .filter_map(|i| match i {
                MenuItem::Action(a) => Some(a.id.as_str()),
                _ => None,
            })
            .collect();
        // The two folder-bearing windows are clickable; the folderless one is a
        // plain Label, so it never yields a focus action.
        assert!(action_ids.contains(&"focus:w1"));
        assert!(action_ids.contains(&"focus:w2"));
        assert!(!action_ids.contains(&"focus:w3"));
    }

    #[test]
    fn start_menu_refresh_is_a_noop_outside_a_runtime() {
        // With no tokio runtime, the background task is never spawned, so the
        // bare service keeps computing `menu()` inline (what the tests rely on).
        let svc = WorktreesService::new();
        svc.start_menu_refresh();
        assert!(svc.refresh.lock().unwrap().is_none());
    }

    #[tokio::test]
    async fn start_menu_refresh_populates_cache_and_shutdown_stops_it() {
        let svc = WorktreesService::new();
        svc.handle("register", register_payload("w1", Some("repo-a"), "/tmp/a"))
            .await
            .unwrap();
        // Before the task runs, `menu()` computes inline from an empty cache.
        assert!(svc.menu_cache.lock().unwrap().is_none());

        svc.start_menu_refresh();
        // Idempotent: a second call does not start a second task.
        svc.start_menu_refresh();

        // The task fills the cache off the main thread; poll briefly for it.
        let mut filled = false;
        for _ in 0..100 {
            if svc.menu_cache.lock().unwrap().is_some() {
                filled = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(filled, "background refresh should populate the menu cache");

        // `menu()` now serves the cache: one clickable line for the window.
        let menu = svc.menu();
        assert_eq!(menu.title, "Worktrees");
        assert!(menu
            .items
            .iter()
            .any(|i| matches!(i, MenuItem::Action(a) if a.id == "focus:w1")));

        // Shutdown cancels and joins the task, clearing the handle.
        svc.shutdown().await;
        assert!(svc.refresh.lock().unwrap().is_none());
    }

    #[tokio::test]
    async fn default_constructs_an_empty_service() {
        let svc = WorktreesService::default();
        let payload = svc.handle("list", Value::Null).await.unwrap();
        assert_eq!(payload, json!({ "windows": [] }));
    }

    // --- Push subscription (#1267) -----------------------------------------

    #[tokio::test]
    async fn subscribe_streams_only_for_the_subscribe_op() {
        let svc = WorktreesService::new();
        // The one streaming op yields a stream; every other op (including the
        // request/reply worktrees ops) declines, so the server dispatches them
        // normally.
        assert!(svc.subscribe("subscribe", &Value::Null).is_some());
        assert!(svc.subscribe("list", &Value::Null).is_none());
        assert!(svc.subscribe("register", &Value::Null).is_none());
        assert!(svc.subscribe("bogus", &Value::Null).is_none());
    }

    #[tokio::test]
    async fn subscribe_snapshot_matches_the_tree_op() {
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();

        let svc = WorktreesService::new();
        let stream = svc
            .subscribe("subscribe", &Value::Null)
            .expect("subscribe stream");
        // No windows yet → no repos derived; the toggle rides along at its
        // default (show all).
        assert_eq!(
            stream.snapshot().await,
            json!({ "repos": [], "show_closed": true })
        );

        // A window opens on the repo → the snapshot carries it, byte-identical to
        // what the `tree` op returns for the same registry state.
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [dir.path()], "repo": "r" }),
        )
        .await
        .unwrap();
        let snap = stream.snapshot().await;
        let tree = svc.handle("tree", Value::Null).await.unwrap();
        assert_eq!(snap, tree);
        let repos = snap["repos"].as_array().expect("repos array");
        assert_eq!(repos.len(), 1);
        assert_eq!(repos[0]["worktrees"][0]["branch"], json!("main"));
    }

    #[tokio::test]
    async fn subscribe_changed_wakes_on_register() {
        let svc = WorktreesService::new();
        let mut stream = svc
            .subscribe("subscribe", &Value::Null)
            .expect("subscribe stream");
        // Idle: `changed()` must not resolve without a registry change.
        tokio::select! {
            () = stream.changed() => panic!("changed resolved with no registry change"),
            () = tokio::time::sleep(Duration::from_millis(50)) => {}
        }
        // A register bumps the change-notify → `changed()` resolves promptly.
        svc.handle("register", register_payload("w1", Some("r"), "/tmp/a"))
            .await
            .unwrap();
        tokio::time::timeout(Duration::from_secs(1), stream.changed())
            .await
            .expect("changed should resolve after a register");
    }

    // --- Coalesced tree-snapshot cache (#1303) -----------------------------

    #[tokio::test]
    async fn tree_cache_coalesces_reads_within_ttl_and_generation() {
        let reg = Arc::new(WorktreesRegistry::new());
        // A long TTL so only the generation gate is exercised here.
        let cache = TreeSnapshotCache::with_ttl(
            reg,
            Arc::new(PrStatusCache::new()),
            Duration::from_secs(60),
        );
        // The first read builds once.
        let first = cache.snapshot().await;
        assert_eq!(cache.compute_count(), 1);
        // Further reads with no registry change and within the TTL reuse the
        // cached value — no extra build, byte-identical result.
        let second = cache.snapshot().await;
        assert_eq!(
            cache.compute_count(),
            1,
            "an unchanged read must not rebuild"
        );
        assert_eq!(first, second);
    }

    #[tokio::test]
    async fn tree_cache_single_flights_a_read_burst() {
        let reg = Arc::new(WorktreesRegistry::new());
        let cache = Arc::new(TreeSnapshotCache::with_ttl(
            reg,
            Arc::new(PrStatusCache::new()),
            Duration::from_secs(60),
        ));
        // A burst of concurrent readers — as N subscriber streams would wake
        // together on a change/tick — collapses to exactly one build; the rest
        // read the shared result (the acceptance criterion).
        let mut handles = Vec::new();
        for _ in 0..16 {
            let cache = cache.clone();
            handles.push(tokio::spawn(async move { cache.snapshot().await }));
        }
        let mut results = Vec::new();
        for handle in handles {
            results.push(handle.await.unwrap());
        }
        assert_eq!(
            cache.compute_count(),
            1,
            "a concurrent read burst must build the tree once"
        );
        assert!(
            results.windows(2).all(|w| w[0] == w[1]),
            "every reader must observe the identical snapshot"
        );
    }

    #[tokio::test]
    async fn tree_cache_rebuilds_on_registry_change() {
        let reg = Arc::new(WorktreesRegistry::new());
        let cache = TreeSnapshotCache::with_ttl(
            reg.clone(),
            Arc::new(PrStatusCache::new()),
            Duration::from_secs(60),
        );
        cache.snapshot().await;
        assert_eq!(cache.compute_count(), 1);
        // A registry change bumps the generation, so the next read rebuilds even
        // though the (long) TTL has not expired — subscribers never see a stale
        // visible set.
        assert!(reg.set_show_closed(false));
        cache.snapshot().await;
        assert_eq!(
            cache.compute_count(),
            2,
            "a generation bump must force a rebuild"
        );
    }

    #[tokio::test]
    async fn tree_cache_rebuilds_after_ttl_expiry() {
        let reg = Arc::new(WorktreesRegistry::new());
        // A zero TTL: every read is already past it, so a pure on-disk git change
        // still surfaces on the next tick with no registry bump needed.
        let cache =
            TreeSnapshotCache::with_ttl(reg, Arc::new(PrStatusCache::new()), Duration::ZERO);
        cache.snapshot().await;
        cache.snapshot().await;
        assert_eq!(
            cache.compute_count(),
            2,
            "an expired TTL must force a rebuild each read"
        );
    }

    #[tokio::test]
    async fn subscribe_streams_share_one_build_per_generation() {
        let svc = WorktreesService::new();
        let s1 = svc
            .subscribe("subscribe", &Value::Null)
            .expect("subscribe stream");
        let s2 = svc
            .subscribe("subscribe", &Value::Null)
            .expect("subscribe stream");
        // Two windows' streams sampling the same registry state build the tree
        // once, not once per stream (#1303) — they share the service's cache.
        let a = s1.snapshot().await;
        let b = s2.snapshot().await;
        assert_eq!(a, b);
        assert_eq!(
            svc.tree_cache.compute_count(),
            1,
            "N streams on one generation must share a single build"
        );
    }

    // --- Show/hide-closed toggle (#1301) -----------------------------------

    #[tokio::test]
    async fn set_show_closed_toggles_the_snapshot_field() {
        let svc = WorktreesService::new();
        // The snapshot carries the toggle; it defaults to show-all.
        assert_eq!(
            svc.handle("tree", Value::Null).await.unwrap()["show_closed"],
            json!(true)
        );
        // Setting it flips the field the next snapshot reports.
        let reply = svc
            .handle("set-show-closed", json!({ "show_closed": false }))
            .await
            .unwrap();
        assert_eq!(reply, json!({ "ok": true }));
        assert_eq!(
            svc.handle("tree", Value::Null).await.unwrap()["show_closed"],
            json!(false)
        );
    }

    #[tokio::test]
    async fn set_show_closed_rejects_a_non_boolean_payload() {
        let svc = WorktreesService::new();
        assert!(svc.handle("set-show-closed", json!({})).await.is_err());
        assert!(svc
            .handle("set-show-closed", json!({ "show_closed": "yes" }))
            .await
            .is_err());
    }

    #[tokio::test]
    async fn set_show_closed_wakes_the_subscription() {
        let svc = WorktreesService::new();
        let mut stream = svc
            .subscribe("subscribe", &Value::Null)
            .expect("subscribe stream");
        // A real flip bumps the change-notify → `changed()` resolves promptly.
        svc.handle("set-show-closed", json!({ "show_closed": false }))
            .await
            .unwrap();
        tokio::time::timeout(Duration::from_secs(1), stream.changed())
            .await
            .expect("changed should resolve after a toggle flip");
        // The pushed snapshot now reflects the new toggle.
        assert_eq!(stream.snapshot().await["show_closed"], json!(false));
    }

    #[tokio::test]
    async fn set_polling_toggles_the_snapshot_field_for_a_repo() {
        // #1376: enabling stamps `polling_enabled: true` on the repo; disabling
        // drops it (skip-if-false), so the extension colours the icon off the flag.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();

        let repo = repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0].clone();
        assert!(
            repo.get("polling_enabled").is_none(),
            "default off omits the flag: {repo:?}"
        );

        let reply = svc
            .handle(
                "set-polling",
                json!({ "owner": "rust-works", "name": "omni-dev", "enabled": true }),
            )
            .await
            .unwrap();
        assert_eq!(reply, json!({ "ok": true }));
        let repo = repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0].clone();
        assert_eq!(repo["polling_enabled"], json!(true));

        svc.handle(
            "set-polling",
            json!({ "owner": "rust-works", "name": "omni-dev", "enabled": false }),
        )
        .await
        .unwrap();
        let repo = repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0].clone();
        assert!(repo.get("polling_enabled").is_none());
    }

    #[tokio::test]
    async fn set_polling_rejects_missing_or_empty_fields() {
        let svc = WorktreesService::new();
        // Missing `enabled`.
        assert!(svc
            .handle("set-polling", json!({ "owner": "o", "name": "n" }))
            .await
            .is_err());
        // Missing `owner`/`name`.
        assert!(svc
            .handle("set-polling", json!({ "enabled": true }))
            .await
            .is_err());
        // Blank `owner`/`name`.
        assert!(svc
            .handle(
                "set-polling",
                json!({ "owner": " ", "name": "n", "enabled": true })
            )
            .await
            .is_err());
    }

    #[tokio::test]
    async fn set_polling_wakes_the_subscription() {
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        let mut stream = svc
            .subscribe("subscribe", &Value::Null)
            .expect("subscribe stream");
        svc.handle(
            "set-polling",
            json!({ "owner": "rust-works", "name": "omni-dev", "enabled": true }),
        )
        .await
        .unwrap();
        tokio::time::timeout(Duration::from_secs(1), stream.changed())
            .await
            .expect("changed should resolve after enabling a repo");
        let repo = repos_of(&stream.snapshot().await)[0].clone();
        assert_eq!(repo["polling_enabled"], json!(true));
    }

    #[tokio::test]
    async fn disabling_a_repo_drops_its_pr_badges_immediately() {
        // The "drop existing badges immediately" requirement (#1376), done
        // daemon-side: the fold skips a not-polled repo, so a disable strips the
        // badge on the very next snapshot rather than waiting for a poll.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let head = repo.head().unwrap().target().unwrap().to_string();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        svc.registry.set_polling("rust-works", "omni-dev", true);

        let mut badges = HashMap::new();
        badges.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            pr(pending_badge(7, &head)),
        );
        svc.pr_cache.replace(badges);

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr"]["number"], json!(7));

        svc.handle(
            "set-polling",
            json!({ "owner": "rust-works", "name": "omni-dev", "enabled": false }),
        )
        .await
        .unwrap();
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert!(
            wt.get("pr").is_none(),
            "a disabled repo must carry no badge: {wt:?}"
        );
    }

    #[tokio::test]
    async fn an_expired_lease_drops_the_flag_and_badges() {
        // The 15-minute auto-expire (#1376) seen end-to-end: once a repo's lease
        // elapses, the snapshot drops `polling_enabled` *and* the badge, and the
        // poller would no longer watch it — all reaped on read, no timer.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let head = repo.head().unwrap().target().unwrap().to_string();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        svc.registry.set_polling("rust-works", "omni-dev", true);
        let mut badges = HashMap::new();
        badges.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            pr(pending_badge(7, &head)),
        );
        svc.pr_cache.replace(badges);

        // Leased: flag stamped, badge folded, and the poller would watch it.
        let snap = svc.handle("tree", Value::Null).await.unwrap();
        assert_eq!(repos_of(&snap)[0]["polling_enabled"], json!(true));
        assert_eq!(repos_of(&snap)[0]["worktrees"][0]["pr"]["number"], json!(7));
        assert_eq!(pr_targets_from_snapshot(&snap).len(), 1);

        // Force the lease into the past — as 15 minutes elapsing would.
        svc.registry.set_polling_expiry(
            "rust-works",
            "omni-dev",
            Utc::now() - chrono::Duration::minutes(1),
        );

        let snap = svc.handle("tree", Value::Null).await.unwrap();
        let repo0 = &repos_of(&snap)[0];
        assert!(
            repo0.get("polling_enabled").is_none(),
            "expired lease drops the flag: {repo0:?}"
        );
        assert!(
            repo0["worktrees"][0].get("pr").is_none(),
            "expired lease drops the badge"
        );
        assert!(
            pr_targets_from_snapshot(&snap).is_empty(),
            "the poller no longer watches an expired repo"
        );
    }

    #[tokio::test]
    async fn polling_prefs_persist_across_reloads_with_0600() {
        // The enable set survives a daemon restart (#1376): a change writes the
        // `0600` file, and a fresh service seeded from it comes up enabled.
        let dir = tempfile::tempdir().unwrap();
        let prefs = dir.path().join("worktrees-polling.json");

        let svc = WorktreesService::new();
        svc.load_polling_prefs(prefs.clone());
        assert!(!svc.registry.is_polling_enabled("rust-works", "omni-dev"));
        svc.handle(
            "set-polling",
            json!({ "owner": "rust-works", "name": "omni-dev", "enabled": true }),
        )
        .await
        .unwrap();
        assert!(prefs.exists());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                std::fs::metadata(&prefs).unwrap().permissions().mode() & 0o777,
                0o600
            );
        }

        // A new service reloads the enabled set from that file.
        let svc2 = WorktreesService::new();
        svc2.load_polling_prefs(prefs.clone());
        assert!(svc2.registry.is_polling_enabled("rust-works", "omni-dev"));

        // Disabling rewrites the file, so the next reload has nothing enabled.
        svc2.handle(
            "set-polling",
            json!({ "owner": "rust-works", "name": "omni-dev", "enabled": false }),
        )
        .await
        .unwrap();
        let svc3 = WorktreesService::new();
        svc3.load_polling_prefs(prefs);
        assert!(!svc3.registry.is_polling_enabled("rust-works", "omni-dev"));
    }

    #[test]
    fn load_polling_prefs_tolerates_a_corrupt_or_unreadable_file() {
        // Best-effort load (#1376): a hand-edited/corrupt file or an unreadable
        // path is logged and treated as "nothing enabled" rather than wedging the
        // service. A missing file is already the first-run default (covered by the
        // persistence round-trip above); this exercises the two error branches.
        let dir = tempfile::tempdir().unwrap();

        // Corrupt JSON — the parse error is swallowed, nothing is enabled.
        let corrupt = dir.path().join("worktrees-polling.json");
        std::fs::write(&corrupt, b"{ not valid json ]").unwrap();
        let svc = WorktreesService::new();
        svc.load_polling_prefs(corrupt);
        assert!(svc.registry.enabled_polling_repos().is_empty());

        // A directory at the path — the (non-NotFound) read error is swallowed too.
        let as_dir = dir.path().join("is-a-directory");
        std::fs::create_dir(&as_dir).unwrap();
        let svc2 = WorktreesService::new();
        svc2.load_polling_prefs(as_dir);
        assert!(svc2.registry.enabled_polling_repos().is_empty());
    }

    #[tokio::test]
    async fn pr_poller_asks_nothing_for_a_registered_but_not_enabled_repo() {
        // The zero-`gh` guarantee (#1376): a window is open on a GitHub repo, but
        // the user has not enabled polling for it — so the poller spawns no `gh`.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let marker = bin_dir.path().join("spawned");
        let fake = bin_dir.path().join("fake-gh");
        std::fs::write(
            &fake,
            format!("#!/bin/sh\ntouch '{}'\necho '{{}}'\n", marker.display()),
        )
        .unwrap();
        let mut perms = std::fs::metadata(&fake).unwrap().permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
        std::fs::set_permissions(&fake, perms).unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Deliberately NOT enabling polling for the repo.
        svc.start_pr_poller_with(Duration::from_millis(20), Duration::from_millis(10), fake);
        tokio::time::sleep(Duration::from_millis(200)).await;
        svc.shutdown().await;
        assert!(
            !marker.exists(),
            "a registered-but-not-enabled repo must drive zero gh"
        );
    }

    #[tokio::test]
    async fn menu_action_rejects_unknown_and_missing_window() {
        let svc = WorktreesService::new();
        assert!(svc.menu_action("bogus").await.is_err());
        // A focus for a key with no registration errors rather than spawning.
        assert!(svc.menu_action("focus:nope").await.is_err());
        svc.shutdown().await;
    }

    /// Restores `OMNI_DEV_VSCODE_BIN` on drop. The two spawn tests that read the
    /// variable (via `resolve_code_binary` → `focus_window`) —
    /// `menu_action_focus_resolves_folder_and_spawns` and
    /// `open_focuses_an_existing_absolute_dir` — both point the launcher at the
    /// same harmless `/bin/sh`, and no test asserts the variable is *unset*, so a
    /// transient overlap under the harness's test parallelism is benign.
    struct VscodeBinGuard(Option<std::ffi::OsString>);
    impl Drop for VscodeBinGuard {
        fn drop(&mut self) {
            match self.0.take() {
                Some(v) => std::env::set_var(VSCODE_BIN_ENV, v),
                None => std::env::remove_var(VSCODE_BIN_ENV),
            }
        }
    }

    #[tokio::test]
    async fn menu_action_focus_resolves_folder_and_spawns() {
        let dir = tempfile::tempdir().unwrap();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [dir.path()], "repo": "r" }),
        )
        .await
        .unwrap();

        // Point the launcher at a harmless binary so the spawn deterministically
        // succeeds and the focus path returns Ok.
        let _g = VscodeBinGuard(std::env::var_os(VSCODE_BIN_ENV));
        std::env::set_var(VSCODE_BIN_ENV, "/bin/sh");
        svc.menu_action("focus:w1").await.unwrap();
    }

    #[tokio::test]
    async fn open_rejects_missing_relative_or_nonexistent_path() {
        let svc = WorktreesService::new();
        // A missing `path` is a payload error.
        assert!(svc.handle("open", json!({})).await.is_err());
        assert!(svc.handle("open", json!({ "path": 42 })).await.is_err());
        // A relative path is rejected before any spawn — this is also what
        // blocks a `-`-leading argument from reaching `code` as a flag.
        assert!(svc
            .handle("open", json!({ "path": "relative/dir" }))
            .await
            .is_err());
        assert!(svc
            .handle("open", json!({ "path": "-flag" }))
            .await
            .is_err());
        // An absolute path that does not exist is rejected before any spawn, so
        // no launcher is needed for these guard cases.
        assert!(svc
            .handle("open", json!({ "path": "/no/such/abs/dir/xyzzy" }))
            .await
            .is_err());
        svc.shutdown().await;
    }

    #[tokio::test]
    async fn open_focuses_an_existing_absolute_dir() {
        let dir = tempfile::tempdir().unwrap();
        let svc = WorktreesService::new();
        // Pin the launcher to a harmless binary so the spawn deterministically
        // succeeds whether or not `code` is installed. Unlike the tray `focus`
        // path, `open` takes the folder straight from the payload — no prior
        // `register` is required.
        let _g = VscodeBinGuard(std::env::var_os(VSCODE_BIN_ENV));
        std::env::set_var(VSCODE_BIN_ENV, "/bin/sh");
        let reply = svc
            .handle("open", json!({ "path": dir.path() }))
            .await
            .unwrap();
        assert_eq!(reply, json!({ "ok": true }));
        svc.shutdown().await;
    }

    #[test]
    fn focus_window_with_validates_folder_then_spawns() {
        let dir = tempfile::tempdir().unwrap();
        // Non-absolute and missing-directory folders are rejected before spawn.
        assert!(focus_window_with(Path::new("/bin/sh"), Path::new("relative/dir")).is_err());
        assert!(
            focus_window_with(Path::new("/bin/sh"), Path::new("/no/such/abs/dir/xyzzy")).is_err()
        );
        // A valid absolute directory spawns the launcher successfully.
        focus_window_with(Path::new("/bin/sh"), dir.path()).unwrap();
        // A missing launcher surfaces the spawn error (with context), not Ok.
        assert!(focus_window_with(Path::new("/no/such/launcher/xyzzy"), dir.path()).is_err());
    }

    #[test]
    fn resolve_code_binary_from_prefers_env_then_candidate_then_fallback() {
        // Env override wins outright.
        assert_eq!(
            resolve_code_binary_from(Some("/custom/code".into()), &["/usr/bin/code"]),
            PathBuf::from("/custom/code")
        );
        // No override: the first existing candidate is chosen.
        let existing = tempfile::NamedTempFile::new().unwrap();
        let existing_path = existing.path().to_str().unwrap();
        assert_eq!(
            resolve_code_binary_from(None, &["/no/such/candidate/xyzzy", existing_path]),
            PathBuf::from(existing_path)
        );
        // Nothing exists: fall back to bare `code` on PATH.
        assert_eq!(
            resolve_code_binary_from(None, &["/no/such/candidate/xyzzy"]),
            PathBuf::from("code")
        );
        // The real-env wrapper resolves without panicking.
        let _ = resolve_code_binary();
    }

    // --- Git enrichment (#1186) --------------------------------------------

    /// Initializes a fresh repo with a deterministic identity so `commit()`
    /// works without depending on a global git config.
    fn init_repo(dir: &Path) -> Repository {
        let repo = Repository::init(dir).unwrap();
        let mut cfg = repo.config().unwrap();
        cfg.set_str("user.name", "Test").unwrap();
        cfg.set_str("user.email", "test@example.com").unwrap();
        repo
    }

    /// Writes an empty-tree commit (file content is irrelevant to ahead/behind),
    /// optionally moving `refname` to it, and returns its oid.
    fn empty_commit(
        repo: &Repository,
        refname: Option<&str>,
        parents: &[&git2::Commit<'_>],
        msg: &str,
    ) -> git2::Oid {
        let sig = git2::Signature::now("Test", "test@example.com").unwrap();
        let tree = repo
            .find_tree(repo.treebuilder(None).unwrap().write().unwrap())
            .unwrap();
        repo.commit(refname, &sig, &sig, msg, &tree, parents)
            .unwrap()
    }

    /// Commits `content` as file `name` onto `refname`, chaining off its current
    /// tip (if any). Unlike [`empty_commit`], the tree carries a real blob, so
    /// the file is checked out into a worktree and can then be modified to
    /// produce a dirty (tracked) status.
    fn commit_file(
        repo: &Repository,
        refname: &str,
        name: &str,
        content: &[u8],
        msg: &str,
    ) -> git2::Oid {
        let sig = git2::Signature::now("Test", "test@example.com").unwrap();
        let blob = repo.blob(content).unwrap();
        let mut builder = repo.treebuilder(None).unwrap();
        builder.insert(name, blob, 0o100_644).unwrap();
        let tree = repo.find_tree(builder.write().unwrap()).unwrap();
        let parent = repo
            .refname_to_id(refname)
            .ok()
            .and_then(|oid| repo.find_commit(oid).ok());
        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
        repo.commit(Some(refname), &sig, &sig, msg, &tree, &parents)
            .unwrap()
    }

    /// Builds a repo whose `main` is 1 commit ahead of and 1 behind a configured
    /// `origin/main` upstream, so enrichment reports `ahead: 1, behind: 1`.
    fn diverging_repo(dir: &Path) -> Repository {
        let repo = init_repo(dir);
        // A: the shared base on `main`.
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        let a_commit = repo.find_commit(a).unwrap();
        // origin/main diverges to C, a sibling of the local tip.
        let c = empty_commit(&repo, None, &[&a_commit], "C");
        repo.reference("refs/remotes/origin/main", c, true, "origin main")
            .unwrap();
        // Local `main` advances to B → 1 ahead of / 1 behind origin/main.
        empty_commit(&repo, Some("refs/heads/main"), &[&a_commit], "B");
        // Release the commit's borrow of `repo` so it can be returned.
        drop(a_commit);
        repo.set_head("refs/heads/main").unwrap();
        // Configure the tracking relationship so `upstream()` resolves.
        let mut cfg = repo.config().unwrap();
        cfg.set_str("remote.origin.url", "https://example.invalid/x.git")
            .unwrap();
        cfg.set_str("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")
            .unwrap();
        cfg.set_str("branch.main.remote", "origin").unwrap();
        cfg.set_str("branch.main.merge", "refs/heads/main").unwrap();
        repo
    }

    #[test]
    fn git_status_reads_branch_and_ahead_behind() {
        let dir = tempfile::tempdir().unwrap();
        let _repo = diverging_repo(dir.path());
        let status = git_status(dir.path());
        assert_eq!(status.branch.as_deref(), Some("main"));
        assert_eq!(status.ahead, Some(1));
        assert_eq!(status.behind, Some(1));
        // A normal checkout names itself and is not flagged a worktree.
        assert_eq!(
            status.main_repo.as_deref(),
            dir.path().file_name().and_then(|n| n.to_str())
        );
        assert!(!status.is_worktree);
    }

    #[test]
    fn git_status_empty_repo_is_unborn() {
        // A repo with no commits has an unborn HEAD, so `head()` errors and the
        // branch/sync fields stay empty rather than panicking — but the repo
        // identity is still resolved from the common dir.
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        let status = git_status(dir.path());
        assert_eq!(status.branch, None);
        // An unborn HEAD has no commit to name, so the SHA is absent too (#1337).
        assert_eq!(status.head_sha, None);
        assert_eq!(status.ahead, None);
        assert_eq!(status.behind, None);
        assert_eq!(
            status.main_repo.as_deref(),
            dir.path().file_name().and_then(|n| n.to_str())
        );
        assert!(!status.is_worktree);
    }

    #[test]
    fn git_status_no_upstream_reports_branch_only() {
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        let status = git_status(dir.path());
        assert_eq!(status.branch.as_deref(), Some("main"));
        // No upstream → ahead/behind stay absent rather than zero.
        assert_eq!(status.ahead, None);
        assert_eq!(status.behind, None);
        // …and so does the upstream SHA, so such a branch still renders with no
        // sync indicator at all (#1344).
        assert_eq!(status.upstream_sha, None);
    }

    #[test]
    fn git_status_non_repo_is_empty_detached_reports_repo_without_branch() {
        // A plain directory that is not a git repo yields nothing at all.
        let plain = tempfile::tempdir().unwrap();
        assert_eq!(git_status(plain.path()), GitStatus::default());

        // A detached HEAD reports no branch (and thus no sync), but the repo
        // identity is still resolved from the common dir.
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head_detached(a).unwrap();
        let status = git_status(dir.path());
        assert_eq!(status.branch, None);
        // A detached HEAD has no branch but *does* have a commit — the SHA is
        // resolved before the branch filter, so it survives here (#1337).
        assert_eq!(status.head_sha.as_deref(), Some(a.to_string().as_str()));
        assert_eq!(status.ahead, None);
        assert_eq!(status.behind, None);
        // A detached HEAD has no branch, so there is no upstream to resolve
        // either — the branch filter returns before the wrap (#1344).
        assert_eq!(status.upstream_sha, None);
        assert_eq!(
            status.main_repo.as_deref(),
            dir.path().file_name().and_then(|n| n.to_str())
        );
        assert!(!status.is_worktree);
    }

    // --- Lazy ahead/behind (#1306) -----------------------------------------

    #[test]
    fn git_status_cheap_reads_branch_but_skips_the_divergence_walk() {
        // The same repo `git_status` reports 1/1 for. The cheap variant used by
        // the streamed tree snapshot still reads the branch and repo identity, but
        // leaves ahead/behind absent — divergence is now lazy (#1306).
        let dir = tempfile::tempdir().unwrap();
        let repo = diverging_repo(dir.path());
        let status = git_status_cheap(dir.path());
        assert_eq!(status.branch.as_deref(), Some("main"));
        assert_eq!(status.ahead, None);
        assert_eq!(status.behind, None);
        assert_eq!(
            status.main_repo.as_deref(),
            dir.path().file_name().and_then(|n| n.to_str())
        );
        // The SHA rides the *cheap* path deliberately: it is a refs read, not a
        // revwalk, and it is what makes a new commit a snapshot delta (#1337).
        let head = repo.head().unwrap().target().unwrap();
        assert_eq!(status.head_sha.as_deref(), Some(head.to_string().as_str()));
    }

    // --- HEAD SHA on the snapshot (#1337) ----------------------------------

    #[test]
    fn git_status_head_sha_tracks_new_commits() {
        // The regression #1337 turns on: a commit must change the status the
        // snapshot is built from. Before the SHA rode the payload, committing
        // changed nothing on the wire, the server's diff dropped the identical
        // snapshot, and no client re-rendered — so a badge computed for the old
        // head survived the push that invalidated it.
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        let before = git_status_cheap(dir.path());
        assert_eq!(before.head_sha.as_deref(), Some(a.to_string().as_str()));

        let head = repo.find_commit(a).unwrap();
        let b = empty_commit(&repo, Some("refs/heads/main"), &[&head], "B");
        let after = git_status_cheap(dir.path());
        assert_eq!(after.head_sha.as_deref(), Some(b.to_string().as_str()));
        assert_ne!(before.head_sha, after.head_sha);
        // The branch is unchanged — the SHA is the *only* thing that moved, which
        // is exactly why its absence made the push invisible.
        assert_eq!(before.branch, after.branch);
    }

    // --- Upstream SHA on the snapshot (#1344) ------------------------------

    /// Repoints `refs/remotes/origin/main` at `oid` — exactly what a `git push`
    /// does, and all of what it does: the local branch and HEAD do not move. Lets
    /// these tests exercise a push with no network and no second repo.
    fn simulate_push(repo: &Repository, oid: git2::Oid) {
        repo.reference("refs/remotes/origin/main", oid, true, "push")
            .unwrap();
    }

    #[test]
    fn git_status_upstream_sha_tracks_a_push() {
        // The regression #1344 turns on. `diverging_repo` leaves local `main` at B
        // and origin/main at C — 1 ahead, 1 behind. Pushing B moves *only* the
        // remote-tracking ref, so before this field rode the payload every wire
        // field was byte-identical across the push, the server's diff dropped the
        // snapshot, no client re-rendered, and the lazily-fetched ahead/behind was
        // never re-asked — the row showed `↑1 ↓0` forever.
        let dir = tempfile::tempdir().unwrap();
        let repo = diverging_repo(dir.path());
        let before = git_status(dir.path());
        assert_eq!(before.ahead, Some(1));
        assert_eq!(before.behind, Some(1));

        let head = repo.head().unwrap().target().unwrap();
        simulate_push(&repo, head);
        let after = git_status(dir.path());

        // The upstream now names the pushed commit, and the counts agree.
        assert_eq!(
            after.upstream_sha.as_deref(),
            Some(head.to_string().as_str())
        );
        assert_ne!(before.upstream_sha, after.upstream_sha);
        assert_eq!(after.ahead, Some(0));
        assert_eq!(after.behind, Some(0));
        // Nothing else moved — which is the whole point. A push leaves the branch
        // and the local head exactly where they were, so `upstream_sha` is the
        // only signal a client could possibly notice.
        assert_eq!(before.branch, after.branch);
        assert_eq!(before.head_sha, after.head_sha);
    }

    #[test]
    fn git_status_cheap_reports_upstream_sha() {
        // The crux: the field has to ride the *cheap* path, since that is the one
        // the streamed snapshot is built from. Costing a config lookup and a refs
        // read — no revwalk — it clears the bar #1306 set, unlike the divergence
        // walk still absent here.
        let dir = tempfile::tempdir().unwrap();
        let repo = diverging_repo(dir.path());
        let status = git_status_cheap(dir.path());
        let upstream = repo
            .find_branch("origin/main", git2::BranchType::Remote)
            .unwrap()
            .get()
            .target()
            .unwrap();
        assert_eq!(
            status.upstream_sha.as_deref(),
            Some(upstream.to_string().as_str())
        );
        assert_eq!(status.ahead, None);
        assert_eq!(status.behind, None);
    }

    #[test]
    fn folder_ahead_behind_computes_divergence_and_degrades() {
        // A diverging tracking branch → the on-demand walk reports (ahead, behind).
        let dir = tempfile::tempdir().unwrap();
        let _repo = diverging_repo(dir.path());
        assert_eq!(folder_ahead_behind(dir.path()), Some((1, 1)));

        // A branch with no upstream → None (the tree renders no sync indicator).
        let no_up = tempfile::tempdir().unwrap();
        let repo = init_repo(no_up.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        assert_eq!(folder_ahead_behind(no_up.path()), None);

        // A detached HEAD and a plain (non-repo) directory → None.
        let detached = tempfile::tempdir().unwrap();
        let drepo = init_repo(detached.path());
        let a = empty_commit(&drepo, Some("refs/heads/main"), &[], "A");
        drepo.set_head_detached(a).unwrap();
        assert_eq!(folder_ahead_behind(detached.path()), None);
        let plain = tempfile::tempdir().unwrap();
        assert_eq!(folder_ahead_behind(plain.path()), None);
    }

    #[tokio::test]
    async fn ahead_behind_op_returns_divergence_keyed_by_path_and_omits_no_upstream() {
        let diverging = tempfile::tempdir().unwrap();
        let _d = diverging_repo(diverging.path());
        let no_up = tempfile::tempdir().unwrap();
        let repo = init_repo(no_up.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();

        let svc = WorktreesService::new();
        let diverging_path = diverging.path().display().to_string();
        let no_up_path = no_up.path().display().to_string();
        let reply = svc
            .handle(
                "ahead-behind",
                json!({ "paths": [&diverging_path, &no_up_path] }),
            )
            .await
            .unwrap();
        let results = reply.get("results").unwrap();
        // The diverging worktree carries its counts, keyed by the requested path.
        let d = results.get(diverging_path.as_str()).unwrap();
        assert_eq!(d.get("ahead").and_then(Value::as_u64), Some(1));
        assert_eq!(d.get("behind").and_then(Value::as_u64), Some(1));
        // The no-upstream worktree is omitted entirely, not reported as zero.
        assert!(results.get(no_up_path.as_str()).is_none(), "{results:?}");

        // A missing/empty `paths` list yields an empty results object, not an error.
        let empty = svc.handle("ahead-behind", json!({})).await.unwrap();
        assert_eq!(empty.get("results"), Some(&json!({})));
    }

    #[tokio::test]
    async fn tree_snapshot_omits_ahead_behind_for_a_diverging_worktree() {
        // A window on a repo whose branch is 1 ahead of / 1 behind its upstream.
        let dir = tempfile::tempdir().unwrap();
        let _repo = diverging_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "x" }),
        )
        .await
        .unwrap();

        let repos = repos_of(&svc.handle("tree", Value::Null).await.unwrap());
        let worktrees = repos[0].get("worktrees").and_then(Value::as_array).unwrap();
        let main_wt = &worktrees[0];
        // The cheap parts are present, but divergence is not — it is fetched
        // lazily via the `ahead-behind` op (#1306).
        assert_eq!(main_wt.get("branch").and_then(Value::as_str), Some("main"));
        assert!(main_wt.get("ahead").is_none(), "{main_wt:?}");
        assert!(main_wt.get("behind").is_none(), "{main_wt:?}");
    }

    #[tokio::test]
    async fn tree_snapshot_carries_head_sha_so_a_commit_is_a_real_delta() {
        // The end-to-end shape of the #1337 freshness fix. The server pushes a
        // snapshot only when it differs from the last one
        // (`server.rs`: `if snap != last`), so anything invisible on the wire
        // cannot trigger a re-render. Committing must therefore move the payload.
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "x" }),
        )
        .await
        .unwrap();

        let before = svc.handle("tree", Value::Null).await.unwrap();
        let wt = &repos_of(&before)[0]["worktrees"][0];
        assert_eq!(
            wt.get("head_sha").and_then(Value::as_str),
            Some(a.to_string().as_str())
        );

        // Commit again: same branch, same paths, same open windows — pre-#1337 the
        // snapshot was byte-identical here and the push was dropped.
        let head = repo.find_commit(a).unwrap();
        let b = empty_commit(&repo, Some("refs/heads/main"), &[&head], "B");
        let after = svc.handle("tree", Value::Null).await.unwrap();
        assert_eq!(
            repos_of(&after)[0]["worktrees"][0]
                .get("head_sha")
                .and_then(Value::as_str),
            Some(b.to_string().as_str())
        );
        assert_ne!(before, after, "a commit must be a visible snapshot delta");
    }

    #[tokio::test]
    async fn tree_snapshot_omits_head_sha_for_an_unborn_repo() {
        // Wire-compat: an absent SHA is dropped entirely rather than sent as null,
        // matching the payload's `skip_serializing_if` convention.
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "x" }),
        )
        .await
        .unwrap();
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert!(wt.get("head_sha").is_none(), "{wt:?}");
    }

    // --- Upstream SHA on the snapshot (#1344) ------------------------------

    #[tokio::test]
    async fn tree_snapshot_carries_upstream_sha_so_a_push_is_a_real_delta() {
        // The end-to-end shape of the #1344 fix, one ref over from #1337. A push
        // moves neither the branch nor the local head, so `upstream_sha` is the
        // only field that can carry the news. Without it the snapshot serialised
        // byte-identically, `server.rs`'s `if snap != last` dropped the frame, no
        // window re-rendered, and the lazy ahead/behind was never re-fetched.
        let dir = tempfile::tempdir().unwrap();
        let repo = diverging_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "x" }),
        )
        .await
        .unwrap();

        let before = svc.handle("tree", Value::Null).await.unwrap();
        let head = repo.head().unwrap().target().unwrap();
        assert_ne!(
            repos_of(&before)[0]["worktrees"][0]
                .get("upstream_sha")
                .and_then(Value::as_str),
            Some(head.to_string().as_str()),
            "the fixture must start un-pushed for this to prove anything"
        );

        // Push: only `refs/remotes/origin/main` moves.
        simulate_push(&repo, head);
        let after = svc.handle("tree", Value::Null).await.unwrap();
        let wt = &repos_of(&after)[0]["worktrees"][0];
        assert_eq!(
            wt.get("upstream_sha").and_then(Value::as_str),
            Some(head.to_string().as_str())
        );
        // The head and branch are untouched across the push — so this delta rests
        // entirely on `upstream_sha`.
        assert_eq!(
            wt.get("head_sha").and_then(Value::as_str),
            repos_of(&before)[0]["worktrees"][0]
                .get("head_sha")
                .and_then(Value::as_str)
        );
        assert_ne!(before, after, "a push must be a visible snapshot delta");
    }

    #[tokio::test]
    async fn tree_snapshot_omits_upstream_sha_without_an_upstream() {
        // Wire-compat, and the no-regression case: a branch tracking nothing sends
        // no key at all rather than a null, so an older client sees exactly the
        // payload it saw before and still renders no sync indicator.
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "x" }),
        )
        .await
        .unwrap();
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert!(wt.get("upstream_sha").is_none(), "{wt:?}");
        // The head still rides, so this is specifically the upstream degrading.
        assert!(wt.get("head_sha").is_some(), "{wt:?}");
    }

    // --- PR badge poller (#1337) -------------------------------------------

    /// Writes an executable stub that ignores its arguments and prints `stdout`,
    /// standing in for `gh api graphql` so the poll loop is exercised offline.
    /// Returns the shim lock alongside the path: the caller **must** hold the
    /// guard until the poller has finished exec'ing the stub. Writing an
    /// executable and then `execve`ing it races every other thread that forks —
    /// the child inherits the still-open writable FD and the exec fails
    /// `ETXTBSY`. See [`crate::pr_status`]'s twin helper (#642, #1344).
    fn fake_gh(dir: &Path, stdout: &str) -> (PathBuf, MutexGuard<'static, ()>) {
        let guard = shim_lock();
        let path = dir.join("fake-gh");
        write_exec_script(&path, &format!("#!/bin/sh\ncat <<'JSON'\n{stdout}\nJSON\n"));
        (path, guard)
    }

    /// A [`fake_gh`] that also records **ground truth**: each invocation appends a
    /// byte to a counter file before printing `stdout`. The returned counter path
    /// lets a test assert how many `gh` subprocesses actually ran, independent of
    /// the #1387 request-log counter — so the two can be compared (#1389).
    fn counting_fake_gh(dir: &Path, stdout: &str) -> (PathBuf, MutexGuard<'static, ()>, PathBuf) {
        let guard = shim_lock();
        let path = dir.join("fake-gh");
        let counter = dir.join("gh-calls");
        write_exec_script(
            &path,
            &format!(
                "#!/bin/sh\nprintf x >> {counter:?}\ncat <<'JSON'\n{stdout}\nJSON\n",
                counter = counter.display()
            ),
        );
        (path, guard, counter)
    }

    /// The number of `gh` subprocesses the counting stub recorded (0 if it never
    /// ran) — the length of the counter file.
    fn gh_spawn_count(counter: &Path) -> usize {
        std::fs::read(counter).map_or(0, |b| b.len())
    }

    /// The number of **successful** `kind: "gh"` records the #1387 choke point
    /// wrote to `log` — one NDJSON line per `gh` that ran to a `0` exit. Filtering
    /// on the exit code matches the ground-truth counter (which is written when the
    /// stub *runs*), so a rare failed spawn cannot desync the two.
    fn counted_gh_records(log: &Path) -> usize {
        std::fs::read_to_string(log)
            .unwrap_or_default()
            .lines()
            .filter(|l| l.contains(r#""kind":"gh""#) && l.contains(r#""exit_code":0"#))
            .count()
    }

    /// A repo with a GitHub origin and one commit on `main`.
    fn github_repo(dir: &Path) -> Repository {
        github_repo_with_remote(dir, "git@github.com:rust-works/omni-dev.git")
    }

    /// A repo with a specific GitHub `origin` URL and one commit on `main`, so a
    /// test can register **distinct** targets (owner/name) across windows.
    fn github_repo_with_remote(dir: &Path, url: &str) -> Repository {
        let repo = init_repo(dir);
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        repo.remote("origin", url).unwrap();
        repo
    }

    /// A pending badge whose verdict is about `head_oid`. The commit is explicit
    /// because the fold downgrades a badge naming a different commit than the
    /// worktree's HEAD (#1337) — a fixture that got it wrong would pass for the
    /// wrong reason.
    fn pending_badge(number: u64, head_oid: &str) -> PrBadge {
        PrBadge {
            number,
            is_draft: false,
            checks: PrCheckState::Pending,
            url: "u".into(),
            head_oid: head_oid.to_string(),
        }
    }

    /// Wraps a badge as the cache's resolution value (#1370).
    fn pr(badge: PrBadge) -> PrResolution {
        PrResolution::Pr(badge)
    }

    #[test]
    fn pr_targets_from_snapshot_reads_github_branches_and_dedupes() {
        let snapshot = json!({"repos":[
            {
                "main_repo":"omni-dev",
                "github":{"owner":"rust-works","name":"omni-dev"},
                "root":"/r",
                // Enabled (#1376) — a not-polled repo contributes no targets (see
                // `pr_watch_from_snapshot_skips_a_not_polled_repo`).
                "polling_enabled":true,
                // Two worktrees on the same branch must ask once, not twice.
                "worktrees":[
                    {"path":"/r","branch":"main","is_main":true,"open":true},
                    {"path":"/w1","branch":"main","is_main":false,"open":true},
                    {"path":"/w2","branch":"feature","is_main":false,"open":true},
                    // Detached: no branch, so nothing to resolve.
                    {"path":"/w3","is_main":false,"open":true}
                ]
            },
            {
                // Not on GitHub: contributes no targets at all.
                "main_repo":"local","root":"/l",
                "worktrees":[{"path":"/l","branch":"main","is_main":true,"open":true}]
            }
        ]});
        let targets = pr_targets_from_snapshot(&snapshot);
        assert_eq!(
            targets,
            vec![
                PrTarget {
                    owner: "rust-works".into(),
                    name: "omni-dev".into(),
                    branch: "feature".into()
                },
                PrTarget {
                    owner: "rust-works".into(),
                    name: "omni-dev".into(),
                    branch: "main".into()
                },
            ]
        );
    }

    #[test]
    fn pr_targets_from_snapshot_is_empty_without_repos() {
        assert!(pr_targets_from_snapshot(&json!({"repos":[]})).is_empty());
        assert!(pr_targets_from_snapshot(&json!({})).is_empty());
    }

    #[test]
    fn pr_targets_from_snapshot_skips_a_malformed_github_identity() {
        // Defensive: a `github` object without usable owner/name strings yields no
        // target rather than a half-built query.
        for github in [
            json!({}),
            json!({"owner": "o"}),
            json!({"owner": 1, "name": 2}),
        ] {
            let snapshot = json!({"repos":[{
                "main_repo":"r","github":github,"root":"/r","polling_enabled":true,
                "worktrees":[{"path":"/r","branch":"main","is_main":true,"open":true}]
            }]});
            assert!(
                pr_targets_from_snapshot(&snapshot).is_empty(),
                "{snapshot:?}"
            );
        }
    }

    #[test]
    fn pr_watch_from_snapshot_skips_a_not_polled_repo() {
        // The zero-`gh` guarantee (#1376): a GitHub repo with `polling_enabled`
        // absent (the default-off case) or explicitly false contributes no watch,
        // so the poll never mentions it. Only an enabled repo is polled.
        for repo in [
            json!({
                "main_repo":"omni-dev","github":{"owner":"o","name":"n"},"root":"/r",
                "worktrees":[{"path":"/r","branch":"main","is_main":true,"open":true}]
            }),
            json!({
                "main_repo":"omni-dev","github":{"owner":"o","name":"n"},"root":"/r",
                "polling_enabled":false,
                "worktrees":[{"path":"/r","branch":"main","is_main":true,"open":true}]
            }),
        ] {
            let snapshot = json!({ "repos": [repo] });
            assert!(
                pr_targets_from_snapshot(&snapshot).is_empty(),
                "not-polled repo must yield no targets: {snapshot:?}"
            );
        }
        // Flipping the same repo to enabled makes it contribute.
        let enabled = json!({"repos":[{
            "main_repo":"omni-dev","github":{"owner":"o","name":"n"},"root":"/r",
            "polling_enabled":true,
            "worktrees":[{"path":"/r","branch":"main","is_main":true,"open":true}]
        }]});
        assert_eq!(pr_targets_from_snapshot(&enabled).len(), 1);
    }

    #[test]
    fn pr_should_fetch_when_the_watch_grew_or_the_backoff_elapsed() {
        let backoff = Duration::from_secs(600);
        // Never fetched: go.
        assert!(pr_should_fetch(false, None, backoff));
        // Quiet tree, backoff not elapsed: this is the common tick — wake, look,
        // spend nothing.
        assert!(!pr_should_fetch(
            false,
            Some(Duration::from_secs(1)),
            backoff
        ));
        // Quiet tree, backoff elapsed: time to look again.
        assert!(pr_should_fetch(false, Some(backoff), backoff));
        assert!(pr_should_fetch(false, Some(backoff * 2), backoff));
        // The load-bearing case: the watch grew (a target added, or an upstream
        // pushed), so fetch **now** regardless of how deep the backoff had grown.
        // Without this a push waits out the full ceiling on a stale badge.
        assert!(pr_should_fetch(true, Some(Duration::ZERO), backoff));
        assert!(pr_should_fetch(
            true,
            Some(Duration::from_millis(1)),
            backoff
        ));
    }

    #[test]
    fn next_pr_poll_delay_escalates_within_pending_and_backs_off_when_terminal() {
        let base = Duration::from_secs(10);
        let fresh = Some(Duration::ZERO);
        let stale = Some(PENDING_FAST_WINDOW);
        // Pending and fresh (within the fast window): hold `base`, however long we
        // had backed off for.
        assert_eq!(next_pr_poll_delay(base, base, true, fresh), base);
        assert_eq!(
            next_pr_poll_delay(PENDING_MAX_INTERVAL, base, true, fresh),
            base
        );
        // Pending but past the fast window (a long CI run): escalate — double up to
        // the pending ceiling, never to the terminal one.
        assert_eq!(next_pr_poll_delay(base, base, true, stale), base * 2);
        assert_eq!(
            next_pr_poll_delay(PENDING_MAX_INTERVAL, base, true, stale),
            PENDING_MAX_INTERVAL
        );
        // Pending with nothing having moved yet (`None`) is treated as past the fast
        // window, so a stale-from-boot pending state does not pin `base`.
        assert_eq!(next_pr_poll_delay(base, base, true, None), base * 2);
        // Everything terminal: double…
        assert_eq!(next_pr_poll_delay(base, base, false, fresh), base * 2);
        assert_eq!(next_pr_poll_delay(base * 2, base, false, fresh), base * 4);
        // …up to the terminal ceiling (above the pending one), and never overflow.
        assert_eq!(
            next_pr_poll_delay(MAX_PR_POLL_INTERVAL, base, false, fresh),
            MAX_PR_POLL_INTERVAL
        );
        assert_eq!(
            next_pr_poll_delay(Duration::MAX, base, false, None),
            MAX_PR_POLL_INTERVAL
        );
    }

    /// A watch on one branch with the given upstream tip.
    fn watch(branch: &str, upstream: Option<&str>) -> PrWatch {
        PrWatch {
            target: PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: branch.into(),
            },
            upstream_sha: upstream.map(str::to_string),
        }
    }

    #[test]
    fn pr_watch_grew_fires_on_additions_and_pushes_but_never_on_removals() {
        let a = watch("a", Some("111"));
        let b = watch("b", Some("222"));
        let ab = [a.clone(), b.clone()];
        let just_a = std::slice::from_ref(&a);
        let just_b = std::slice::from_ref(&b);
        // Nothing new: quiet tick.
        assert!(!pr_watch_grew(&ab, &ab));
        // Addition: a new target appeared.
        assert!(pr_watch_grew(just_a, &ab));
        // Pure removal: a window/worktree went away — must NOT fetch (#1389, fix 1).
        assert!(!pr_watch_grew(&ab, just_a));
        // First sight (empty prev, from `None`): everything is new.
        assert!(pr_watch_grew(&[], just_a));
        // A push moves only the upstream — still "grew".
        let a_pushed = [watch("a", Some("999"))];
        assert!(pr_watch_grew(just_a, &a_pushed));
        // Gaining a target while losing another still fetches (the gain wins).
        assert!(pr_watch_grew(just_a, just_b));
    }

    #[test]
    fn budget_throttled_delay_holds_the_floor_only_when_over_warn() {
        let base = Duration::from_secs(10);
        let over = RateLimitSnapshot {
            graphql: Some(rl_resource(90)),
            core: Some(rl_resource(3)),
            search: None,
        };
        let under = RateLimitSnapshot {
            graphql: Some(rl_resource(50)),
            core: Some(rl_resource(3)),
            search: None,
        };
        // No reading yet: unchanged.
        assert_eq!(budget_throttled_delay(base, None), base);
        // Under the warn threshold: unchanged.
        assert_eq!(budget_throttled_delay(base, Some(&under)), base);
        // Over: raised to at least the throttle floor…
        assert_eq!(
            budget_throttled_delay(base, Some(&over)),
            BUDGET_THROTTLE_INTERVAL
        );
        // …but a delay already above the floor is left alone (never shortened).
        let long = BUDGET_THROTTLE_INTERVAL * 2;
        assert_eq!(budget_throttled_delay(long, Some(&over)), long);
    }

    #[test]
    fn pr_cache_prefs_round_trips_through_json_including_head_oid() {
        // The persisted cache must survive a JSON round trip with `head_oid` intact
        // — it is the staleness key the tree wire drops, and losing it would render
        // every restored badge stale (#1389, fix 4).
        let target = PrTarget {
            owner: "rust-works".into(),
            name: "omni-dev".into(),
            branch: "main".into(),
        };
        let badge = PrResolution::Pr(PrBadge {
            number: 1337,
            is_draft: true,
            checks: PrCheckState::Pending,
            url: "http://x/1337".into(),
            head_oid: "deadbeef".into(),
        });
        let watched = vec![watch("main", Some("abc"))];
        let polled_at = DateTime::parse_from_rfc3339("2026-07-21T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let prefs = pr_cache_prefs_from(vec![(target, badge.clone())], &watched, polled_at);

        let json = serde_json::to_vec(&prefs).unwrap();
        let back: PrCachePrefs = serde_json::from_slice(&json).unwrap();
        assert_eq!(back, prefs);
        assert_eq!(back.polled_at, Some(polled_at));
        assert_eq!(back.watched[0].upstream_sha.as_deref(), Some("abc"));
        // The restored resolution equals the original — head_oid and all.
        assert_eq!(back.entries[0].resolution.clone().into_resolution(), badge);
    }

    #[test]
    fn pr_cache_prefs_round_trip_an_explicit_no_pr_verdict() {
        // The explicit negative must survive persistence too: restoring `NoPr`
        // as "absent" would lose the #1370 distinction across a restart and
        // re-ask GitHub for branches already known to have no PR.
        let target = PrTarget {
            owner: "rust-works".into(),
            name: "omni-dev".into(),
            branch: "feature".into(),
        };
        let prefs = pr_cache_prefs_from(vec![(target, PrResolution::NoPr)], &[], Utc::now());
        let json = serde_json::to_vec(&prefs).unwrap();
        let back: PrCachePrefs = serde_json::from_slice(&json).unwrap();
        assert_eq!(back.entries[0].resolution, PersistedResolution::NoPr);
        assert_eq!(
            back.entries[0].resolution.clone().into_resolution(),
            PrResolution::NoPr
        );
    }

    #[test]
    fn load_pr_cache_without_polled_at_restores_badges_but_no_warm_start() {
        // A file with verdicts but no `polled_at` (an older shape, or a
        // hand-edited one) still renders badges, but must not arm the warm
        // start: without a poll time there is nothing to age the verdicts
        // against, so the poller re-polls immediately (#1389, fix 4).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pr-cache.json");
        let target = PrTarget {
            owner: "rust-works".into(),
            name: "omni-dev".into(),
            branch: "main".into(),
        };
        let mut prefs = pr_cache_prefs_from(
            vec![(target, PrResolution::Pr(pending_badge(7, "abc")))],
            &[watch("main", None)],
            Utc::now(),
        );
        prefs.polled_at = None;
        write_pr_cache(&path, &prefs).unwrap();

        let svc = WorktreesService::new();
        svc.load_pr_cache(path);
        assert!(
            svc.pr_cache.get("rust-works", "omni-dev", "main").is_some(),
            "the badge itself must still restore"
        );
        assert!(
            svc.pr_warm_start
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .is_none(),
            "no poll time means a cold start, not a trusted warm one"
        );
    }

    /// Installs a thread-local WARN-level subscriber for the duration of a
    /// test, so degraded-path `tracing::warn!` sites actually format their
    /// fields instead of short-circuiting on "nobody is listening".
    fn warn_subscriber() -> tracing::subscriber::DefaultGuard {
        tracing::subscriber::set_default(
            tracing_subscriber::fmt()
                .with_max_level(tracing::Level::WARN)
                .with_writer(std::io::sink)
                .finish(),
        )
    }

    #[test]
    fn load_pr_cache_tolerates_a_corrupt_or_unreadable_file() {
        // The best-effort contract: a mangled cache is logged and treated as
        // empty — never a panic — and the path is stored regardless, so the
        // next successful poll rewrites a clean file (#1389, fix 4).
        let _trace = warn_subscriber();
        let dir = tempfile::tempdir().unwrap();
        let corrupt = dir.path().join("pr-cache.json");
        std::fs::write(&corrupt, b"not json").unwrap();
        let svc = WorktreesService::new();
        svc.load_pr_cache(corrupt.clone());
        assert!(svc.pr_cache.entries().is_empty());
        assert_eq!(
            svc.pr_cache_path
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .as_deref(),
            Some(corrupt.as_path()),
            "the path must be stored even when the load fails, so persistence recovers"
        );

        // A directory: `read` fails with a non-NotFound error (the distinct
        // "could not read" arm), with the same treated-as-empty outcome.
        let svc = WorktreesService::new();
        svc.load_pr_cache(dir.path().to_path_buf());
        assert!(svc.pr_cache.entries().is_empty());
    }

    #[test]
    fn persist_pr_cache_swallows_a_write_failure() {
        // Best-effort: an unwritable path is logged at WARN and swallowed — the
        // in-memory cache stays authoritative, and losing the warm start only
        // costs one extra poll after the next restart.
        let _trace = warn_subscriber();
        let dir = tempfile::tempdir().unwrap();
        let blocker = dir.path().join("blocker");
        std::fs::write(&blocker, b"").unwrap();
        // The parent is a regular file, so creating the runtime dir must fail.
        let path = blocker.join("pr-cache.json");
        persist_pr_cache(&path, &PrStatusCache::new(), &[], Utc::now());
        assert!(!path.exists());
        // The root has no parent at all — nothing to create, and the write
        // itself fails (it is a directory); still swallowed.
        persist_pr_cache(Path::new("/"), &PrStatusCache::new(), &[], Utc::now());
    }

    #[tokio::test]
    async fn tree_snapshot_folds_cached_pr_badges_onto_matching_branches() {
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let head = repo.head().unwrap().target().unwrap().to_string();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);

        // No poll has landed: the badge is absent, exactly as a pre-#1337 daemon —
        // and so is the negative, so "not resolved" stays distinguishable (#1370).
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert!(wt.get("pr").is_none(), "{wt:?}");
        assert!(wt.get("pr_none").is_none(), "{wt:?}");

        // Seed the cache the poller writes, then re-read the tree.
        let mut badges = HashMap::new();
        badges.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            pr(pending_badge(1337, &head)),
        );
        assert!(svc.pr_cache.replace(badges));

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr"]["number"], json!(1337));
        assert_eq!(wt["pr"]["checks"], json!("pending"));
        // camelCase on the wire, or the extension silently loses the draft marker.
        assert_eq!(wt["pr"]["isDraft"], json!(false));
        // A badge and the negative are mutually exclusive.
        assert!(wt.get("pr_none").is_none(), "{wt:?}");
    }

    #[tokio::test]
    async fn tree_snapshot_omits_a_badge_for_a_detached_worktree() {
        // A detached HEAD has a commit but no branch, and a badge is keyed by
        // branch — so there is nothing to match. It must fall through silently
        // rather than borrow a badge from whatever branch happens to be cached, and
        // rather than sink the tree.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let head = repo.head().unwrap().target().unwrap();
        repo.set_head_detached(head).unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        // A badge *is* cached for `main` — the branch this worktree was on before
        // detaching. It must not leak onto the now-branchless row.
        let mut badges = HashMap::new();
        badges.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            pr(pending_badge(1, &head.to_string())),
        );
        svc.pr_cache.replace(badges);

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert!(wt.get("branch").is_none(), "{wt:?}");
        // The SHA still shows — detached means no branch, not no commit.
        assert_eq!(
            wt.get("head_sha").and_then(Value::as_str),
            Some(head.to_string().as_str())
        );
        assert!(wt.get("pr").is_none(), "{wt:?}");
        // No branch means nothing was checked either: no negative on the row.
        assert!(wt.get("pr_none").is_none(), "{wt:?}");
    }

    #[tokio::test]
    async fn tree_snapshot_omits_a_badge_for_an_unmatched_branch() {
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        // A badge for a different branch must not leak onto `main`.
        let mut badges = HashMap::new();
        badges.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "other".into(),
            },
            pr(pending_badge(1, "irrelevant")),
        );
        svc.pr_cache.replace(badges);
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert!(wt.get("pr").is_none(), "{wt:?}");
        // An unmatched branch is unresolved, not negative.
        assert!(wt.get("pr_none").is_none(), "{wt:?}");
    }

    #[tokio::test]
    async fn tree_snapshot_reports_an_explicit_negative_for_a_branch_with_no_pr() {
        // The #1370 fix on the wire: a branch the poller checked and found PR-less
        // carries `pr_none: true` — never a sentinel `pr` object — so a client can
        // tell "checked, none" from "not resolved" and keep its fallback quiet.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);

        let mut resolutions = HashMap::new();
        resolutions.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            PrResolution::NoPr,
        );
        assert!(svc.pr_cache.replace(resolutions));

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr_none"], json!(true));
        // Mutually exclusive with a badge.
        assert!(wt.get("pr").is_none(), "{wt:?}");
    }

    #[tokio::test]
    async fn a_commit_does_not_drop_a_negative_resolution() {
        // A negative has no commit to be stale against. Dropping it when HEAD
        // moves would flip the row back to "unresolved" on every local commit —
        // re-arming every client's `gh` fallback, the very cost #1370 removes. The
        // poller's `moved` trigger re-checks the branch promptly instead.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let first = repo.head().unwrap().target().unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);

        let mut resolutions = HashMap::new();
        resolutions.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            PrResolution::NoPr,
        );
        svc.pr_cache.replace(resolutions);

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr_none"], json!(true));

        // Commit — as a push would leave things, with the cache untouched.
        let head = repo.find_commit(first).unwrap();
        empty_commit(&repo, Some("refs/heads/main"), &[&head], "B");

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(
            wt["pr_none"],
            json!(true),
            "a local commit must not drop the negative"
        );
    }

    #[tokio::test]
    async fn pr_poller_asks_nothing_while_no_window_is_registered() {
        // The idle case — the daemon runs all day with no editor open. Point it at a
        // stub that fails loudly if ever spawned: a poll here would both waste
        // GitHub budget and, on a real `gh`, wake the radio for nothing.
        let bin_dir = tempfile::tempdir().unwrap();
        let marker = bin_dir.path().join("spawned");
        let fake = bin_dir.path().join("fake-gh");
        std::fs::write(
            &fake,
            format!("#!/bin/sh\ntouch '{}'\necho '{{}}'\n", marker.display()),
        )
        .unwrap();
        let mut perms = std::fs::metadata(&fake).unwrap().permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
        std::fs::set_permissions(&fake, perms).unwrap();

        let svc = WorktreesService::new();
        svc.start_pr_poller_with(Duration::from_millis(20), Duration::from_millis(10), fake);
        tokio::time::sleep(Duration::from_millis(200)).await;
        svc.shutdown().await;
        assert!(
            !marker.exists(),
            "the poller must not spawn gh with no windows registered"
        );
    }

    #[tokio::test]
    async fn pr_poller_survives_a_failing_gh_and_keeps_the_last_good_badges() {
        // Badges are decoration: an unauthenticated or broken `gh` must never sink
        // the tree, and one bad poll must not blank rows that were fine a second ago.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let head = repo.head().unwrap().target().unwrap().to_string();
        let bin_dir = tempfile::tempdir().unwrap();
        let fake = bin_dir.path().join("fake-gh");
        // Exits non-zero, exactly as `gh` does without `gh auth login`.
        std::fs::write(
            &fake,
            "#!/bin/sh\necho 'gh: not authenticated' >&2\nexit 1\n",
        )
        .unwrap();
        let mut perms = std::fs::metadata(&fake).unwrap().permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
        std::fs::set_permissions(&fake, perms).unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        // Seed a badge as though an earlier poll had succeeded.
        let mut seeded = HashMap::new();
        seeded.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            pr(pending_badge(7, &head)),
        );
        svc.pr_cache.replace(seeded);

        svc.start_pr_poller_with(Duration::from_millis(20), Duration::from_millis(10), fake);
        tokio::time::sleep(Duration::from_millis(200)).await;

        // The tree still serves, and the seeded badge survived the failing polls —
        // which also minted no false "no PR" negatives (#1370).
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr"]["number"], json!(7));
        assert!(wt.get("pr_none").is_none(), "{wt:?}");
        svc.shutdown().await;
    }

    #[tokio::test]
    // The shim guard is deliberately held across the awaits below: it must span
    // both the stub's write *and* the poller's exec of it, since the ETXTBSY race
    // is against another test writing while this one forks. Safe here — only test
    // threads take it, never a task inside the runtime, so it cannot deadlock.
    // Scoped per-test rather than on the module, which would also silence the
    // registry lock's "never held across .await" invariant.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_wakes_when_the_first_window_opens_after_an_idle_start() {
        // The normal startup order: the daemon starts at login, *before* any
        // editor. It therefore sees an empty tree and backs off to the 30-minute
        // ceiling — so unless a register wakes it, the first badge of the session
        // arrives up to half an hour after the window does, which reads as the
        // feature being broken rather than slow.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"a","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"IN_PROGRESS","conclusion":null}
                ]}}},
                "associatedPullRequests":{"nodes":[{"number":99,"isDraft":false,"url":"u"}]}
            }}}}"#,
        );

        let svc = WorktreesService::new();
        // Poller first, with nothing registered — it backs off on the empty tree.
        svc.start_pr_poller_with(Duration::from_millis(50), Duration::from_millis(10), fake);
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Now an editor opens.
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);

        // The badge must follow promptly — the register wakes the loop out of its
        // backoff. The deadline is orders of magnitude below the ceiling, so this
        // fails on the bug rather than merely being slow.
        let badge = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if let Some(PrResolution::Pr(badge)) =
                    svc.pr_cache.get("rust-works", "omni-dev", "main")
                {
                    return badge;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("a window opening must wake the poller out of its idle backoff");
        assert_eq!(badge.number, 99);
        svc.shutdown().await;
    }

    #[tokio::test]
    async fn a_commit_invalidates_the_previous_verdict_without_a_poll() {
        // The acceptance criterion: "pushing a new commit invalidates the badge
        // rather than leaving the previous head's verdict standing."
        //
        // The cache still holds the verdict for the *old* commit, and the poller may
        // have backed off for up to half an hour. So the fold — which runs on every
        // snapshot — has to notice on its own, with no network call.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let first = repo.head().unwrap().target().unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);

        // A green verdict, correctly describing the commit currently checked out.
        let mut badges = HashMap::new();
        badges.insert(
            PrTarget {
                owner: "rust-works".into(),
                name: "omni-dev".into(),
                branch: "main".into(),
            },
            pr(PrBadge {
                number: 1337,
                is_draft: false,
                checks: PrCheckState::Success,
                url: "u".into(),
                head_oid: first.to_string(),
            }),
        );
        svc.pr_cache.replace(badges);

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(
            wt["pr"]["checks"],
            json!("success"),
            "green for its own commit"
        );

        // Now commit — as a push would leave things, with the cache untouched.
        let head = repo.find_commit(first).unwrap();
        empty_commit(&repo, Some("refs/heads/main"), &[&head], "B");

        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(
            wt["pr"]["checks"],
            json!("pending"),
            "the previous commit's ✓ must not stand after a new commit"
        );
        // The PR itself is still shown — it is the *verdict* that is unknown, not
        // the PR.
        assert_eq!(wt["pr"]["number"], json!(1337));
    }

    #[test]
    fn is_stale_for_compares_the_commit_the_verdict_describes() {
        let badge = pending_badge(1, "aaa");
        assert!(!badge.is_stale_for(Some("aaa")));
        assert!(badge.is_stale_for(Some("bbb")));
        // No local HEAD (unborn): nothing to compare against, so not stale.
        assert!(!badge.is_stale_for(None));
    }

    #[test]
    fn pr_watch_ignores_the_head_so_a_local_commit_asks_nothing() {
        // #1389, fix 3. A local commit moves only the head — GitHub has not seen
        // it — so asking would return exactly the cached verdict, and the badge
        // stays correctly stale via `is_stale_for` with no network. So a snapshot
        // that differs *only* in `head_sha` must compare **equal** as a watch.
        let snap = |sha: &str| {
            json!({"repos":[{
                "main_repo":"omni-dev",
                "github":{"owner":"rust-works","name":"omni-dev"},
                "root":"/r",
                "polling_enabled":true,
                "worktrees":[{"path":"/r","branch":"main","head_sha":sha,"is_main":true,"open":true}]
            }]})
        };
        let before = pr_watch_from_snapshot(&snap("aaa"));
        let after = pr_watch_from_snapshot(&snap("bbb"));
        assert_eq!(before.len(), 1);
        assert_eq!(before[0].target, after[0].target);
        // The head moved, but the watch did not — no fetch trigger, no `gh` call.
        assert_eq!(before, after);
        assert!(!pr_watch_grew(&before, &after));
    }

    #[test]
    fn pr_watch_tracks_the_upstream_so_a_push_is_visible_to_the_poller() {
        // #1344's bonus. A push is what *starts* the CI run a badge reports, yet
        // it moves no local head — so an upstream move alone must register as "go
        // and ask now", or the badge sits at `●` until the backoff elapses.
        let snap = |upstream: &str| {
            json!({"repos":[{
                "main_repo":"omni-dev",
                "github":{"owner":"rust-works","name":"omni-dev"},
                "root":"/r",
                "polling_enabled":true,
                "worktrees":[{"path":"/r","branch":"main","head_sha":"aaa",
                              "upstream_sha":upstream,"is_main":true,"open":true}]
            }]})
        };
        let before = pr_watch_from_snapshot(&snap("aaa"));
        let after = pr_watch_from_snapshot(&snap("bbb"));
        // Same target, only the upstream moved — a genuine "grew" signal.
        assert_eq!(before.len(), 1);
        assert_eq!(before[0].target, after[0].target);
        assert_ne!(before, after);
        assert!(pr_watch_grew(&before, &after));
        // A quiet tick still asks nothing.
        assert_eq!(before, pr_watch_from_snapshot(&snap("aaa")));
        assert!(!pr_watch_grew(
            &before,
            &pr_watch_from_snapshot(&snap("aaa"))
        ));
    }

    #[test]
    fn pr_watch_omits_an_absent_upstream_rather_than_erroring() {
        // An older daemon — or any branch tracking nothing — simply sends no
        // `upstream_sha`, which reads as `None` rather than failing the poll.
        let snap = json!({"repos":[{
            "main_repo":"omni-dev",
            "github":{"owner":"rust-works","name":"omni-dev"},
            "root":"/r",
            "polling_enabled":true,
            "worktrees":[{"path":"/r","branch":"main","head_sha":"aaa","is_main":true,"open":true}]
        }]});
        let watch = pr_watch_from_snapshot(&snap);
        assert_eq!(watch.len(), 1);
        assert_eq!(watch[0].upstream_sha, None);
    }

    #[test]
    fn start_pr_poller_is_a_noop_outside_a_runtime() {
        let svc = WorktreesService::new();
        svc.start_pr_poller();
        assert!(svc
            .poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_none());
    }

    #[tokio::test]
    async fn start_pr_poller_is_idempotent_and_shutdown_stops_it() {
        let svc = WorktreesService::new();
        svc.start_pr_poller_with(
            Duration::from_millis(50),
            Duration::from_millis(10),
            PathBuf::from("/bin/true"),
        );
        let token = svc
            .poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .as_ref()
            .map(|t| t.token.clone())
            .expect("poller started");

        // Cancel the live task, then start again: if `start` spawned a replacement
        // it would orphan this one, so the token staying cancelled proves it did not.
        token.cancel();
        svc.start_pr_poller_with(
            Duration::from_millis(50),
            Duration::from_millis(10),
            PathBuf::from("/bin/true"),
        );
        assert!(svc
            .poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .as_ref()
            .is_some_and(|t| t.token.is_cancelled()));

        svc.shutdown().await;
        assert!(svc
            .poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_none());
    }

    // --- Rate-limit monitor (#1375) ---

    /// A resource at `used`% of a 100-request budget.
    fn rl_resource(used: u64) -> RateLimitResource {
        RateLimitResource {
            used,
            limit: 100,
            remaining: 100 - used,
            percent: used as f64,
            reset: 0,
        }
    }

    #[test]
    fn rate_limit_crossed_warn_fires_only_on_the_rising_edge() {
        let snap = |graphql: u64, core: u64| RateLimitSnapshot {
            graphql: Some(rl_resource(graphql)),
            core: Some(rl_resource(core)),
            search: None,
        };
        // First poll already over threshold → warn.
        assert!(rate_limit_crossed_warn(None, &snap(85, 3)));
        // First poll below → no warn.
        assert!(!rate_limit_crossed_warn(None, &snap(50, 3)));
        // Crossing upward → warn.
        assert!(rate_limit_crossed_warn(Some(&snap(70, 3)), &snap(85, 3)));
        // Staying over → no repeat warn.
        assert!(!rate_limit_crossed_warn(Some(&snap(85, 3)), &snap(90, 3)));
        // Recovering below → no warn.
        assert!(!rate_limit_crossed_warn(Some(&snap(85, 3)), &snap(50, 3)));
        // A *different* resource crossing while the first recovers is still caught.
        assert!(rate_limit_crossed_warn(Some(&snap(85, 3)), &snap(50, 90)));
    }

    #[test]
    fn start_rate_limit_poller_is_a_noop_outside_a_runtime() {
        let svc = WorktreesService::new();
        svc.start_rate_limit_poller();
        assert!(svc
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_none());
    }

    #[tokio::test]
    async fn start_rate_limit_poller_is_idempotent_and_shutdown_stops_it() {
        let svc = WorktreesService::new();
        svc.start_rate_limit_poller_with(Duration::from_millis(50), PathBuf::from("/bin/true"));
        let token = svc
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .as_ref()
            .map(|t| t.token.clone())
            .expect("poller started");

        // Cancel the live task, then start again: a second start must not spawn a
        // replacement (which would orphan this one), so the token stays cancelled.
        token.cancel();
        svc.start_rate_limit_poller_with(Duration::from_millis(50), PathBuf::from("/bin/true"));
        assert!(svc
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .as_ref()
            .is_some_and(|t| t.token.is_cancelled()));

        svc.shutdown().await;
        assert!(svc
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_none());
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn rate_limit_poller_resolves_via_gh_populates_the_cache_and_stops_on_shutdown() {
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"resources":{
                "graphql":{"limit":5000,"used":4100,"remaining":900,"reset":1700000000},
                "core":{"limit":5000,"used":27,"remaining":4973,"reset":1700000000}
            }}"#,
        );
        let svc = WorktreesService::new();
        // #1389, fix 8b: the poller only spends a `/rate_limit` call while something
        // is being watched — a lease makes it active without needing a window/folder.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.start_rate_limit_poller_with(Duration::from_millis(50), fake.clone());

        // Each poll spawns a real subprocess; wait on a generous deadline so a
        // loaded machine fails honestly rather than flaking.
        let snap = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if let Some(snap) = svc.rate_limit_cache.get() {
                    return snap;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("poller should populate the cache through the fake gh");
        assert_eq!(snap.graphql.unwrap().used, 4100);
        assert_eq!(snap.core.unwrap().used, 27);

        // The reading reaches the built-in status field via the shared cache.
        assert!(svc.rate_limit_cache().get().is_some());

        svc.shutdown().await;
        assert!(svc
            .rate_limit_poller
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_none());
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn rate_limit_poller_stays_idle_with_nothing_registered() {
        // #1389, fix 8b: a fully-idle daemon (no window, no lease) spends no
        // `/rate_limit` subprocess — the counting stub records zero spawns.
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim, counter) = counting_fake_gh(
            bin_dir.path(),
            r#"{"resources":{"graphql":{"limit":5000,"used":1,"remaining":4999,"reset":1}}}"#,
        );
        let svc = WorktreesService::new();
        svc.start_rate_limit_poller_with(Duration::from_millis(20), fake);

        // Give the loop several ticks; with nothing registered it must never poll.
        tokio::time::sleep(Duration::from_millis(300)).await;
        assert_eq!(
            gh_spawn_count(&counter),
            0,
            "idle daemon must not poll (#1389, fix 8b)"
        );
        assert!(svc.rate_limit_cache.get().is_none());

        // Once a lease is active, the next tick populates the cache.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if svc.rate_limit_cache.get().is_some() {
                    return;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("an active lease should resume polling");
        assert!(gh_spawn_count(&counter) >= 1);
        svc.shutdown().await;
    }

    #[tokio::test]
    async fn rate_limit_poller_survives_a_failing_gh() {
        // A missing/failing `gh` leaves the cache empty and never wedges the loop —
        // the degraded branch keeps the last (here, absent) reading rather than
        // crashing. Active via a lease so the gate (#1389, fix 8b) lets it try.
        let svc = WorktreesService::new();
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.start_rate_limit_poller_with(
            Duration::from_millis(20),
            PathBuf::from("/no/such/gh/xyzzy"),
        );
        // Let it fail a few times: the cache stays empty and the task stays alive.
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert!(svc.rate_limit_cache.get().is_none());
        assert!(
            svc.rate_limit_poller
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .is_some(),
            "the loop must survive a failing gh, not panic out"
        );
        svc.shutdown().await;
    }

    #[test]
    fn menu_prepends_the_rate_limit_line_only_when_the_cache_is_populated() {
        let svc = WorktreesService::new();
        // Empty cache → no rate-limit line (the pre-#1375 shape).
        let items = svc.menu().items;
        assert!(
            !items
                .iter()
                .any(|i| matches!(i, MenuItem::Label(l) if l.contains("github:"))),
            "no github line before the first poll"
        );

        // Populate the cache → the first item is the rate-limit status line.
        svc.rate_limit_cache.replace(RateLimitSnapshot {
            graphql: Some(rl_resource(82)),
            core: Some(rl_resource(3)),
            search: None,
        });
        let items = svc.menu().items;
        assert!(
            matches!(items.first(), Some(MenuItem::Label(l)) if l.starts_with("github: graphql 82%")),
            "expected the github line first, got {items:?}"
        );
        assert!(
            matches!(items.get(1), Some(MenuItem::Separator)),
            "expected a separator after the github line"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_resolves_via_gh_populates_the_cache_and_stops_on_shutdown() {
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        // One repo, one branch → aliases r0/b0. A still-running check so the badge
        // stays pending and the loop keeps its fast cadence.
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"abc","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"IN_PROGRESS","conclusion":null}
                ]}}},
                "associatedPullRequests":{"nodes":[{"number":1337,"isDraft":false,"url":"http://x/1337"}]}
            }}}}"#,
        );
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.start_pr_poller_with(
            Duration::from_millis(50),
            Duration::from_millis(10),
            fake.clone(),
        );

        // Wait on a generous wall-clock deadline: each poll spawns a real
        // subprocess, and under a loaded machine (a full `build.sh` runs a build
        // and clippy alongside) a tight budget flakes rather than fails honestly.
        let badge = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if let Some(PrResolution::Pr(badge)) =
                    svc.pr_cache.get("rust-works", "omni-dev", "main")
                {
                    return badge;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("poller should resolve a badge through the fake gh");
        assert_eq!(badge.number, 1337);
        assert_eq!(badge.checks, crate::pr_status::PrCheckState::Pending);

        // The badge reaches the wire the windows actually read.
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr"]["number"], json!(1337));

        // And the loop is quiescent after shutdown: the generation must stop moving.
        svc.shutdown().await;
        let generation = svc.registry.change_generation();
        tokio::time::sleep(Duration::from_millis(120)).await;
        assert_eq!(
            svc.registry.change_generation(),
            generation,
            "no bumps after shutdown"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poll_folds_its_graphql_budget_into_the_rate_limit_cache() {
        // #1389, fix 8a: every PR poll carries a free graphql budget reading, which
        // the poller folds into the shared cache — so the graphql figure stays fresh
        // without a standalone `/rate_limit` call.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"data":{
                "rateLimit":{"limit":5000,"cost":1,"remaining":4877,"used":123,
                             "resetAt":"2026-07-21T16:00:00Z"},
                "r0":{"b0":{
                  "target":{"oid":"abc","statusCheckRollup":{"contexts":{"nodes":[
                    {"__typename":"CheckRun","status":"IN_PROGRESS","conclusion":null}
                  ]}}},
                  "associatedPullRequests":{"nodes":[{"number":1337,"isDraft":false,"url":"http://x/1337"}]}
                }}
            }}"#,
        );
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        svc.registry.set_polling("rust-works", "omni-dev", true);
        // No rate-limit poller started: the only writer of the cache is the PR poll's
        // folded-in budget, so a populated graphql reading proves fix 8a.
        svc.start_pr_poller_with(
            Duration::from_millis(50),
            Duration::from_millis(10),
            fake.clone(),
        );

        let graphql = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if let Some(g) = svc.rate_limit_cache.get().and_then(|s| s.graphql) {
                    return g;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("the PR poll should fold its budget into the cache");
        assert_eq!(graphql.used, 123);
        assert_eq!(graphql.limit, 5000);
        assert_eq!(graphql.remaining, 4877);
        svc.shutdown().await;
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poll_counts_every_gh_call_exactly_once() {
        // #1389's non-negotiable constraint (#1387): fewer calls, but every call
        // still counted. Compares the ground-truth number of `gh` subprocesses the
        // poll actually spawned against the number of successful `kind:"gh"` records
        // the counted `run_gh` choke point wrote — they must be equal, so a future
        // refactor cannot add an uncounted `gh` path (counted < spawns) without
        // failing here.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim, counter) = counting_fake_gh(
            bin_dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"abc","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"IN_PROGRESS","conclusion":null}
                ]}}},
                "associatedPullRequests":{"nodes":[{"number":1337,"isDraft":false,"url":"http://x/1337"}]}
            }}}}"#,
        );
        let log = bin_dir.path().join("log.jsonl");
        std::env::set_var("OMNI_DEV_LOG_FILE", &log);

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.start_pr_poller_with(Duration::from_millis(30), Duration::from_millis(10), fake);

        // Wait for at least one fetch to land.
        tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if svc.pr_cache.get("rust-works", "omni-dev", "main").is_some() {
                    return;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("poller should fetch through the fake gh");

        // Stop the loop so both counts are final (no in-flight gh), then compare.
        svc.shutdown().await;
        let spawns = gh_spawn_count(&counter);
        let counted = counted_gh_records(&log);
        std::env::remove_var("OMNI_DEV_LOG_FILE");
        assert!(
            spawns >= 1,
            "the poll should have spent at least one gh call"
        );
        assert_eq!(
            counted, spawns,
            "#1387: every gh call ({spawns}) must be counted exactly once, got {counted}"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poll_debounces_a_registration_storm_into_one_fetch() {
        // #1389, fix 2: a burst of registrations (a VS Code restart re-registering
        // its windows) that each *grow* the watch must collapse into ONE fetch on
        // the final set, not one per window. Two distinct repos appear back-to-back
        // inside the debounce window; a debounce-free loop would fetch twice.
        let dir_a = tempfile::tempdir().unwrap();
        let dir_b = tempfile::tempdir().unwrap();
        github_repo(dir_a.path()); // rust-works/omni-dev → alias r0
        github_repo_with_remote(dir_b.path(), "git@github.com:rust-works/other-repo.git"); // r1
        let bin_dir = tempfile::tempdir().unwrap();
        // Both terminal, so no fast pending cadence can add a second fetch.
        let (fake, _shim, counter) = counting_fake_gh(
            bin_dir.path(),
            r#"{"data":{
                "r0":{"b0":{"target":{"oid":"a","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"}]}}},
                  "associatedPullRequests":{"nodes":[{"number":1,"isDraft":false,"url":"http://x/1"}]}}},
                "r1":{"b0":{"target":{"oid":"b","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"}]}}},
                  "associatedPullRequests":{"nodes":[{"number":2,"isDraft":false,"url":"http://x/2"}]}}}
            }}"#,
        );
        let svc = WorktreesService::new();
        // Enable polling for both before they register, so the first snapshot after
        // the storm already counts them.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.registry.set_polling("rust-works", "other-repo", true);
        // `base` far larger than the test so only the storm — never the cadence —
        // can trigger a fetch; a generous debounce so the two registers land inside
        // one settle window even on a loaded machine.
        svc.start_pr_poller_with(Duration::from_secs(30), Duration::from_millis(200), fake);
        // The burst: both windows register back-to-back.
        svc.handle(
            "register",
            json!({ "key": "a", "folders": [dir_a.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // A beat between the two, so the first bump has (all but certainly)
        // woken the poller into its settle window before the second arrives —
        // exercising the debounce *restart*, not just a single coalesced wake.
        tokio::time::sleep(Duration::from_millis(50)).await;
        svc.handle(
            "register",
            json!({ "key": "b", "folders": [dir_b.path()], "repo": "other-repo" }),
        )
        .await
        .unwrap();

        // Wait until both badges resolve — proving the single fetch covered the full
        // final set, not just the first window.
        tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                let a = svc.pr_cache.get("rust-works", "omni-dev", "main").is_some();
                let b = svc
                    .pr_cache
                    .get("rust-works", "other-repo", "main")
                    .is_some();
                if a && b {
                    return;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("the debounced fetch should resolve both repos");

        svc.shutdown().await;
        assert_eq!(
            gh_spawn_count(&counter),
            1,
            "the registration storm must collapse into exactly one fetch (#1389, fix 2)"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poll_debounce_deadline_bounds_a_steady_drip_of_changes() {
        // The settle loop is bounded: a drip of registry bumps, each landing
        // inside the debounce window, must not postpone the poll forever — the
        // overall deadline (4× the debounce) forces the snapshot mid-storm
        // (#1389, fix 2).
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim, counter) = counting_fake_gh(bin_dir.path(), "{}");
        let svc = WorktreesService::new();
        svc.registry.set_polling("rust-works", "omni-dev", true);
        // `base` far larger than the test, so only the grew-trigger — released
        // by the deadline — can fetch.
        svc.start_pr_poller_with(Duration::from_secs(30), Duration::from_millis(50), fake);
        let register = json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" });
        svc.handle("register", register.clone()).await.unwrap();
        // Re-register (an upsert, but still a bump) every 25ms — inside the
        // 50ms debounce — for well past the 200ms deadline. A deadline-free
        // loop would still be settling when the drip ends.
        for _ in 0..24 {
            tokio::time::sleep(Duration::from_millis(25)).await;
            svc.handle("register", register.clone()).await.unwrap();
        }
        let spawned_mid_drip = gh_spawn_count(&counter);
        svc.shutdown().await;
        assert!(
            spawned_mid_drip >= 1,
            "the deadline must force a fetch while the drip is still running (#1389, fix 2)"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_skips_the_immediate_fetch_when_the_warm_cache_is_fresh() {
        // #1389, fix 4: a daemon restart within the backoff window serves badges
        // from the persisted cache and spends **no** gh call, because every current
        // target already has a fresh verdict.
        let dir = tempfile::tempdir().unwrap();
        let repo = github_repo(dir.path());
        let head = repo.head().unwrap().target().unwrap().to_string();
        let bin_dir = tempfile::tempdir().unwrap();
        // If the poller wrongly fetched, this empty reply would still spawn the stub
        // and bump the counter — which is exactly what the assertion catches.
        let (fake, _shim, counter) = counting_fake_gh(bin_dir.path(), "{}");

        // Persist a fresh cache the way the previous daemon would have: a badge for
        // `main` whose verdict is about the current head (so it is not stale),
        // watched at `(main, no upstream)`, resolved just now.
        let cache_path = bin_dir.path().join("pr-cache.json");
        let target = PrTarget {
            owner: "rust-works".into(),
            name: "omni-dev".into(),
            branch: "main".into(),
        };
        let prefs = pr_cache_prefs_from(
            vec![(target, PrResolution::Pr(pending_badge(1337, &head)))],
            &[watch("main", None)],
            Utc::now(),
        );
        write_pr_cache(&cache_path, &prefs).unwrap();

        let svc = WorktreesService::new();
        svc.load_pr_cache(cache_path);
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // `base` far larger than the test: the only fetch that could happen is the
        // immediate one we expect the warm cache to skip.
        svc.start_pr_poller_with(Duration::from_secs(30), Duration::from_millis(10), fake);

        // The restored badge renders on the wire without a gh call.
        let number = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                let tree = svc.handle("tree", Value::Null).await.unwrap();
                if let Some(n) = repos_of(&tree)
                    .first()
                    .and_then(|r| r["worktrees"][0]["pr"]["number"].as_u64())
                {
                    return n;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("the restored badge should render from the warm cache");
        assert_eq!(number, 1337);

        // Let the poller run a while, then confirm it stayed quiet.
        tokio::time::sleep(Duration::from_millis(300)).await;
        svc.shutdown().await;
        assert_eq!(
            gh_spawn_count(&counter),
            0,
            "a fresh warm cache must skip the immediate re-poll (#1389, fix 4)"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_persists_fresh_verdicts_for_the_next_warm_start() {
        // #1389, fix 4, write side (the twin of the skip test above, which reads
        // a hand-written file): a successful resolve persists the cache —
        // creating the runtime dir if needed — so the *next* daemon restart
        // warm-starts from it.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"abc","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"}]}}},
                "associatedPullRequests":{"nodes":[{"number":41,"isDraft":false,"url":"u"}]}
            }}}}"#,
        );
        let svc = WorktreesService::new();
        // No file yet, and no parent dir either: the load takes the benign
        // NotFound arm, and the write must create the `0700` runtime dir.
        let cache_path = bin_dir.path().join("runtime").join("pr-cache.json");
        svc.load_pr_cache(cache_path.clone());
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        svc.start_pr_poller_with(Duration::from_millis(50), Duration::from_millis(10), fake);

        // A partially-written or not-yet-written file simply retries: only a
        // fully parseable cache ends the wait.
        let prefs = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if let Ok(bytes) = std::fs::read(&cache_path) {
                    if let Ok(prefs) = serde_json::from_slice::<PrCachePrefs>(&bytes) {
                        if !prefs.entries.is_empty() {
                            return prefs;
                        }
                    }
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("a successful resolve should persist the cache file");
        svc.shutdown().await;

        assert_eq!(prefs.entries[0].target.branch, "main");
        assert!(
            matches!(&prefs.entries[0].resolution, PersistedResolution::Pr(b) if b.number == 41),
            "{:?}",
            prefs.entries[0].resolution
        );
        assert_eq!(
            prefs.watched,
            vec![PersistedWatch {
                target: prefs.entries[0].target.clone(),
                upstream_sha: None
            }]
        );
        assert!(
            prefs.polled_at.is_some(),
            "the poll time is what ages the next warm start"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn open_prs_op_serves_from_gh_then_dedupes_within_the_ttl() {
        // #1389, fix 7: the daemon serves "Open Pull Request…" so N windows dedupe
        // to one counted `gh pr list` per repo. A generous TTL, so the second call
        // is served from the cache and spawns **no** second `gh` — the whole point.
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim, counter) = counting_fake_gh(
            bin_dir.path(),
            r#"[{"number":42,"title":"T","url":"http://x/42","headRefName":"feat",
                "baseRefName":"main","isDraft":false,"state":"OPEN","author":{"login":"me"}}]"#,
        );
        let svc = WorktreesService::new();

        let prs = svc
            .open_prs_with("rust-works", "omni-dev", fake.clone())
            .await
            .expect("gh pr list should resolve");
        assert_eq!(prs.len(), 1);
        assert_eq!(prs[0]["number"], json!(42));
        assert_eq!(prs[0]["url"], json!("http://x/42"));
        assert_eq!(gh_spawn_count(&counter), 1, "first call spends one gh");

        // A second window asking the same repo is served from the shared cache.
        let again = svc
            .open_prs_with("rust-works", "omni-dev", fake.clone())
            .await
            .expect("cache hit should resolve");
        assert_eq!(again, prs);
        assert_eq!(
            gh_spawn_count(&counter),
            1,
            "the second lookup must dedupe to the cached result, not a new gh (#1389, fix 7)"
        );

        // The op wrapper shapes the reply and validates the payload.
        let reply = svc
            .handle(
                "open-prs",
                json!({ "owner": "rust-works", "name": "omni-dev" }),
            )
            .await
            .expect("open-prs op should route");
        assert_eq!(reply["pull_requests"][0]["number"], json!(42));
        assert!(svc
            .handle("open-prs", json!({ "owner": "  ", "name": "x" }))
            .await
            .is_err());
    }

    #[test]
    fn open_pr_list_surfaces_a_missing_binary_a_failed_run_and_bad_json() {
        // The three degraded shapes a real `gh` presents — not installed, a
        // nonzero exit (auth/network), and output that is not the JSON array
        // the menu indexes into — must each be a distinct, actionable error
        // rather than a panic or a silently empty list (#1389, fix 7).
        let err = open_pr_list(Path::new("/nonexistent/gh"), "rust-works/omni-dev").unwrap_err();
        assert!(
            err.to_string().contains("is the GitHub CLI installed"),
            "{err:#}"
        );

        let bin_dir = tempfile::tempdir().unwrap();
        let _guard = shim_lock();
        let failing = bin_dir.path().join("fake-gh-fails");
        write_exec_script(&failing, "#!/bin/sh\necho 'boom' >&2\nexit 1\n");
        let err = open_pr_list(&failing, "rust-works/omni-dev").unwrap_err();
        assert!(err.to_string().contains("gh pr list failed"), "{err:#}");
        assert!(err.to_string().contains("boom"), "{err:#}");

        let object = bin_dir.path().join("fake-gh-object");
        write_exec_script(&object, "#!/bin/sh\necho '{}'\n");
        let err = open_pr_list(&object, "rust-works/omni-dev").unwrap_err();
        assert!(
            err.to_string().contains("did not return a JSON array"),
            "{err:#}"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_throttles_when_the_budget_is_over_warn() {
        // #1389, fix 6: over the ~80% warn threshold the poller holds its stretched
        // cadence and ignores even a grown watch, so no runaway can drain the shared
        // budget. A recent warm `last_poll` is seeded so the "first sight always
        // fetches" base case cannot mask the throttle — the only thing that could
        // fetch here is the grew-trigger, which the throttle suppresses.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim, counter) = counting_fake_gh(bin_dir.path(), "{}");

        let svc = WorktreesService::new();
        // Warm start with an *empty* watch but a fresh poll time: the registered
        // repo then reads as a grown watch, while `last_poll` is recent enough that
        // only the grew-trigger — not an elapsed backoff — could drive a fetch.
        *svc.pr_warm_start
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = Some(PrWarmStart {
            watched: vec![],
            polled_at: Utc::now(),
        });
        // Budget over the warn threshold before the poller starts.
        svc.rate_limit_cache.replace(RateLimitSnapshot {
            graphql: Some(rl_resource(90)),
            core: Some(rl_resource(3)),
            search: None,
        });
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // `base` far larger than the test, so a fetch could only come from the
        // grew-trigger the throttle is meant to suppress.
        svc.start_pr_poller_with(Duration::from_secs(30), Duration::from_millis(10), fake);

        // Let the poller wake on the registration and run a while.
        tokio::time::sleep(Duration::from_millis(300)).await;
        svc.shutdown().await;
        assert_eq!(
            gh_spawn_count(&counter),
            0,
            "over WARN_PERCENT the poller must not fetch a grown watch (#1389, fix 6)"
        );
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_bumps_only_when_a_verdict_actually_moves() {
        // The diff-and-drop contract: an unchanged poll must not bump, or every
        // window re-renders on every tick — the cost this design exists to avoid.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"abc","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"IN_PROGRESS","conclusion":null}
                ]}}},
                "associatedPullRequests":{"nodes":[{"number":1,"isDraft":false,"url":"u"}]}
            }}}}"#,
        );
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.start_pr_poller_with(
            Duration::from_millis(50),
            Duration::from_millis(10),
            fake.clone(),
        );

        tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if svc.pr_cache.get("rust-works", "omni-dev", "main").is_some() {
                    return;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("poller should resolve a badge through the fake gh");
        // The fake always answers identically, so after the first resolve every
        // subsequent poll is a no-change and must leave the generation alone.
        let settled = svc.registry.change_generation();
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert_eq!(
            svc.registry.change_generation(),
            settled,
            "an unchanged poll must not bump the change-notify"
        );
        svc.shutdown().await;
    }

    #[tokio::test]
    // Holds the shim guard across awaits; see the note above.
    #[allow(clippy::await_holding_lock)]
    async fn pr_poller_resolves_a_negative_through_gh_and_bumps_once() {
        // The negative twin of `pr_poller_bumps_only_when_a_verdict_actually_moves`
        // (#1370): a PR-less branch resolves to NoPr end-to-end, reaches the wire
        // as `pr_none`, and — since the answer never changes — bumps the
        // change-notify only for the poll that first delivered it.
        let dir = tempfile::tempdir().unwrap();
        github_repo(dir.path());
        let bin_dir = tempfile::tempdir().unwrap();
        let (fake, _shim) = fake_gh(
            bin_dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"abc","statusCheckRollup":null},
                "associatedPullRequests":{"nodes":[]}
            }}}}"#,
        );
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w", "folders": [dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        // Polling defaults off (#1376): enable it for this repo so the poller/fold
        // act on it, as if the user had toggled it on.
        svc.registry.set_polling("rust-works", "omni-dev", true);
        svc.start_pr_poller_with(
            Duration::from_millis(50),
            Duration::from_millis(10),
            fake.clone(),
        );

        tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if svc.pr_cache.get("rust-works", "omni-dev", "main") == Some(PrResolution::NoPr) {
                    return;
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .expect("poller should resolve the negative through the fake gh");

        // The negative reaches the wire the windows actually read.
        let wt = &repos_of(&svc.handle("tree", Value::Null).await.unwrap())[0]["worktrees"][0];
        assert_eq!(wt["pr_none"], json!(true));
        assert!(wt.get("pr").is_none(), "{wt:?}");

        // Identical re-polls of the same negative must not bump.
        let settled = svc.registry.change_generation();
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert_eq!(
            svc.registry.change_generation(),
            settled,
            "an unchanged negative must not bump the change-notify"
        );
        svc.shutdown().await;
    }

    #[test]
    fn sync_indicator_formats_only_with_upstream() {
        assert_eq!(sync_indicator(Some(2), Some(1)).as_deref(), Some("(+2 -1)"));
        assert_eq!(sync_indicator(Some(0), Some(0)).as_deref(), Some("(+0 -0)"));
        assert_eq!(sync_indicator(None, None), None);
        // A partial pair (no real upstream) yields nothing.
        assert_eq!(sync_indicator(Some(1), None), None);
    }

    #[tokio::test]
    async fn list_enriches_entries_with_git_status() {
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [dir.path()], "repo": "r" }),
        )
        .await
        .unwrap();
        let payload = svc.handle("list", Value::Null).await.unwrap();
        let windows = windows_of(&payload);
        assert_eq!(windows.len(), 1);
        assert_eq!(
            windows[0].get("branch").and_then(Value::as_str),
            Some("main")
        );
        // No upstream configured → the ahead/behind keys are absent, not zero.
        assert!(windows[0].get("ahead").is_none());
        assert!(windows[0].get("behind").is_none());
        // The main repo name is enriched onto the entry.
        assert_eq!(
            windows[0].get("main_repo").and_then(Value::as_str),
            dir.path().file_name().and_then(|n| n.to_str())
        );

        // A non-repo folder is still listed, just without a branch or main repo.
        let plain = tempfile::tempdir().unwrap();
        svc.handle(
            "register",
            json!({ "key": "w2", "folders": [plain.path()], "repo": "plain" }),
        )
        .await
        .unwrap();
        let windows = windows_of(&svc.handle("list", Value::Null).await.unwrap()).clone();
        let w2 = windows
            .iter()
            .find(|w| w.get("key").and_then(Value::as_str) == Some("w2"))
            .unwrap();
        assert!(w2.get("branch").is_none());
        assert!(w2.get("main_repo").is_none());
    }

    #[test]
    fn window_label_prefers_git_branch_over_title() {
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        let repo_name = dir.path().file_name().unwrap().to_str().unwrap();
        let entry = WindowEntry {
            key: "k".to_string(),
            folders: vec![dir.path().to_path_buf()],
            // Both the companion `repo` and `title` are overridden by the
            // git-derived main repo name and computed branch.
            repo: Some("companion-repo".to_string()),
            title: Some("ignored title".to_string()),
            pid: None,
            last_seen: Utc::now(),
        };
        // Main checkout: `repo · branch`, and with no upstream there is no sync.
        assert_eq!(window_label(&entry), format!("{repo_name} · main"));
    }

    #[tokio::test]
    async fn list_includes_ahead_behind_for_tracking_branch() {
        let dir = tempfile::tempdir().unwrap();
        let _repo = diverging_repo(dir.path());

        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [dir.path()], "repo": "r" }),
        )
        .await
        .unwrap();
        let payload = svc.handle("list", Value::Null).await.unwrap();
        let windows = windows_of(&payload);
        // A tracking branch serializes branch plus both divergence counts.
        assert_eq!(
            windows[0].get("branch").and_then(Value::as_str),
            Some("main")
        );
        assert_eq!(windows[0].get("ahead").and_then(Value::as_u64), Some(1));
        assert_eq!(windows[0].get("behind").and_then(Value::as_u64), Some(1));
    }

    #[test]
    fn window_label_includes_sync_for_tracking_branch() {
        let dir = tempfile::tempdir().unwrap();
        let _repo = diverging_repo(dir.path());
        let repo_name = dir.path().file_name().unwrap().to_str().unwrap();
        let entry = WindowEntry {
            key: "k".to_string(),
            folders: vec![dir.path().to_path_buf()],
            repo: Some("companion-repo".to_string()),
            title: None,
            pid: None,
            last_seen: Utc::now(),
        };
        // A tracking branch appends the `(+ahead -behind)` sync indicator.
        assert_eq!(window_label(&entry), format!("{repo_name} · main (+1 -1)"));
    }

    /// Adds a linked worktree of `repo` at `wt_path` checked out on a new
    /// `branch` pointed at `base`, mirroring `git worktree add -b <branch>
    /// <wt_path>`.
    fn add_worktree(repo: &Repository, base: git2::Oid, wt_path: &Path, branch: &str) {
        let commit = repo.find_commit(base).unwrap();
        repo.branch(branch, &commit, false).unwrap();
        let reference = repo
            .find_reference(&format!("refs/heads/{branch}"))
            .unwrap();
        let mut opts = git2::WorktreeAddOptions::new();
        opts.reference(Some(&reference));
        repo.worktree(branch, wt_path, Some(&opts)).unwrap();
    }

    #[test]
    fn git_status_marks_linked_worktree_and_names_parent_repo() {
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();

        // A linked worktree checked out on a new `feature` branch, in a
        // directory whose basename is deliberately *not* the repo name.
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");

        let status = git_status(&wt_path);
        assert!(status.is_worktree);
        assert_eq!(status.branch.as_deref(), Some("feature"));
        // The worktree names its *parent* repo, not its worktree-folder basename.
        assert_eq!(
            status.main_repo.as_deref(),
            main_dir.path().file_name().and_then(|n| n.to_str())
        );

        // The main checkout resolves the same repo name and is not a worktree.
        let main_status = git_status(main_dir.path());
        assert!(!main_status.is_worktree);
        assert_eq!(main_status.main_repo, status.main_repo);
    }

    #[test]
    fn window_label_marks_worktree_with_fork_glyph() {
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");

        let repo_name = main_dir.path().file_name().unwrap().to_str().unwrap();
        let entry = WindowEntry {
            key: "k".to_string(),
            folders: vec![wt_path],
            repo: Some("feature-wt".to_string()),
            title: None,
            pid: None,
            last_seen: Utc::now(),
        };
        // A worktree line: parent repo, the fork glyph, then the branch (no
        // upstream here, so no sync suffix).
        assert_eq!(window_label(&entry), format!("{repo_name} ⑂ feature"));
    }

    #[test]
    fn main_repo_name_derives_from_common_dir() {
        // Normal layout: the repo is the directory that contains `.git`.
        assert_eq!(
            main_repo_name(Path::new("/home/me/omni-dev/.git")).as_deref(),
            Some("omni-dev")
        );
        // A trailing slash on the common dir does not change the answer.
        assert_eq!(
            main_repo_name(Path::new("/home/me/omni-dev/.git/")).as_deref(),
            Some("omni-dev")
        );
        // A bare repo: its own directory name, without the `.git` suffix.
        assert_eq!(
            main_repo_name(Path::new("/srv/git/omni-dev.git")).as_deref(),
            Some("omni-dev")
        );
        // A `.git` at the filesystem root has no parent name to use.
        assert_eq!(main_repo_name(Path::new("/.git")), None);
    }

    // --- Repo/worktree tree (#1265) ----------------------------------------

    /// Pulls the `repos` array out of a `tree` payload (owned, so it survives a
    /// temporary payload).
    fn repos_of(payload: &Value) -> Vec<Value> {
        payload
            .get("repos")
            .and_then(Value::as_array)
            .expect("repos array")
            .clone()
    }

    fn github(owner: &str, name: &str) -> Option<GithubIdentity> {
        Some(GithubIdentity {
            owner: owner.to_string(),
            name: name.to_string(),
        })
    }

    #[test]
    fn github_identity_parses_supported_forms() {
        // https / http, with and without the `.git` suffix.
        assert_eq!(
            github_identity("https://github.com/rust-works/omni-dev.git"),
            github("rust-works", "omni-dev")
        );
        assert_eq!(
            github_identity("https://github.com/rust-works/omni-dev"),
            github("rust-works", "omni-dev")
        );
        assert_eq!(github_identity("http://github.com/o/r"), github("o", "r"));
        // SCP-like and ssh:// / git:// forms.
        assert_eq!(
            github_identity("git@github.com:rust-works/omni-dev.git"),
            github("rust-works", "omni-dev")
        );
        assert_eq!(
            github_identity("ssh://git@github.com/o/r.git"),
            github("o", "r")
        );
        assert_eq!(github_identity("git://github.com/o/r"), github("o", "r"));
        // A trailing slash and surrounding whitespace are tolerated.
        assert_eq!(
            github_identity("  https://github.com/o/r/  "),
            github("o", "r")
        );
    }

    #[test]
    fn github_identity_rejects_non_github_and_malformed() {
        // Non-GitHub hosts.
        assert_eq!(github_identity("https://gitlab.com/o/r.git"), None);
        assert_eq!(github_identity("git@example.com:o/r.git"), None);
        // Missing or extra path segments.
        assert_eq!(github_identity("https://github.com/onlyowner"), None);
        assert_eq!(github_identity("https://github.com/o/r/extra"), None);
        assert_eq!(github_identity("https://github.com/"), None);
        // Not a URL at all.
        assert_eq!(github_identity("not a url"), None);
    }

    #[test]
    fn remote_github_identity_reads_origin_then_falls_back() {
        let dir = tempfile::tempdir().unwrap();
        let repo = init_repo(dir.path());
        // No remotes → None.
        assert_eq!(remote_github_identity(&repo), None);
        // A non-GitHub origin is not a match.
        repo.remote("origin", "https://gitlab.com/o/r.git").unwrap();
        assert_eq!(remote_github_identity(&repo), None);
        // A GitHub origin resolves to its identity.
        repo.remote_set_url("origin", "git@github.com:rust-works/omni-dev.git")
            .unwrap();
        assert_eq!(
            remote_github_identity(&repo),
            github("rust-works", "omni-dev")
        );

        // Origin non-GitHub but another remote is GitHub: the fallback loop over
        // the remaining remotes finds it.
        repo.remote_set_url("origin", "https://gitlab.com/o/r.git")
            .unwrap();
        repo.remote("upstream", "https://github.com/other/proj.git")
            .unwrap();
        assert_eq!(remote_github_identity(&repo), github("other", "proj"));
    }

    #[tokio::test]
    async fn tree_is_empty_with_no_windows_and_skips_non_repos() {
        let svc = WorktreesService::new();
        // No windows → an empty repo set (not an error), toggle at its default.
        assert_eq!(
            svc.handle("tree", Value::Null).await.unwrap(),
            json!({ "repos": [], "show_closed": true })
        );
        // A plain non-repo folder is skipped rather than sinking the op.
        let plain = tempfile::tempdir().unwrap();
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [plain.path()], "repo": "plain" }),
        )
        .await
        .unwrap();
        assert!(repos_of(&svc.handle("tree", Value::Null).await.unwrap()).is_empty());
    }

    #[tokio::test]
    async fn tree_enumerates_main_and_linked_with_open_join_and_github() {
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        // A GitHub origin so the repo carries an identity in the payload.
        repo.remote("origin", "git@github.com:rust-works/omni-dev.git")
            .unwrap();

        // A linked worktree on a new `feature` branch, in a directory whose
        // basename is deliberately not the repo name.
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");

        let svc = WorktreesService::new();
        // A window open on the main checkout and one on the linked worktree —
        // two windows, but one repo (they must dedupe).
        svc.handle(
            "register",
            json!({ "key": "wm", "folders": [main_dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();
        svc.handle(
            "register",
            json!({ "key": "wf", "folders": [wt_path], "repo": "feature-wt" }),
        )
        .await
        .unwrap();

        let repos = repos_of(&svc.handle("tree", Value::Null).await.unwrap());
        assert_eq!(
            repos.len(),
            1,
            "two worktrees of one repo dedupe: {repos:?}"
        );
        let repo0 = &repos[0];
        // Repo identity is the parent-repo name (not a worktree-folder basename).
        assert_eq!(
            repo0.get("main_repo").and_then(Value::as_str),
            main_dir.path().file_name().and_then(|n| n.to_str())
        );
        assert_eq!(
            repo0.pointer("/github/owner").and_then(Value::as_str),
            Some("rust-works")
        );
        assert_eq!(
            repo0.pointer("/github/name").and_then(Value::as_str),
            Some("omni-dev")
        );
        assert!(repo0.get("root").and_then(Value::as_str).is_some());

        let worktrees = repo0.get("worktrees").and_then(Value::as_array).unwrap();
        assert_eq!(worktrees.len(), 2);
        // Main working tree first: is_main, open, with the main window's key.
        let main_wt = &worktrees[0];
        assert_eq!(main_wt.get("is_main").and_then(Value::as_bool), Some(true));
        assert_eq!(main_wt.get("open").and_then(Value::as_bool), Some(true));
        assert_eq!(
            main_wt.get("window_key").and_then(Value::as_str),
            Some("wm")
        );
        assert_eq!(main_wt.get("branch").and_then(Value::as_str), Some("main"));
        // Linked worktree: not main, open via the feature window.
        let linked = &worktrees[1];
        assert_eq!(linked.get("is_main").and_then(Value::as_bool), Some(false));
        assert_eq!(linked.get("open").and_then(Value::as_bool), Some(true));
        assert_eq!(linked.get("window_key").and_then(Value::as_str), Some("wf"));
        assert_eq!(
            linked.get("branch").and_then(Value::as_str),
            Some("feature")
        );
    }

    #[tokio::test]
    async fn tree_marks_unopened_linked_worktree_closed_and_omits_github() {
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/main"), &[], "A");
        repo.set_head("refs/heads/main").unwrap();
        // No remote at all → the repo carries no `github` identity.
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");

        let svc = WorktreesService::new();
        // Only the main checkout has a window; the linked worktree has none.
        svc.handle(
            "register",
            json!({ "key": "wm", "folders": [main_dir.path()], "repo": "omni-dev" }),
        )
        .await
        .unwrap();

        let repos = repos_of(&svc.handle("tree", Value::Null).await.unwrap());
        assert_eq!(repos.len(), 1);
        assert!(repos[0].get("github").is_none(), "no remote → no github");
        let worktrees = repos[0].get("worktrees").and_then(Value::as_array).unwrap();
        let linked = worktrees
            .iter()
            .find(|w| w.get("is_main").and_then(Value::as_bool) == Some(false))
            .expect("the linked worktree");
        // Enumerated even though no window has it open, and marked closed.
        assert_eq!(linked.get("open").and_then(Value::as_bool), Some(false));
        assert!(linked.get("window_key").is_none());
    }

    // --- Close op (#1277) --------------------------------------------------

    /// Builds a repo whose main working tree is on `trunk` with one **clean**
    /// linked worktree on `feature`, returning the temp dirs (kept alive so the
    /// paths stay valid) and the linked worktree path.
    fn repo_with_linked_worktree() -> (tempfile::TempDir, tempfile::TempDir, PathBuf) {
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/trunk"), &[], "A");
        repo.set_head("refs/heads/trunk").unwrap();
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");
        (main_dir, wt_parent, wt_path)
    }

    /// [`repo_with_linked_worktree`] with a **second** linked worktree of the same
    /// repo — the shape a multi-select delete fans out over, and the only one where
    /// two prunes share a `.git/worktrees` to race on (#1359).
    fn repo_with_two_linked_worktrees() -> (tempfile::TempDir, tempfile::TempDir, PathBuf, PathBuf)
    {
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/trunk"), &[], "A");
        repo.set_head("refs/heads/trunk").unwrap();
        let wt_parent = tempfile::tempdir().unwrap();
        let first = wt_parent.path().join("first-wt");
        let second = wt_parent.path().join("second-wt");
        add_worktree(&repo, a, &first, "first");
        add_worktree(&repo, a, &second, "second");
        (main_dir, wt_parent, first, second)
    }

    #[tokio::test]
    async fn close_removes_two_linked_worktrees_of_one_repo_concurrently() {
        let (main_dir, _wtp, first, second) = repo_with_two_linked_worktrees();
        let svc = Arc::new(WorktreesService::new());

        // The multi-select fan-out: one `close` op per target, both in flight at
        // once against the one repo's shared admin state. Genuinely concurrent
        // even on this single-threaded runtime — each op's prune is a
        // `spawn_blocking`, so awaiting its join yields to the other op.
        //
        // This guards the fan-out end-to-end (both ops complete, neither is
        // starved or deadlocked by `prune_lock`); it is deliberately *not* sold as
        // a race detector for the lock, because it is not one — it passes with the
        // guard removed, the two prunes being far too quick to collide reliably.
        let close = |path: PathBuf| {
            let svc = svc.clone();
            async move {
                svc.handle(
                    "close",
                    json!({ "path": path, "remove": true, "confirmed": true }),
                )
                .await
            }
        };
        let (a, b) = tokio::join!(close(first.clone()), close(second.clone()));

        assert_eq!(a.unwrap(), json!({ "removed": true }));
        assert_eq!(b.unwrap(), json!({ "removed": true }));
        assert!(!first.exists());
        assert!(!second.exists());
        // Both *admin* entries pruned too, not merely the directories — the half
        // the two ops contend on.
        let repo = Repository::open(main_dir.path()).unwrap();
        assert!(repo.worktrees().unwrap().is_empty());
    }

    #[tokio::test]
    async fn concurrent_closes_overlap_their_heartbeat_waits() {
        let (_main, _wtp, first, second) = repo_with_two_linked_worktrees();
        let svc = Arc::new(WorktreesService::new());
        // Two *different* windows own the two targets — the multi-select shape.
        for (key, path) in [("w2", &first), ("w3", &second)] {
            svc.handle("register", json!({ "key": key, "folders": [path] }))
                .await
                .unwrap();
        }

        let spawn_close = |path: PathBuf| {
            let svc = svc.clone();
            tokio::spawn(async move {
                svc.handle(
                    "close",
                    json!({
                        "path": path,
                        "remove": true,
                        "confirmed": true,
                        "requester_key": "w1",
                    }),
                )
                .await
            })
        };
        let a = spawn_close(first.clone());
        let b = spawn_close(second.clone());

        // The crux of #1359, and the one thing pinning `prune_lock`'s placement:
        // *both* windows are told to close while *neither* op has finished, so the
        // two multi-second heartbeat waits are in flight at once. Take the guard
        // before `await_windows_closed` instead of after and this fails — op B
        // would sit on the lock without ever marking w3, restoring exactly the
        // N-stacked-waits latency the fan-out exists to remove.
        for key in ["w2", "w3"] {
            let mut saw_close = false;
            for _ in 0..400 {
                let hb = svc
                    .handle("heartbeat", json!({ "key": key }))
                    .await
                    .unwrap();
                if hb.get("close").and_then(Value::as_bool) == Some(true) {
                    saw_close = true;
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
            assert!(saw_close, "{key} should have been told to close while the other target's close was still waiting");
        }
        assert!(
            !a.is_finished() && !b.is_finished(),
            "neither close can have finished: both windows are still registered"
        );

        // Both windows close; both ops then remove.
        for key in ["w2", "w3"] {
            svc.handle("unregister", json!({ "key": key }))
                .await
                .unwrap();
        }
        assert_eq!(a.await.unwrap().unwrap(), json!({ "removed": true }));
        assert_eq!(b.await.unwrap().unwrap(), json!({ "removed": true }));
        assert!(!first.exists());
        assert!(!second.exists());
    }

    #[tokio::test]
    async fn close_safety_check_reports_clean_linked_as_removable_with_no_risks() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        // Phase 1 (confirmed absent) on a clean linked worktree: removable, not
        // main, no risks → the extension proceeds with no dialog.
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        assert_eq!(report.get("removable").and_then(Value::as_bool), Some(true));
        assert_eq!(report.get("is_main").and_then(Value::as_bool), Some(false));
        assert_eq!(report.get("open").and_then(Value::as_bool), Some(false));
        assert!(report
            .get("risks")
            .and_then(Value::as_array)
            .unwrap()
            .is_empty());
        // No side effects: the worktree still exists.
        assert!(wt_path.exists());
    }

    #[tokio::test]
    async fn close_removes_a_clean_linked_worktree() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        let reply = svc
            .handle(
                "close",
                json!({ "path": wt_path, "remove": true, "confirmed": true }),
            )
            .await
            .unwrap();
        assert_eq!(reply, json!({ "removed": true }));
        assert!(
            !wt_path.exists(),
            "the worktree directory should be deleted"
        );
    }

    #[test]
    fn remove_worktree_deletes_the_directory_and_prunes_the_admin_metadata() {
        // The reorder (#1315) must still fully remove a worktree: both the
        // checked-out directory *and* the admin metadata git tracks it by, so it
        // no longer appears in `Repository::worktrees()`.
        let (main, _wtp, wt_path) = repo_with_linked_worktree();
        let admin = main.path().join(".git").join("worktrees").join("feature");
        assert!(admin.exists(), "admin metadata should exist before removal");

        remove_worktree(&wt_path).unwrap();

        assert!(!wt_path.exists(), "the working directory should be gone");
        assert!(!admin.exists(), "the admin metadata should be pruned");
        let main_repo = Repository::open(main.path()).unwrap();
        assert_eq!(
            main_repo.worktrees().unwrap().len(),
            0,
            "git should no longer track the worktree"
        );
    }

    #[test]
    fn remove_worktree_recovers_a_half_removed_orphan() {
        // The exact #1315 leftover: the old ordering deleted the admin metadata
        // first, then failed to rmdir the working tree, orphaning the directory
        // with a dangling `.git` gitlink. `remove_worktree` must clean it up
        // rather than error with "not a git worktree".
        let (main, _wtp, wt_path) = repo_with_linked_worktree();
        let admin = main.path().join(".git").join("worktrees").join("feature");
        // Simulate the half-removed state: admin gone, directory (+gitlink) left.
        std::fs::remove_dir_all(&admin).unwrap();
        assert!(wt_path.join(".git").is_file(), "dangling gitlink remains");
        assert!(
            Repository::open(&wt_path).is_err(),
            "the orphan should not open as a repo"
        );

        remove_worktree(&wt_path).unwrap();
        assert!(
            !wt_path.exists(),
            "the leftover directory should be removed"
        );
    }

    #[test]
    fn is_orphaned_worktree_only_matches_a_dangling_linked_gitlink() {
        let (main, _wtp, wt_path) = repo_with_linked_worktree();
        // A live worktree: gitlink resolves → not an orphan.
        assert!(!is_orphaned_worktree(&wt_path));
        // The main checkout has a `.git` directory → not an orphan.
        assert!(!is_orphaned_worktree(main.path()));
        // Drop the admin metadata → the gitlink now dangles → orphan.
        std::fs::remove_dir_all(main.path().join(".git").join("worktrees").join("feature"))
            .unwrap();
        assert!(is_orphaned_worktree(&wt_path));
    }

    #[test]
    fn remove_dir_all_retrying_is_idempotent_on_a_missing_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let missing = tmp.path().join("gone");
        assert!(remove_dir_all_retrying(&missing).is_ok());
    }

    #[test]
    fn is_transient_rmdir_error_matches_only_the_repopulated_directory_race() {
        use std::io::Error;
        for errno in [nix::libc::ENOTEMPTY, nix::libc::EEXIST, nix::libc::EBUSY] {
            assert!(
                is_transient_rmdir_error(&Error::from_raw_os_error(errno)),
                "errno {errno} is the concurrent-writer race and must be retried"
            );
        }
        // A hard failure must surface immediately rather than burn the backoff
        // waiting for a condition that will never clear.
        for errno in [
            nix::libc::EACCES,
            nix::libc::EPERM,
            nix::libc::EROFS,
            nix::libc::ENOTDIR,
        ] {
            assert!(
                !is_transient_rmdir_error(&Error::from_raw_os_error(errno)),
                "errno {errno} is permanent and must not be retried"
            );
        }
        // Not from the OS at all, so there is no errno to classify.
        assert!(!is_transient_rmdir_error(&Error::other("synthetic")));
    }

    #[test]
    fn remove_dir_all_retrying_surfaces_a_non_transient_error_without_retrying() {
        // Removing a *file* as if it were a directory fails with ENOTDIR: not the
        // race, so it must fail on the first attempt with the original cause
        // attached, leaving the path untouched.
        let tmp = tempfile::tempdir().unwrap();
        let file = tmp.path().join("not-a-directory");
        std::fs::write(&file, b"x").unwrap();

        let mut attempts = 0;
        let err = remove_dir_all_retrying_with(&file, WORKTREE_RMDIR_BACKOFF, || {
            attempts += 1;
            std::fs::remove_dir_all(&file)
        })
        .unwrap_err();

        assert_eq!(attempts, 1, "a permanent error must not be retried");
        assert!(
            err.to_string()
                .contains("failed to remove worktree directory"),
            "unexpected error: {err:#}"
        );
        assert!(err.source().is_some(), "the io::Error cause is preserved");
        assert!(file.exists());
    }

    #[test]
    fn remove_dir_all_retrying_gives_up_after_the_backoff_is_exhausted() {
        // A writer that never quiesces: every sweep re-finds the directory
        // populated. Once the schedule runs out the ENOTEMPTY must surface rather
        // than the loop spinning forever.
        let tmp = tempfile::tempdir().unwrap();
        let mut attempts = 0;
        let backoff = [Duration::ZERO, Duration::ZERO];
        let err = remove_dir_all_retrying_with(tmp.path(), &backoff, || {
            attempts += 1;
            Err(std::io::Error::from_raw_os_error(nix::libc::ENOTEMPTY))
        })
        .unwrap_err();

        // One attempt per delay, plus the initial one.
        assert_eq!(attempts, backoff.len() + 1);
        assert!(
            err.to_string()
                .contains("failed to remove worktree directory"),
            "unexpected error: {err:#}"
        );
    }

    #[test]
    fn remove_dir_all_retrying_succeeds_once_the_writer_quiesces() {
        // The #1315 happy path, deterministically: the race clears partway through
        // the schedule and the removal then succeeds.
        let tmp = tempfile::tempdir().unwrap();
        let mut attempts = 0;
        let result = remove_dir_all_retrying_with(tmp.path(), WORKTREE_RMDIR_BACKOFF, || {
            attempts += 1;
            if attempts < 3 {
                Err(std::io::Error::from_raw_os_error(nix::libc::ENOTEMPTY))
            } else {
                Ok(())
            }
        });
        assert!(result.is_ok(), "{result:?}");
        assert_eq!(attempts, 3);
    }

    #[test]
    fn is_orphaned_worktree_ignores_a_git_file_that_is_not_a_gitlink() {
        // A `.git` file that is readable but carries no `gitdir:` pointer is not
        // something we may delete.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join(".git"), b"not a gitlink\n").unwrap();
        assert!(!is_orphaned_worktree(tmp.path()));
    }

    #[test]
    fn remove_worktree_rejects_a_path_that_is_not_a_worktree() {
        // Neither a repo nor an orphan: refuse it rather than recursively deleting
        // whatever directory was passed in.
        let tmp = tempfile::tempdir().unwrap();
        let plain = tmp.path().join("plain");
        std::fs::create_dir(&plain).unwrap();

        let err = remove_worktree(&plain).unwrap_err();

        assert!(
            err.to_string().contains("not a git worktree"),
            "unexpected error: {err:#}"
        );
        assert!(plain.exists(), "a non-worktree path must be left alone");
    }

    #[test]
    fn remove_worktree_succeeds_while_a_concurrent_writer_winds_down() {
        // Acceptance criterion (#1315): a language server / cargo still writing
        // into `target/` as the window closes makes the recursive rmdir race with
        // "Directory not empty". A background thread reproduces that by
        // repopulating `target/` for a bounded window; removal must retry past it
        // and still succeed once the writer stops.
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;

        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let target = wt_path.join("target");
        std::fs::create_dir_all(&target).unwrap();

        let stop = Arc::new(AtomicBool::new(false));
        let writer_stop = Arc::clone(&stop);
        let writer_dir = target;
        let writer = std::thread::spawn(move || {
            let mut n = 0u64;
            // Churn hard for ~400ms (well under the ~2.75s retry budget), then
            // stop so a later removal pass finds the directory quiescent.
            let deadline = std::time::Instant::now() + Duration::from_millis(400);
            while !writer_stop.load(Ordering::Relaxed) && std::time::Instant::now() < deadline {
                let nested = writer_dir.join("nested");
                // Best-effort: the parent may be mid-deletion — ignore failures.
                let _ = std::fs::create_dir_all(&nested);
                let _ = std::fs::write(nested.join(format!("artifact-{n}.tmp")), b"x");
                n += 1;
            }
        });

        let result = remove_worktree(&wt_path);
        stop.store(true, Ordering::Relaxed);
        writer.join().unwrap();

        assert!(
            result.is_ok(),
            "removal should retry past the writer: {result:?}"
        );
        assert!(!wt_path.exists(), "the worktree directory should be gone");
    }

    #[tokio::test]
    async fn close_safety_check_flags_untracked_and_does_not_remove_without_confirmation() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        // An untracked file in the worktree would be lost on removal.
        std::fs::write(wt_path.join("scratch.txt"), b"work in progress").unwrap();

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        let risks = report.get("risks").and_then(Value::as_array).unwrap();
        assert!(
            risks
                .iter()
                .any(|r| r.get("kind").and_then(Value::as_str) == Some("untracked")),
            "expected an untracked risk: {report}"
        );
        // Still removable — the risk only means "confirm first", not "refuse".
        assert_eq!(report.get("removable").and_then(Value::as_bool), Some(true));
        // The unconfirmed check has no side effects.
        assert!(wt_path.exists());
    }

    #[tokio::test]
    async fn close_confirmed_removes_a_dirty_worktree() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        std::fs::write(wt_path.join("scratch.txt"), b"discard me").unwrap();
        let svc = WorktreesService::new();
        // With confirmation, the risks are overridden and removal proceeds.
        let reply = svc
            .handle(
                "close",
                json!({ "path": wt_path, "remove": true, "confirmed": true }),
            )
            .await
            .unwrap();
        assert_eq!(reply, json!({ "removed": true }));
        assert!(!wt_path.exists());
    }

    #[tokio::test]
    async fn close_refuses_to_remove_the_main_working_tree() {
        let (main, _wtp, _wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        // Phase 1: the main tree reports not-removable, marked main.
        let report = svc
            .handle("close", json!({ "path": main.path(), "remove": true }))
            .await
            .unwrap();
        assert_eq!(report.get("is_main").and_then(Value::as_bool), Some(true));
        assert_eq!(
            report.get("removable").and_then(Value::as_bool),
            Some(false)
        );
        // Phase 2: even a confirmed delete of the main tree is refused
        // defensively, and the directory is untouched.
        assert!(svc
            .handle(
                "close",
                json!({ "path": main.path(), "remove": true, "confirmed": true }),
            )
            .await
            .is_err());
        assert!(main.path().exists());
    }

    #[tokio::test]
    async fn close_removes_a_linked_worktree_on_the_default_branch_and_keeps_the_branch() {
        // The case a naive impl would wrongly protect: a linked worktree checked
        // out on `main` (the default branch) is *still a linked worktree*, so it
        // is fully deletable — and `main` survives (removal never deletes a branch).
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/trunk"), &[], "A");
        repo.set_head("refs/heads/trunk").unwrap();
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("main-wt");
        add_worktree(&repo, a, &wt_path, "main");

        let svc = WorktreesService::new();
        let reply = svc
            .handle(
                "close",
                json!({ "path": wt_path, "remove": true, "confirmed": true }),
            )
            .await
            .unwrap();
        assert_eq!(reply, json!({ "removed": true }));
        assert!(!wt_path.exists());
        // The `main` branch is untouched by the worktree removal.
        assert!(
            repo.find_branch("main", git2::BranchType::Local).is_ok(),
            "the default branch must survive worktree removal"
        );
    }

    #[tokio::test]
    async fn close_is_idempotent_when_the_worktree_is_already_gone() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        // First removal succeeds.
        svc.handle(
            "close",
            json!({ "path": wt_path, "remove": true, "confirmed": true }),
        )
        .await
        .unwrap();
        // A second confirmed close of the now-missing path is a clean success,
        // not an error (a stale snapshot must not crash).
        let reply = svc
            .handle(
                "close",
                json!({ "path": wt_path, "remove": true, "confirmed": true }),
            )
            .await
            .unwrap();
        assert_eq!(reply, json!({ "removed": true }));
    }

    #[tokio::test]
    async fn close_safety_check_detects_detached_head_unreachable_commits() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        // In the worktree, commit onto a detached HEAD so the new commit is
        // reachable from no ref — it would be GC'd on removal.
        let wt_repo = Repository::open(&wt_path).unwrap();
        let parent_oid = wt_repo.head().unwrap().target().unwrap();
        let parent = wt_repo.find_commit(parent_oid).unwrap();
        let orphan = empty_commit(&wt_repo, None, &[&parent], "orphan");
        wt_repo.set_head_detached(orphan).unwrap();

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        let risks = report.get("risks").and_then(Value::as_array).unwrap();
        assert!(
            risks
                .iter()
                .any(|r| r.get("kind").and_then(Value::as_str) == Some("unreachable-commits")),
            "expected an unreachable-commits risk: {report}"
        );
    }

    #[tokio::test]
    async fn close_self_close_removes_when_the_requester_owns_the_target() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        // The requesting window itself has the worktree open: it is the only
        // owning window, so there is nothing to wait on — remove and reply, and
        // the extension closes its own window on `ok`.
        svc.handle(
            "register",
            json!({ "key": "w1", "folders": [wt_path], "repo": "feature-wt" }),
        )
        .await
        .unwrap();
        let reply = svc
            .handle(
                "close",
                json!({
                    "path": wt_path,
                    "remove": true,
                    "confirmed": true,
                    "requester_key": "w1",
                }),
            )
            .await
            .unwrap();
        assert_eq!(reply, json!({ "removed": true }));
        assert!(!wt_path.exists());
    }

    #[tokio::test]
    async fn close_safety_check_surfaces_the_owning_window() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        // A multi-root window owns the target: the report surfaces its key and
        // folder count so the extension can warn "all N folders will close".
        svc.handle(
            "register",
            json!({ "key": "w2", "folders": [&wt_path, "/tmp/other"], "repo": "feature-wt" }),
        )
        .await
        .unwrap();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        assert_eq!(report.get("open").and_then(Value::as_bool), Some(true));
        assert_eq!(report.get("window_key").and_then(Value::as_str), Some("w2"));
        assert_eq!(
            report.get("window_folder_count").and_then(Value::as_u64),
            Some(2)
        );
    }

    #[tokio::test]
    async fn heartbeat_op_surfaces_a_pending_close_directive_once() {
        let svc = WorktreesService::new();
        svc.handle("register", register_payload("w1", Some("r"), "/tmp/a"))
            .await
            .unwrap();
        // No directive → a plain `{ known: true }`, byte-identical to before.
        assert_eq!(
            svc.handle("heartbeat", json!({ "key": "w1" }))
                .await
                .unwrap(),
            json!({ "known": true })
        );
        // Marked → the next heartbeat carries `close: true`, exactly once.
        svc.registry.mark_close_pending("w1");
        assert_eq!(
            svc.handle("heartbeat", json!({ "key": "w1" }))
                .await
                .unwrap(),
            json!({ "known": true, "close": true })
        );
        assert_eq!(
            svc.handle("heartbeat", json!({ "key": "w1" }))
                .await
                .unwrap(),
            json!({ "known": true })
        );
    }

    #[tokio::test]
    async fn close_signals_a_cross_window_target_then_removes_after_it_closes() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = Arc::new(WorktreesService::new());
        // A *different* window (not the requester) owns the target.
        svc.handle(
            "register",
            json!({ "key": "w2", "folders": [&wt_path], "repo": "feature-wt" }),
        )
        .await
        .unwrap();

        // Drive the destructive close concurrently: it marks w2 to close and
        // waits for it to unregister before removing.
        let svc2 = svc.clone();
        let path = wt_path.clone();
        let close = tokio::spawn(async move {
            svc2.handle(
                "close",
                json!({
                    "path": path,
                    "remove": true,
                    "confirmed": true,
                    "requester_key": "w1",
                }),
            )
            .await
        });

        // Simulate w2's extension: its next heartbeat sees `close: true`, so it
        // closes its window and unregisters. Poll until the directive appears.
        let mut saw_close = false;
        for _ in 0..200 {
            let hb = svc
                .handle("heartbeat", json!({ "key": "w2" }))
                .await
                .unwrap();
            if hb.get("close").and_then(Value::as_bool) == Some(true) {
                saw_close = true;
                svc.handle("unregister", json!({ "key": "w2" }))
                    .await
                    .unwrap();
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        assert!(saw_close, "w2 should have been told to close");

        // Once w2 has unregistered, the close op removes the worktree.
        let reply = close.await.unwrap().unwrap();
        assert_eq!(reply, json!({ "removed": true }));
        assert!(!wt_path.exists());
    }

    #[tokio::test]
    async fn await_windows_closed_times_out_when_a_window_never_closes() {
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        svc.handle(
            "register",
            json!({ "key": "w2", "folders": [&wt_path], "repo": "feature-wt" }),
        )
        .await
        .unwrap();
        // The owning window never unregisters: the wait gives up (with a short
        // timeout here) rather than block, and names the still-open window.
        let err = await_windows_closed(
            &svc.registry,
            &wt_path,
            Some("w1"),
            Duration::from_millis(150),
            Duration::from_millis(25),
        )
        .await
        .unwrap_err();
        assert!(
            err.to_string().contains("w2"),
            "error names the window: {err}"
        );
        // The requester itself is excluded, so a self-only owner returns at once.
        await_windows_closed(
            &svc.registry,
            &wt_path,
            Some("w2"),
            Duration::from_millis(150),
            Duration::from_millis(25),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn close_window_without_remove_replies_closed_and_never_deletes() {
        let (main, _wtp, _wt_path) = repo_with_linked_worktree();
        let svc = WorktreesService::new();
        // "Close Window" on the main tree: no git inspection, no removal.
        let reply = svc
            .handle("close", json!({ "path": main.path(), "remove": false }))
            .await
            .unwrap();
        assert_eq!(reply, json!({ "closed": true }));
        assert!(main.path().exists());
    }

    #[tokio::test]
    async fn close_safety_check_flags_modified_tracked_files() {
        // A tracked file, checked out into the linked worktree, then modified —
        // its content is lost on removal, so it is a `dirty` risk (distinct from
        // the untracked case).
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = commit_file(&repo, "refs/heads/trunk", "tracked.txt", b"original\n", "A");
        repo.set_head("refs/heads/trunk").unwrap();
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");
        std::fs::write(wt_path.join("tracked.txt"), b"uncommitted change\n").unwrap();

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        let risks = report.get("risks").and_then(Value::as_array).unwrap();
        assert!(
            risks
                .iter()
                .any(|r| r.get("kind").and_then(Value::as_str) == Some("dirty")),
            "expected a dirty risk: {report}"
        );
    }

    #[tokio::test]
    async fn close_safety_check_flags_an_in_progress_operation() {
        // Plant a MERGE_HEAD in the worktree's gitdir so `repo.state()` reports a
        // non-Clean (interrupted merge) state — its progress is lost on removal.
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let wt_repo = Repository::open(&wt_path).unwrap();
        let head = wt_repo.head().unwrap().target().unwrap();
        std::fs::write(wt_repo.path().join("MERGE_HEAD"), format!("{head}\n")).unwrap();
        assert_ne!(wt_repo.state(), RepositoryState::Clean);

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        let risks = report.get("risks").and_then(Value::as_array).unwrap();
        assert!(
            risks
                .iter()
                .any(|r| r.get("kind").and_then(Value::as_str) == Some("in-progress")),
            "expected an in-progress risk: {report}"
        );
    }

    #[tokio::test]
    async fn close_safety_check_reports_unpushed_commits_as_info_not_a_risk() {
        // A linked worktree on `feature`, which tracks `origin/feature` and is one
        // commit ahead. The unpushed commit is INFO (the branch — and thus the
        // commit — survives removal), never a blocking risk.
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = empty_commit(&repo, Some("refs/heads/trunk"), &[], "A");
        repo.set_head("refs/heads/trunk").unwrap();
        let a_commit = repo.find_commit(a).unwrap();
        repo.branch("feature", &a_commit, false).unwrap();
        repo.reference("refs/remotes/origin/feature", a, true, "origin feature")
            .unwrap();
        // `feature` advances one commit past `origin/feature`.
        empty_commit(&repo, Some("refs/heads/feature"), &[&a_commit], "B");
        drop(a_commit);
        let mut cfg = repo.config().unwrap();
        cfg.set_str("remote.origin.url", "https://example.invalid/x.git")
            .unwrap();
        cfg.set_str("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")
            .unwrap();
        cfg.set_str("branch.feature.remote", "origin").unwrap();
        cfg.set_str("branch.feature.merge", "refs/heads/feature")
            .unwrap();
        // A worktree on the existing `feature` branch (not created fresh, so it
        // keeps the ahead-of-upstream divergence).
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        let reference = repo.find_reference("refs/heads/feature").unwrap();
        let mut opts = git2::WorktreeAddOptions::new();
        opts.reference(Some(&reference));
        repo.worktree("feature", &wt_path, Some(&opts)).unwrap();

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        // Unpushed commits appear as `info`, and the worktree is still cleanly
        // removable with no blocking risks.
        let info = report.get("info").and_then(Value::as_array).unwrap();
        assert!(
            info.iter()
                .any(|r| r.get("kind").and_then(Value::as_str) == Some("unpushed")),
            "expected an unpushed info note: {report}"
        );
        assert!(
            report
                .get("risks")
                .and_then(Value::as_array)
                .unwrap()
                .is_empty(),
            "unpushed commits alone must not block: {report}"
        );
        assert_eq!(report.get("removable").and_then(Value::as_bool), Some(true));
    }

    #[tokio::test]
    async fn close_safety_check_ignores_gitignored_files() {
        // With `.gitignore` committed, an ignored artifact is the only worktree
        // change — it must not count as untracked (it is regenerable), so the
        // worktree stays cleanly removable with no risks.
        let main_dir = tempfile::tempdir().unwrap();
        let repo = init_repo(main_dir.path());
        let a = commit_file(&repo, "refs/heads/trunk", ".gitignore", b"build/\n", "A");
        repo.set_head("refs/heads/trunk").unwrap();
        let wt_parent = tempfile::tempdir().unwrap();
        let wt_path = wt_parent.path().join("feature-wt");
        add_worktree(&repo, a, &wt_path, "feature");
        std::fs::create_dir(wt_path.join("build")).unwrap();
        std::fs::write(wt_path.join("build/artifact.o"), b"junk").unwrap();

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        assert!(
            report
                .get("risks")
                .and_then(Value::as_array)
                .unwrap()
                .is_empty(),
            "a gitignored file must not create a risk: {report}"
        );
        assert_eq!(report.get("removable").and_then(Value::as_bool), Some(true));
    }

    #[tokio::test]
    async fn close_safety_check_treats_a_missing_path_as_already_removed() {
        // The phase-1 check on a path that no longer exists reports it removable
        // with no risks (so the idempotent execute proceeds with no dialog).
        let svc = WorktreesService::new();
        let report = svc
            .handle(
                "close",
                json!({ "path": "/no/such/worktree/xyzzy", "remove": true }),
            )
            .await
            .unwrap();
        assert_eq!(report.get("removable").and_then(Value::as_bool), Some(true));
        assert_eq!(report.get("is_main").and_then(Value::as_bool), Some(false));
        assert!(report
            .get("risks")
            .and_then(Value::as_array)
            .unwrap()
            .is_empty());
        let info = report.get("info").and_then(Value::as_array).unwrap();
        assert!(info
            .iter()
            .any(|r| r.get("kind").and_then(Value::as_str) == Some("already-removed")));
    }

    #[tokio::test]
    async fn close_refuses_a_locked_worktree() {
        // A locked worktree (git worktree lock) must be refused, not forced past
        // (failure mode #6), and left on disk.
        let (main, _wtp, wt_path) = repo_with_linked_worktree();
        let main_repo = Repository::open(main.path()).unwrap();
        main_repo
            .find_worktree("feature")
            .unwrap()
            .lock(Some("under test"))
            .unwrap();

        let svc = WorktreesService::new();
        let err = svc
            .handle(
                "close",
                json!({ "path": wt_path, "remove": true, "confirmed": true }),
            )
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("locked"),
            "expected a locked error: {err}"
        );
        assert!(wt_path.exists(), "a locked worktree must not be removed");
    }

    #[tokio::test]
    async fn close_safety_check_does_not_flag_a_detached_head_reachable_from_a_branch() {
        // A detached HEAD that still sits on a commit a branch points to loses
        // nothing on removal, so it must NOT produce an unreachable-commits risk
        // (the false-positive the reachability walk guards against).
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let wt_repo = Repository::open(&wt_path).unwrap();
        // The worktree is on `feature`; detach HEAD onto its current tip, which
        // the `feature` branch still references.
        let tip = wt_repo.head().unwrap().target().unwrap();
        wt_repo.set_head_detached(tip).unwrap();
        assert!(wt_repo.head_detached().unwrap());

        let svc = WorktreesService::new();
        let report = svc
            .handle("close", json!({ "path": wt_path, "remove": true }))
            .await
            .unwrap();
        let risks = report.get("risks").and_then(Value::as_array).unwrap();
        assert!(
            !risks
                .iter()
                .any(|r| r.get("kind").and_then(Value::as_str) == Some("unreachable-commits")),
            "a detached HEAD reachable from a branch must not be flagged: {report}"
        );
    }

    #[test]
    fn worktree_name_for_path_resolves_a_real_worktree_and_errors_otherwise() {
        let (main, _wtp, wt_path) = repo_with_linked_worktree();
        let main_repo = Repository::open(main.path()).unwrap();
        // The real linked worktree resolves to its registered name.
        assert_eq!(
            worktree_name_for_path(&main_repo, &canonical(&wt_path)).unwrap(),
            "feature"
        );
        // A path that is not one of this repo's worktrees is the defensive
        // "not registered" error (the guard behind removal).
        let err =
            worktree_name_for_path(&main_repo, Path::new("/no/such/worktree/xyzzy")).unwrap_err();
        assert!(
            err.to_string().contains("not registered"),
            "expected a not-registered error: {err}"
        );
    }

    #[test]
    fn count_dirty_untracked_degrades_to_zero_on_an_unreadable_index() {
        // A corrupt index makes `statuses()` fail; the count degrades to (0, 0)
        // rather than sinking the whole safety check.
        let (_main, _wtp, wt_path) = repo_with_linked_worktree();
        let repo = Repository::open(&wt_path).unwrap();
        std::fs::write(repo.path().join("index"), b"not a valid git index").unwrap();
        // Confirm the corruption actually breaks status enumeration, so the
        // count is exercising the error-degradation branch (not an empty repo).
        assert!(
            repo.statuses(Some(&mut StatusOptions::new())).is_err(),
            "a corrupt index should make statuses() fail"
        );
        assert_eq!(count_dirty_untracked(&repo), (0, 0));
    }
}