spar-cli 0.4.20

Two AI coding agents alternate implementing and reviewing GitHub issues until a PR converges.
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
//! Listening for what happens after a review.
//!
//! Every other command does one pass and exits, so a review asked for again
//! after spar posted one waited for a person to notice and run spar again.
//! `spar listen` waits instead, and it waits for free: the only thing that
//! calls an agent is a review, a second look, or a check-in, and none of those
//! starts until GitHub says something happened.
//!
//! A second look is asked for, never assumed: a review requested again or a
//! mention starts one, and a push or a comment alone does not. The author may
//! still be working, and a comment may be another reviewer's review rather than
//! an answer to this one. The look that runs reads every commit and reply since
//! the review on record.
//!
//! Two sources feed it, because neither is enough alone. GitHub's notifications
//! say why a thread moved, a review request, a mention, a comment, and they are
//! polled with a conditional request that costs nothing against the rate limit
//! when nothing changed. But a push raises no notification for a reviewer, so a
//! slower sweep of the open pull requests compares each head with the commit
//! spar last read. Notifications are never raised for the viewer's own actions,
//! which is also why spar's own comments never wake it.
//!
//! Events settle before anything runs: a review request followed by three
//! comments in the same minute is one second look, not four. What runs is
//! decided by a table that is a pure function of the event, a few facts about
//! the item, and the `[listen]` settings, so it can be read and tested on its
//! own.

use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::agent::Agent;
use crate::checkin;
use crate::clock;
use crate::config::{Config, ListenCfg, OwnPr, ReviewOrIgnore};
use crate::error::Result;
use crate::model::{IssueRun, ItemKind, Login, PrSweepRow, ReviewRequested, Status};
use crate::proc;
use crate::repo::{ApiResponse, Repo};
use crate::review_only::{self, RecheckMode, ReviewOpts};
use crate::spend;
use crate::{bail, log, logdim, logwarn, spar_err};

/// Polling never goes below this, whatever the config says.
const FLOOR_SECS: u64 = 15;
/// A `seen` entry older than this is forgotten.
const SEEN_FOR_SECS: u64 = 7 * 86_400;
/// Most notification pages read in one poll. A poll is all or nothing, so one
/// with more than this fails, and says how to start from later.
const MAX_PAGES: usize = 50;
/// Failed dispatches of one item before it is left alone until it changes.
const MAX_FAILURES: u32 = 5;

pub const STATE_VERSION: u32 = 1;

/// How one `spar listen` was asked to run.
#[derive(Debug, Clone, Default)]
pub struct Opts {
    /// The issues and pull requests to watch. Empty means the repository.
    pub items: Vec<i64>,
    /// One poll and one sweep, act on what is due, exit.
    pub once: bool,
    /// Log every event and what it would trigger, and trigger nothing.
    pub dry_run: bool,
    /// How far back the first run looks.
    pub since: Option<Duration>,
}

// ---------------------------------------------------------------------------
// What GitHub returns
// ---------------------------------------------------------------------------

/// One notification thread, as `GET /repos/{owner}/{repo}/notifications`
/// returns it.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct Thread {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub reason: String,
    #[serde(default)]
    pub updated_at: String,
    #[serde(default)]
    pub subject: Subject,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct Subject {
    #[serde(default)]
    pub title: String,
    /// The API URL of the issue or pull request; its number is the last path
    /// segment.
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub latest_comment_url: Option<String>,
    /// `PullRequest`, `Issue`, or something spar does not watch.
    #[serde(default, rename = "type")]
    pub kind: String,
}

// ---------------------------------------------------------------------------
// Events, and what is kept between ticks
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Trigger {
    /// The head moved since spar last read it.
    Pushed,
    /// Somebody other than the viewer said something.
    Replied,
    Mentioned,
    ReviewRequested,
    Assigned,
    Closed,
}

impl Trigger {
    /// The trigger as a reason in a sentence.
    fn noun(self) -> &'static str {
        match self {
            Trigger::Pushed => "a push",
            Trigger::Replied => "a reply",
            Trigger::Mentioned => "a mention",
            Trigger::ReviewRequested => "a review request",
            Trigger::Assigned => "an assignment",
            Trigger::Closed => "a close",
        }
    }
}

/// One thing that happened to one item.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Event {
    pub number: i64,
    pub kind: ItemKind,
    pub trigger: Trigger,
    /// Who did it, when GitHub said.
    pub who: Option<String>,
    /// The old and new head, for a push.
    pub head: Option<(String, String)>,
    /// New commits since the review, when cheap to know.
    pub commits: Option<u64>,
    /// Raised by a notification thread, whose reason is the one the thread
    /// began with: the trigger says how the thread started, not always what
    /// just happened on it.
    pub from_thread: bool,
}

/// What has happened to one item since spar last acted on it. Persisted, so a
/// restart in the middle of settling loses nothing: the notification is
/// already past the watermark and will not come again.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Pending {
    pub kind: ItemKind,
    pub first_seen: u64,
    pub last_seen: u64,
    pub triggers: BTreeSet<Trigger>,
    #[serde(default)]
    pub who: Vec<String>,
    #[serde(default)]
    pub head_from: Option<String>,
    #[serde(default)]
    pub head_to: Option<String>,
}

impl Pending {
    /// "a push and 2 replies", for the line that says why something ran.
    pub fn because(&self) -> String {
        let mut parts: Vec<String> = self.triggers.iter().map(|t| t.noun().to_string()).collect();
        if parts.is_empty() {
            parts.push("nothing in particular".into());
        }
        match parts.len() {
            1 => parts.remove(0),
            2 => format!("{} and {}", parts[0], parts[1]),
            _ => {
                let last = parts.pop().unwrap_or_default();
                format!("{}, and {last}", parts.join(", "))
            }
        }
    }
}

/// What the listener knows about one item it is watching.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Watched {
    pub kind: ItemKind,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub author: String,
    /// The head the listener last saw. A sweep raises Pushed only when this
    /// changes, so a commit spar itself just read is not news.
    #[serde(default)]
    pub head: Option<String>,
    #[serde(default)]
    pub requested_noticed: bool,
    #[serde(default)]
    pub assigned_noticed: bool,
    #[serde(default)]
    pub failures: u32,
    #[serde(default)]
    pub retry_after: u64,
    #[serde(default)]
    pub said_capped: bool,
    #[serde(default)]
    pub said_resume: bool,
    #[serde(default)]
    pub last_dispatched: Option<u64>,
    /// What a pending item was waiting on when the listener gave up on it.
    /// Giving up waits for the item to change, and on a pull request spar has
    /// not reviewed that change is often a push alone, which leads nowhere, so
    /// the reasons come back with it.
    #[serde(default)]
    pub held: BTreeSet<Trigger>,
}

impl Watched {
    fn new(kind: ItemKind) -> Self {
        Self {
            kind,
            title: String::new(),
            author: String::new(),
            head: None,
            requested_noticed: false,
            assigned_noticed: false,
            failures: 0,
            retry_after: 0,
            said_capped: false,
            said_resume: false,
            last_dispatched: None,
            held: BTreeSet::new(),
        }
    }
}

/// Everything the listener keeps between ticks and between runs, in
/// `.spar/state/listen.json`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ListenState {
    pub version: u32,
    /// Threads updated after this are new. RFC 3339, the shape GitHub takes.
    #[serde(default)]
    pub watermark: String,
    /// `Last-Modified` of the last poll that answered, sent back as
    /// `If-Modified-Since` so a poll that finds nothing costs nothing.
    #[serde(default)]
    pub last_modified: Option<String>,
    /// Thread id to the `updated_at` it was last seen with, so one thread
    /// returned twice is one event.
    #[serde(default)]
    pub seen: BTreeMap<String, String>,
    #[serde(default)]
    pub items: BTreeMap<i64, Watched>,
    #[serde(default)]
    pub pending: BTreeMap<i64, Pending>,
}

impl ListenState {
    fn watched(&mut self, number: i64, kind: ItemKind) -> &mut Watched {
        self.items
            .entry(number)
            .or_insert_with(|| Watched::new(kind))
    }

    /// Fold an event into what is pending for its item, with whatever the
    /// item was waiting on when the listener last gave up on it.
    fn note(&mut self, event: &Event, now: u64) {
        let held = std::mem::take(&mut self.watched(event.number, event.kind).held);
        merge(&mut self.pending, event, now);
        if let Some(p) = self.pending.get_mut(&event.number) {
            p.triggers.extend(held);
        }
    }

    /// Stop trying an item until it changes again, holding what it was
    /// waiting on. A requested first review that GitHub's lag behind a push
    /// kept stopping is still requested when that push shows.
    fn give_up(&mut self, number: i64, kind: ItemKind) {
        if let Some(p) = self.pending.remove(&number) {
            self.watched(number, kind).held.extend(p.triggers);
        }
    }
}

// ---------------------------------------------------------------------------
// Pure pieces
// ---------------------------------------------------------------------------

/// `30m`, `2h`, `1d`, `1h30m`.
pub fn parse_duration(text: &str) -> Result<Duration> {
    let bad = || {
        spar_err!(
            "`--since` takes a number and a unit, like 30m, 2h or 1d, not {:?}",
            text.trim()
        )
    };
    let mut total = 0u64;
    let mut digits = String::new();
    let mut any = false;
    for c in text.trim().chars() {
        if c.is_ascii_digit() {
            digits.push(c);
            continue;
        }
        let n: u64 = digits.parse().map_err(|_| bad())?;
        digits.clear();
        let unit = match c {
            's' => 1,
            'm' => 60,
            'h' => 3600,
            'd' => 86_400,
            _ => return Err(bad()),
        };
        total = total.saturating_add(n.saturating_mul(unit));
        any = true;
    }
    if !digits.is_empty() || !any {
        return Err(bad());
    }
    Ok(Duration::from_secs(total))
}

/// How long to wait before the next poll: the config, what GitHub asked for,
/// and the floor, whichever is largest.
pub fn poll_interval(cfg: &ListenCfg, header: Option<&str>) -> u64 {
    let asked = header
        .and_then(|h| h.trim().parse::<u64>().ok())
        .unwrap_or(0);
    cfg.interval.max(asked).max(FLOOR_SECS)
}

/// How long a rate limited answer says to wait, clamped to a minute and an
/// hour, or None when the answer was not about the rate limit.
pub fn rate_limit_wait(resp: &ApiResponse, now: u64) -> Option<u64> {
    if resp.status != 403 && resp.status != 429 {
        return None;
    }
    let retry_after = resp
        .headers
        .get("retry-after")
        .and_then(|v| v.trim().parse::<u64>().ok());
    let exhausted = resp
        .headers
        .get("x-ratelimit-remaining")
        .is_some_and(|v| v.trim() == "0");
    let reset = resp
        .headers
        .get("x-ratelimit-reset")
        .and_then(|v| v.trim().parse::<u64>().ok())
        .map(|at| at.saturating_sub(now));
    let wait = match (retry_after, exhausted, reset) {
        (Some(secs), _, _) => secs,
        (None, true, Some(secs)) => secs,
        _ => return None,
    };
    Some(wait.clamp(60, 3600))
}

/// The body's `message`, or the status line, for a failure that is not a
/// rate limit.
fn status_message(resp: &ApiResponse) -> String {
    serde_json::from_str::<serde_json::Value>(&resp.body)
        .ok()
        .and_then(|v| {
            v.get("message")
                .and_then(|m| m.as_str())
                .map(|m| format!("HTTP {}: {m}", resp.status))
        })
        .unwrap_or_else(|| format!("HTTP {}", resp.status))
}

/// The URL of the next page, from a `Link` header.
pub fn next_link(headers: &BTreeMap<String, String>) -> Option<String> {
    let link = headers.get("link")?;
    link.split(',').find_map(|part| {
        let (url, rel) = part.split_once(';')?;
        if !rel.contains("rel=\"next\"") {
            return None;
        }
        let url = url.trim().trim_start_matches('<').trim_end_matches('>');
        (!url.is_empty()).then(|| url.to_string())
    })
}

/// The number at the end of an issue or pull request API URL.
pub fn number_from_url(url: &str) -> Option<i64> {
    url.trim_end_matches('/')
        .rsplit('/')
        .next()
        .and_then(|last| last.parse().ok())
}

/// Turn a poll's threads into events, skipping what was already seen, and
/// advance the watermark past them.
pub fn events_from_threads(threads: &[Thread], state: &mut ListenState) -> Vec<Event> {
    let mut out = Vec::new();
    for thread in threads {
        if state.seen.get(&thread.id) == Some(&thread.updated_at) {
            continue;
        }
        if !thread.updated_at.is_empty() {
            state
                .seen
                .insert(thread.id.clone(), thread.updated_at.clone());
            if thread.updated_at > state.watermark {
                state.watermark = thread.updated_at.clone();
            }
        }
        let kind = match thread.subject.kind.as_str() {
            "PullRequest" => ItemKind::Pr,
            "Issue" => ItemKind::Issue,
            _ => continue,
        };
        let Some(number) = thread.subject.url.as_deref().and_then(number_from_url) else {
            continue;
        };
        let trigger = match thread.reason.as_str() {
            "review_requested" => Trigger::ReviewRequested,
            "assign" => Trigger::Assigned,
            "mention" | "team_mention" => Trigger::Mentioned,
            // comment, author, manual, state_change: somebody did something
            // on a thread the viewer is part of. The facts call learns whether
            // it closed.
            _ => Trigger::Replied,
        };
        out.push(Event {
            number,
            kind,
            trigger,
            who: None,
            head: None,
            commits: None,
            from_thread: true,
        });
    }
    out
}

/// What a sweep of the open pull requests says happened.
///
/// `record_head` answers with the commit a posted review record holds, so a
/// pull request seen for the first time whose head already moved since its
/// review is a pending second look rather than nothing.
pub fn events_from_sweep(
    rows: &[PrSweepRow],
    viewer: &str,
    state: &mut ListenState,
    named: &BTreeSet<i64>,
    min_number: i64,
    record_head: &dyn Fn(i64) -> Option<String>,
    repo_mode: bool,
) -> Vec<Event> {
    let mut out = Vec::new();
    let mut present: BTreeSet<i64> = BTreeSet::new();
    for row in rows {
        // Present before the floor is applied: a pull request below it is
        // still open, and one a notification put on the watch is not closed
        // just because the sweep does not act on it.
        present.insert(row.number);
        if row.number < min_number && !named.contains(&row.number) {
            continue;
        }
        let watched = state.watched(row.number, ItemKind::Pr);
        if !row.title.is_empty() {
            watched.title = row.title.clone();
        }
        if let Some(author) = &row.author {
            watched.author = author.login.clone();
        }
        if !row.state.eq_ignore_ascii_case("OPEN") {
            out.push(Event {
                number: row.number,
                kind: ItemKind::Pr,
                trigger: Trigger::Closed,
                who: None,
                head: None,
                commits: None,
                from_thread: false,
            });
            continue;
        }
        let from = match &watched.head {
            Some(old) => Some(old.clone()),
            None => record_head(row.number),
        };
        if let Some(old) = from {
            if !row.head_ref_oid.is_empty() && !old.eq_ignore_ascii_case(&row.head_ref_oid) {
                out.push(Event {
                    number: row.number,
                    kind: ItemKind::Pr,
                    trigger: Trigger::Pushed,
                    who: None,
                    head: Some((old, row.head_ref_oid.clone())),
                    commits: None,
                    from_thread: false,
                });
            }
        }
        if !row.head_ref_oid.is_empty() {
            watched.head = Some(row.head_ref_oid.clone());
        }
        let asked = row
            .review_requests
            .iter()
            .any(|l| crate::comments::same_login(&l.login, viewer));
        // A formal review clears a request, so a request seen again later is
        // the author asking again and is news. A review posted as a comment
        // leaves it open, and the dispatch tells that one apart by when it was
        // made.
        if !asked {
            watched.requested_noticed = false;
        } else if !watched.requested_noticed {
            watched.requested_noticed = true;
            out.push(Event {
                number: row.number,
                kind: ItemKind::Pr,
                trigger: Trigger::ReviewRequested,
                who: None,
                head: None,
                commits: None,
                from_thread: false,
            });
        }
        let assigned = row
            .assignees
            .iter()
            .any(|l| crate::comments::same_login(&l.login, viewer));
        if assigned && !watched.assigned_noticed {
            watched.assigned_noticed = true;
            out.push(Event {
                number: row.number,
                kind: ItemKind::Pr,
                trigger: Trigger::Assigned,
                who: None,
                head: None,
                commits: None,
                from_thread: false,
            });
        }
    }
    if repo_mode {
        // A pull request that was open last time and is not in the list now
        // has closed or merged.
        let gone: Vec<i64> = state
            .items
            .iter()
            .filter(|(n, w)| w.kind == ItemKind::Pr && !present.contains(n))
            .map(|(n, _)| *n)
            .collect();
        for number in gone {
            out.push(Event {
                number,
                kind: ItemKind::Pr,
                trigger: Trigger::Closed,
                who: None,
                head: None,
                commits: None,
                from_thread: false,
            });
        }
    }
    out
}

/// Fold one event into what is pending for its item.
pub fn merge(pending: &mut BTreeMap<i64, Pending>, event: &Event, now: u64) {
    let p = pending.entry(event.number).or_insert_with(|| Pending {
        kind: event.kind,
        first_seen: now,
        last_seen: now,
        triggers: BTreeSet::new(),
        who: Vec::new(),
        head_from: None,
        head_to: None,
    });
    p.last_seen = now;
    p.triggers.insert(event.trigger);
    if let Some(who) = &event.who {
        if !p.who.contains(who) {
            p.who.push(who.clone());
        }
    }
    if let Some((from, to)) = &event.head {
        if p.head_from.is_none() {
            p.head_from = Some(from.clone());
        }
        p.head_to = Some(to.clone());
    }
}

/// Whether an item has settled: quiet for `settle` seconds, or pending for
/// `max_wait` however noisy, or `--once`.
pub fn due(p: &Pending, now: u64, cfg: &ListenCfg, once: bool) -> bool {
    once || now.saturating_sub(p.last_seen) >= cfg.settle
        || now.saturating_sub(p.first_seen) >= cfg.max_wait
}

/// When the earliest pending item this run acts on becomes due and is past
/// any wait a failure put on it. Leaving the wait out woke the loop every
/// second until it ended.
pub fn next_due(
    state: &ListenState,
    cfg: &ListenCfg,
    acts_on: &dyn Fn(i64) -> bool,
) -> Option<u64> {
    state
        .pending
        .iter()
        .filter(|(n, _)| acts_on(**n))
        .map(|(n, p)| {
            let settled = (p.last_seen + cfg.settle).min(p.first_seen + cfg.max_wait);
            state
                .items
                .get(n)
                .map_or(settled, |w| settled.max(w.retry_after))
        })
        .min()
}

/// What the dispatch table decided, before anything runs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    /// A second look at this pull request. An issue routes to its pull request.
    Recheck(i64),
    /// A first look.
    Review,
    /// `spar checkin`, with or without the power to push.
    Checkin { reply_only: bool },
    /// This pull request was rechecked as often as the config allows; a person
    /// runs `spar review`. An issue names its pull request.
    Capped(i64),
    /// Custody state and no review record: `spar resume` owns it.
    BelongsToResume,
    /// Closed or merged: forget it.
    Drop,
    /// Nothing, with the reason.
    Ignore(&'static str),
}

impl Action {
    /// What the log says is about to happen to item `number`.
    pub fn phrase(&self, number: i64) -> String {
        match self {
            Action::Recheck(pr) if *pr == number => "take a second look".to_string(),
            Action::Recheck(pr) => format!("take a second look at #{pr}"),
            Action::Review => "review it".to_string(),
            Action::Checkin { reply_only: false } => "check in on it".to_string(),
            Action::Checkin { reply_only: true } => "answer the comments on it".to_string(),
            Action::Capped(_) | Action::BelongsToResume => "leave it".to_string(),
            Action::Drop => "drop it".to_string(),
            Action::Ignore(_) => "ignore it".to_string(),
        }
    }

    fn runs(&self) -> bool {
        matches!(
            self,
            Action::Recheck(_) | Action::Review | Action::Checkin { .. }
        )
    }
}

/// What `plan` needs to know about an item beyond what is pending. Read once
/// per dispatch, never per tick.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Facts {
    pub number: i64,
    pub named: bool,
    pub open: bool,
    /// For an issue, this and `recheck_capped` are about its linked pull
    /// request, since that is what a second look on its behalf would be at.
    pub author_is_viewer: bool,
    /// A review record the author has seen.
    pub has_posted_record: bool,
    pub recheck_capped: bool,
    /// The custody loop's `pr-N.json`.
    pub has_custody_state: bool,
    pub below_floor: bool,
    /// For an issue: its open pull request, when spar reviewed that.
    pub linked_pr_with_record: Option<i64>,
    /// The pull request asks the viewer for a review right now, by name or
    /// through a team the viewer is in.
    pub review_pending: bool,
    /// That request was made before the posted review began, so the review
    /// answered it.
    pub request_answered: bool,
    /// Somebody, not a bot, @mentioned the viewer since the review on record,
    /// or for an issue since its pull request's. Read only when a mention is
    /// pending.
    pub mentioned: bool,
}

/// Whether a pull request's `reviewRequests` ask the viewer now: by name, or
/// through a team `in_team` says the viewer is in. A team nobody could check
/// counts as asking, which is how every team request used to be read.
pub fn review_pending(
    requests: &[Login],
    viewer: &str,
    in_team: &dyn Fn(&str) -> Option<bool>,
) -> bool {
    requests
        .iter()
        .any(|r| crate::comments::same_login(&r.login, viewer))
        || requests
            .iter()
            .filter(|r| r.login.is_empty())
            .any(|team| in_team(&team.slug).unwrap_or(true))
}

/// Whether the review the viewer is asked for is already on record: the newest
/// request that counts for the viewer, as `review_pending` counts one, was made
/// no later than the posted review began at `reviewed_at`.
///
/// A review posted as a comment leaves its request open, and a first sweep has
/// never seen the request before, so without this a request the review already
/// answered reads as the author asking again. False when no request counts or
/// a time cannot be read: answered takes the timeline saying so.
pub fn request_answered(
    made: &[ReviewRequested],
    viewer: &str,
    in_team: &dyn Fn(&str) -> Option<bool>,
    reviewed_at: &str,
) -> bool {
    let Some(reviewed) = clock::parse_rfc3339(reviewed_at) else {
        return false;
    };
    made.iter()
        .filter(|r| review_pending(std::slice::from_ref(&r.who), viewer, in_team))
        .filter_map(|r| clock::parse_rfc3339(&r.at))
        .max()
        .is_some_and(|newest| newest <= reviewed)
}

/// A notification's reason is the one its thread was first raised for and it
/// never changes, so a thread that began as a review request says so on every
/// later update, spar's own review among them. What the pull request says now
/// decides: when nobody is asking any more, or the request is older than the
/// review on record and so was answered by it, the update is only something
/// happening on a thread the viewer is part of. True when it was.
pub fn settle(p: &mut Pending, f: &Facts) -> bool {
    let stale = p.kind == ItemKind::Pr
        && (!f.review_pending || f.request_answered)
        && p.triggers.remove(&Trigger::ReviewRequested);
    if stale {
        p.triggers.insert(Trigger::Replied);
    }
    stale
}

/// A mention is a reason a thread keeps too, so a thread that began with one
/// says so on every later update. On a pull request spar reviewed, or an issue
/// whose pull request it reviewed, only a mention made since that review asks
/// for a second look; any other is only something happening on a thread the
/// viewer is part of. True when it was.
pub fn settle_mention(p: &mut Pending, f: &Facts) -> bool {
    let reviewed = match p.kind {
        ItemKind::Pr => f.has_posted_record,
        ItemKind::Issue => f.linked_pr_with_record.is_some(),
    };
    let stale = reviewed && !f.mentioned && p.triggers.remove(&Trigger::Mentioned);
    if stale {
        p.triggers.insert(Trigger::Replied);
    }
    stale
}

/// The dispatch table.
pub fn plan(p: &Pending, f: &Facts, cfg: &ListenCfg) -> Action {
    use Trigger::*;
    if !f.open || p.triggers.contains(&Closed) {
        return Action::Drop;
    }
    if f.below_floor && !f.named {
        return Action::Ignore("it is below min_number and was not named");
    }
    match p.kind {
        ItemKind::Issue => {
            // Only a mention asks. A reply is not a request, and an issue
            // thread that began with an assignment says so on every later
            // comment.
            if !p.triggers.contains(&Mentioned) {
                return Action::Ignore("nothing on the issue asked for spar");
            }
            // The pull request's own guards hold whichever way its second look
            // was asked for, or a mention on the issue would be a way round them.
            match f.linked_pr_with_record {
                None => Action::Ignore("an issue with no reviewed pull request"),
                Some(_) if f.author_is_viewer => Action::Ignore("its pull request is your own"),
                Some(pr) if f.recheck_capped => Action::Capped(pr),
                Some(pr) => Action::Recheck(pr),
            }
        }
        ItemKind::Pr => {
            // The viewer's own pull request first: it outranks a review
            // record, so a `spar review` somebody ran on their own branch does
            // not make every push a second look the same account cannot
            // approve.
            if f.author_is_viewer {
                let spoken_to = p
                    .triggers
                    .iter()
                    .any(|t| matches!(t, Replied | Mentioned | ReviewRequested));
                if !spoken_to {
                    return Action::Ignore("a push to your own pull request");
                }
                return match cfg.on_own_pr {
                    OwnPr::Checkin => Action::Checkin { reply_only: false },
                    OwnPr::Reply => Action::Checkin { reply_only: true },
                    OwnPr::Ignore => Action::Ignore("on_own_pr is ignore"),
                };
            }
            if f.has_posted_record {
                // A second look is asked for, never assumed. A push may be
                // work in progress, and a comment may be another reviewer's
                // review rather than an answer to this one.
                let asked =
                    p.triggers.contains(&ReviewRequested) || p.triggers.contains(&Mentioned);
                if !asked {
                    return Action::Ignore(
                        "what is neither a review request nor a mention, the only things that \
                         ask for a second look",
                    );
                }
                return if f.recheck_capped {
                    Action::Capped(f.number)
                } else {
                    Action::Recheck(f.number)
                };
            }
            if f.has_custody_state {
                return Action::BelongsToResume;
            }
            if f.named {
                return Action::Review;
            }
            if p.triggers.contains(&ReviewRequested) {
                return match cfg.on_review_requested {
                    ReviewOrIgnore::Review => Action::Review,
                    ReviewOrIgnore::Ignore => Action::Ignore("on_review_requested is ignore"),
                };
            }
            if p.triggers.contains(&Assigned) {
                return match cfg.on_assigned {
                    ReviewOrIgnore::Review => Action::Review,
                    ReviewOrIgnore::Ignore => Action::Ignore("on_assigned is ignore"),
                };
            }
            if p.triggers.contains(&Mentioned) {
                return Action::Review;
            }
            Action::Ignore("a push or a comment on a pull request spar has not reviewed")
        }
    }
}

/// Forget threads not seen for a week.
pub fn prune_seen(state: &mut ListenState, now: u64) {
    state.seen.retain(|_, at| {
        clock::parse_rfc3339(at).is_none_or(|t| now.saturating_sub(t) < SEEN_FOR_SECS)
    });
}

/// A minute, doubling, to a quarter of an hour.
pub fn backoff_secs(failures: u32) -> u64 {
    (60u64 << failures.saturating_sub(1).min(10)).min(900)
}

/// A quarter of an hour, doubling, to six hours.
pub fn dispatch_backoff_secs(failures: u32) -> u64 {
    (900u64 << failures.saturating_sub(1).min(10)).min(6 * 3600)
}

/// How long an item whose dispatch did not finish waits to run again. A head
/// that moved under it is GitHub or the author rather than a failure, so the
/// next look starts once the push settles. Anything else backs off.
pub fn retry_wait(moved: bool, failures: u32, cfg: &ListenCfg) -> u64 {
    if moved {
        cfg.settle.max(FLOOR_SECS)
    } else {
        dispatch_backoff_secs(failures)
    }
}

/// What a `gh` failure is retried after, said loudly once and quietly after.
#[derive(Debug, Default)]
struct Backoff {
    failures: u32,
    said: bool,
}

impl Backoff {
    fn failed(&mut self, what: &str, why: &str) -> u64 {
        self.failures += 1;
        let wait = backoff_secs(self.failures);
        let line = format!(
            "could not {what}: {why}. Trying again in {}.",
            spend::clock(Duration::from_secs(wait))
        );
        if self.said {
            logdim!("{line}");
        } else {
            logwarn!("{line}");
            self.said = true;
        }
        wait
    }

    fn recovered(&mut self) {
        if self.said {
            log!("gh is answering again");
        }
        *self = Self::default();
    }
}

// ---------------------------------------------------------------------------
// The lock
// ---------------------------------------------------------------------------

/// Who holds the lock, for the message a second listener prints. The lock
/// itself is not in here.
#[derive(Debug, Serialize, Deserialize)]
struct LockFile {
    pid: u32,
    started: String,
}

/// One listener per checkout. Two would read the same events, run the same
/// reviews twice, and rebuild the worktree the other's agents are reading.
///
/// On unix the lock is the operating system's, on the open file, rather than
/// the file being there. It is held exactly as long as the process lives,
/// however long one review takes, so nothing has to keep it fresh, and a
/// listener that died holds nothing, even after a reboot hands its pid to
/// something else.
#[derive(Debug)]
struct Lock {
    path: PathBuf,
    /// Open for the lock's lifetime: closing it is what releases the lock.
    _file: File,
}

impl Lock {
    fn acquire(repo: &Repo, now: u64) -> Result<Lock> {
        Lock::at(repo.listen_lock_path(), now)
    }

    fn at(path: PathBuf, now: u64) -> Result<Lock> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        // A listener that exits removes the file while it still holds it, so
        // the file opened here can be one that was unlinked a moment ago.
        // Locking that would lock a file nobody else can find, hence the check
        // that the path still names the file locked, and another try if not.
        for _ in 0..3 {
            let Some(mut file) = open_locked(&path)? else {
                let pid = std::fs::read_to_string(&path)
                    .ok()
                    .and_then(|text| serde_json::from_str::<LockFile>(&text).ok())
                    .map(|h| h.pid.to_string())
                    .unwrap_or_else(|| "unknown".into());
                bail!(
                    "another `spar listen` (pid {pid}) is already watching this checkout. \
                     Stop it first.{}",
                    if cfg!(unix) {
                        String::new()
                    } else {
                        format!(" If that process is gone, delete {}.", path.display())
                    }
                );
            };
            if !same_file(&file, &path) {
                continue;
            }
            file.set_len(0)?;
            serde_json::to_writer_pretty(
                &mut file,
                &LockFile {
                    pid: std::process::id(),
                    started: clock::rfc3339(now),
                },
            )?;
            return Ok(Lock { path, _file: file });
        }
        bail!("could not take the listen lock at {}", path.display())
    }
}

impl Drop for Lock {
    fn drop(&mut self) {
        // Removed while still held, which is what `same_file` relies on. The
        // file closes, and the lock goes with it, after this returns.
        let _ = std::fs::remove_file(&self.path);
    }
}

/// The lock file, opened and locked, or None when another process holds it.
#[cfg(unix)]
fn open_locked(path: &Path) -> Result<Option<File>> {
    use std::os::unix::io::AsRawFd;
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)?;
    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
        return Ok(Some(file));
    }
    let e = std::io::Error::last_os_error();
    if e.raw_os_error() == Some(libc::EWOULDBLOCK) {
        Ok(None)
    } else {
        Err(e.into())
    }
}

/// Without an advisory lock to hand, the file being there is the lock, and one
/// left by a listener that died has to be deleted by hand.
#[cfg(not(unix))]
fn open_locked(path: &Path) -> Result<Option<File>> {
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
    {
        Ok(file) => Ok(Some(file)),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
        Err(e) => Err(e.into()),
    }
}

#[cfg(unix)]
fn same_file(file: &File, path: &Path) -> bool {
    use std::os::unix::fs::MetadataExt;
    match (file.metadata(), std::fs::metadata(path)) {
        (Ok(open), Ok(named)) => open.dev() == named.dev() && open.ino() == named.ino(),
        _ => false,
    }
}

#[cfg(not(unix))]
fn same_file(_file: &File, _path: &Path) -> bool {
    true
}

// ---------------------------------------------------------------------------
// The two sources
// ---------------------------------------------------------------------------

enum Polled {
    /// Nothing new, poll again after this many seconds.
    Nothing(u64),
    Threads(Vec<Thread>, u64),
    /// Rate limited, wait this long.
    RateLimited(u64),
    Failed(String),
}

fn poll(repo: &Repo, cfg: &ListenCfg, state: &mut ListenState, now: u64) -> Polled {
    let endpoint = format!(
        "repos/{{owner}}/{{repo}}/notifications?participating=true&all=true&per_page=100&since={}",
        state.watermark
    );
    let last_modified = state.last_modified.clone();
    let headers: Vec<(&str, &str)> = last_modified
        .as_deref()
        .map(|lm| vec![("If-Modified-Since", lm)])
        .unwrap_or_default();
    let resp = match repo.gh_api_raw(&endpoint, &headers) {
        Ok(resp) => resp,
        Err(e) => return Polled::Failed(e.last_line().to_string()),
    };
    let interval = poll_interval(cfg, resp.headers.get("x-poll-interval").map(String::as_str));
    match resp.status {
        304 => Polled::Nothing(interval),
        200 => match every_page(repo, &resp, &state.watermark, now) {
            Ok(threads) => {
                // Only once every page is in, or the next poll's 304 would
                // answer for pages this one never read.
                state.last_modified = resp
                    .headers
                    .get("last-modified")
                    .or_else(|| resp.headers.get("date"))
                    .cloned();
                Polled::Threads(threads, interval)
            }
            Err(failed) => failed,
        },
        401 => Polled::Failed("gh is not authenticated; run `gh auth status`".into()),
        _ => refused(&resp, now),
    }
}

/// What a failed answer means: a wait for a rate limit, a failure otherwise.
fn refused(resp: &ApiResponse, now: u64) -> Polled {
    match rate_limit_wait(resp, now) {
        Some(wait) => Polled::RateLimited(wait),
        None => Polled::Failed(status_message(resp)),
    }
}

/// Every page of one poll, or what stopped it.
///
/// All or nothing. Notifications come newest first, so a page that was not
/// read holds threads older than every one that was, and moving the watermark
/// past the ones read would lose the rest for good. A poll that cannot read
/// them all changes nothing and is tried again.
fn every_page(
    repo: &Repo,
    first: &ApiResponse,
    watermark: &str,
    now: u64,
) -> std::result::Result<Vec<Thread>, Polled> {
    let unexpected =
        |e: serde_json::Error| Polled::Failed(format!("unexpected notification data: {e}"));
    let mut threads: Vec<Thread> = serde_json::from_str(&first.body).map_err(unexpected)?;
    let mut next = next_link(&first.headers);
    let mut pages = 1;
    while let Some(url) = next.take() {
        if pages >= MAX_PAGES {
            return Err(Polled::Failed(format!(
                "more than {MAX_PAGES} pages of notifications since {watermark}. Run once with \
                 --since, like --since 1d, to start from later and skip the rest"
            )));
        }
        let more = repo
            .gh_api_raw(&url, &[])
            .map_err(|e| Polled::Failed(e.last_line().to_string()))?;
        if more.status != 200 {
            return Err(refused(&more, now));
        }
        threads.extend(serde_json::from_str::<Vec<Thread>>(&more.body).map_err(unexpected)?);
        next = next_link(&more.headers);
        pages += 1;
    }
    Ok(threads)
}

/// What one sweep read.
#[derive(Default)]
struct Swept {
    rows: Vec<PrSweepRow>,
    /// Named issues that are no longer open.
    closed_issues: Vec<i64>,
}

/// The rows a sweep looks at: every open pull request, or the named ones
/// still watched.
fn sweep_rows(
    repo: &Repo,
    cfg: &Config,
    repo_mode: bool,
    named_prs: &[i64],
    named_issues: &[i64],
    state: &ListenState,
) -> Result<Swept> {
    if repo_mode {
        return Ok(Swept {
            rows: repo.sweep_open_prs()?,
            closed_issues: Vec::new(),
        });
    }
    let watched = |n: &&i64| state.items.contains_key(*n);
    let mut swept = Swept::default();
    for number in named_prs.iter().filter(watched) {
        swept.rows.push(repo.sweep_pr(*number)?);
    }
    for issue in named_issues.iter().filter(watched) {
        // Read here, because a notification is not a promise: an issue the
        // viewer never took part in can close without one, and the listener
        // would wait for it forever.
        if !repo.read_issue(*issue)?.state.eq_ignore_ascii_case("OPEN") {
            swept.closed_issues.push(*issue);
            continue;
        }
        // A named issue's open pull request joins the watch once spar has
        // reviewed it, so a review requested again there is a second look.
        if let Ok(Some(pr)) = repo.try_open_pr_for_issue(*issue, cfg.base_branch()) {
            if repo.read_review_record(pr.number).is_some_and(|r| r.posted) {
                swept.rows.push(repo.sweep_pr(pr.number)?);
            }
        }
    }
    Ok(swept)
}

/// `mention` says a mention is pending, which is the only time the comments are
/// read for one.
fn facts(
    repo: &Repo,
    cfg: &Config,
    number: i64,
    kind: ItemKind,
    named: bool,
    mention: bool,
) -> Result<Facts> {
    let viewer = repo.viewer_login()?.to_string();
    let below_floor = number < cfg.loop_cfg.min_number;
    let in_team = |team: &str| repo.team_has_member(team, &viewer);
    match kind {
        ItemKind::Pr => {
            let row = repo.sweep_pr(number)?;
            let record = repo.read_review_record(number);
            let posted = record.as_ref().is_some_and(|r| r.posted);
            let pending = review_pending(&row.review_requests, &viewer, &in_team);
            // Only an open request can have been answered, and only by a
            // review somebody saw, so the timeline is read for nothing else.
            let answered = pending
                && record.as_ref().filter(|r| r.posted).is_some_and(|r| {
                    repo.review_requests_made(number).is_some_and(|made| {
                        request_answered(&made, &viewer, &in_team, &r.reviewed_at)
                    })
                });
            // Read, not believed: the thread may have begun with a mention
            // long before the review on record.
            let mentioned = match record.as_ref().filter(|r| r.posted) {
                Some(r) if mention => {
                    let mut rows = repo.try_pr_review_comments(number)?;
                    rows.extend(repo.try_pr_reviews(number)?);
                    rows.extend(repo.try_issue_comments(number)?);
                    crate::comments::mentioned_in(&rows, &viewer, &r.reviewed_at, &in_team)
                }
                _ => false,
            };
            Ok(Facts {
                number,
                named,
                open: row.state.eq_ignore_ascii_case("OPEN"),
                author_is_viewer: row
                    .author
                    .as_ref()
                    .is_some_and(|a| crate::comments::same_login(&a.login, &viewer)),
                has_posted_record: posted,
                recheck_capped: posted
                    && record
                        .as_ref()
                        .is_some_and(|r| r.rechecks >= cfg.listen.max_rechecks),
                has_custody_state: repo.state_path(number).exists(),
                below_floor,
                linked_pr_with_record: None,
                review_pending: pending,
                request_answered: answered,
                mentioned,
            })
        }
        ItemKind::Issue => {
            let issue = repo.read_issue(number)?;
            let linked = repo
                .try_open_pr_for_issue(number, cfg.base_branch())
                .ok()
                .flatten()
                .and_then(|pr| {
                    repo.read_review_record(pr.number)
                        .filter(|r| r.posted)
                        .map(|r| (pr.number, r))
                });
            // What the pull request's own row of the table would check.
            let (author_is_viewer, recheck_capped) = match &linked {
                Some((pr, record)) => {
                    let row = repo.sweep_pr(*pr)?;
                    (
                        row.author
                            .as_ref()
                            .is_some_and(|a| crate::comments::same_login(&a.login, &viewer)),
                        record.rechecks >= cfg.listen.max_rechecks,
                    )
                }
                None => (false, false),
            };
            let mentioned = match &linked {
                Some((_, record)) if mention => crate::comments::mentioned_in(
                    &repo.try_issue_comments(number)?,
                    &viewer,
                    &record.reviewed_at,
                    &in_team,
                ),
                _ => false,
            };
            Ok(Facts {
                number,
                named,
                open: issue.state.eq_ignore_ascii_case("OPEN"),
                author_is_viewer,
                has_posted_record: false,
                recheck_capped,
                has_custody_state: false,
                below_floor,
                linked_pr_with_record: linked.map(|(pr, _)| pr),
                review_pending: false,
                request_answered: false,
                mentioned,
            })
        }
    }
}

fn dispatch(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    action: &Action,
    number: i64,
    p: &Pending,
) -> IssueRun {
    match action {
        Action::Recheck(pr) => review_only::recheck_pr(
            agents,
            cfg,
            repo,
            *pr,
            RecheckMode {
                dry_run: false,
                requested: p.triggers.contains(&Trigger::ReviewRequested),
                verdict_on_fallback: cfg.listen.verdicts,
            },
        ),
        Action::Review => review_only::review_pr(
            agents,
            cfg,
            repo,
            number,
            ReviewOpts {
                dry_run: false,
                verdict: cfg.listen.verdicts,
            },
        ),
        Action::Checkin { reply_only } => checkin::checkin_pr(
            agents,
            cfg,
            repo,
            number,
            &checkin::Mode {
                dry_run: false,
                reply_only: *reply_only,
                trust: cfg.loop_cfg.checkin_trust,
                again: false,
                resolve: cfg.loop_cfg.checkin_resolve,
                posts: checkin::posts(cfg),
            },
        ),
        other => {
            let mut run = IssueRun::new(number, format!("#{number}"));
            run.status = Status::Error;
            run.notes
                .push(format!("nothing to run: {}", other.phrase(number)));
            run
        }
    }
}

/// One event, as the log says it.
fn describe(repo: &Repo, event: &Event) -> String {
    let n = event.number;
    match event.trigger {
        Trigger::Pushed => {
            let (from, to) = event.head.clone().unwrap_or_default();
            let short = |s: &str| s.chars().take(7).collect::<String>();
            let commits = repo
                .commits_between(&from, &to)
                .map(|c| format!(", {c} new commit{} since the review", plural(c as usize)))
                .unwrap_or_default();
            format!(
                "#{n}: head moved {} to {}{commits}",
                short(&from),
                short(&to)
            )
        }
        Trigger::Replied => match &event.who {
            Some(who) => format!("#{n}: {who} commented"),
            None => format!("#{n}: somebody commented"),
        },
        Trigger::Mentioned => match &event.who {
            Some(who) => format!("#{n}: mentioned by {who}"),
            None => format!("#{n}: mentioned"),
        },
        // The sweep read the request off the pull request. A thread says only
        // that it began as one, which a later update on it says too.
        Trigger::ReviewRequested if event.from_thread => {
            format!("#{n}: news on a thread that asked for your review")
        }
        Trigger::ReviewRequested => format!("#{n}: your review was requested"),
        Trigger::Assigned => format!("#{n}: assigned to you"),
        Trigger::Closed => format!("#{n}: closed, no longer watched"),
    }
}

fn plural(n: usize) -> &'static str {
    if n == 1 {
        ""
    } else {
        "s"
    }
}

// ---------------------------------------------------------------------------
// The loop
// ---------------------------------------------------------------------------

enum Ending {
    Interrupted,
    Once { failed: bool },
    Done,
}

/// Listen until stopped, or once.
pub fn run(agents: &[Agent], cfg: &Config, repo: &Repo, opts: Opts) -> Result<i32> {
    proc::stop_on_signal()?;
    if !cfg!(unix) {
        logdim!(
            "Ctrl-C ends spar at once on this platform; an agent call in flight is not stopped"
        );
    }
    let now = clock::now_secs();
    let lock = Lock::acquire(repo, now)?;
    let viewer = repo.viewer_login()?.to_string();
    let name = repo
        .repo_name()
        .unwrap_or_else(|| repo.root().display().to_string());

    // Named items, sorted into kinds. An unknown number is a hard error, as
    // it is everywhere else: naming something that does not exist is a typo.
    let named: BTreeSet<i64> = opts.items.iter().copied().collect();
    let mut named_prs = Vec::new();
    let mut named_issues = Vec::new();
    for number in &named {
        match repo.item_kind(*number)? {
            ItemKind::Pr => named_prs.push(*number),
            ItemKind::Issue => named_issues.push(*number),
        }
    }
    let repo_mode = named.is_empty();
    // What this run may act on, in numbers mode: what was named, and the pull
    // requests of named issues as the sweep finds them. Anything else in
    // listen.json, pending work included, is left for a run over the
    // repository.
    let mut watching: BTreeSet<i64> = named.clone();
    // A dry run changes nothing, listen.json included, so what it previewed is
    // still there for the real run after it.
    let save = |state: &ListenState| {
        if !opts.dry_run {
            write_state(repo, state);
        }
    };

    let mut state = read_state(repo);
    if state.watermark.is_empty() || opts.since.is_some() {
        let back = opts.since.map(|d| d.as_secs()).unwrap_or(0);
        state.watermark = clock::rfc3339(now.saturating_sub(back));
        state.last_modified = None;
        log!("watching from {}", state.watermark);
    }
    for number in &named_prs {
        state.watched(*number, ItemKind::Pr);
    }
    for number in &named_issues {
        state.watched(*number, ItemKind::Issue);
    }
    log!(
        "listening to {name}{}: polling every {}s, sweeping {} every {}s. Ctrl-C to stop.",
        if repo_mode {
            String::new()
        } else {
            format!(
                " for {}",
                named
                    .iter()
                    .map(|n| format!("#{n}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        },
        cfg.listen.interval.max(FLOOR_SECS),
        if repo_mode {
            "open pull requests"
        } else {
            "the named items"
        },
        cfg.listen.sweep
    );

    let started = now;
    let mut next_poll = now;
    let mut next_sweep = now;
    let mut backoff = Backoff::default();
    let mut events_seen = 0usize;
    let mut dispatches = 0usize;
    let mut tick_failed = false;
    let mut last_prune = now;

    let ending = loop {
        if proc::interrupted() {
            break Ending::Interrupted;
        }
        let now = clock::now_secs();
        let mut events: Vec<Event> = Vec::new();

        if now >= next_poll {
            match poll(repo, &cfg.listen, &mut state, now) {
                Polled::Nothing(interval) => {
                    backoff.recovered();
                    next_poll = now + interval;
                }
                Polled::Threads(threads, interval) => {
                    backoff.recovered();
                    events.extend(events_from_threads(&threads, &mut state));
                    next_poll = now + interval;
                }
                Polled::RateLimited(wait) => {
                    logwarn!(
                        "rate limited by GitHub, waiting {} until it resets",
                        spend::clock(Duration::from_secs(wait))
                    );
                    next_poll = now + wait;
                    tick_failed = true;
                }
                Polled::Failed(why) => {
                    next_poll = now + backoff.failed("read notifications", &why);
                    tick_failed = true;
                }
            }
        }

        if now >= next_sweep {
            match sweep_rows(repo, cfg, repo_mode, &named_prs, &named_issues, &state) {
                Ok(Swept {
                    rows,
                    closed_issues,
                }) => {
                    backoff.recovered();
                    if !repo_mode {
                        watching.extend(rows.iter().map(|r| r.number));
                    }
                    events.extend(closed_issues.into_iter().map(|number| Event {
                        number,
                        kind: ItemKind::Issue,
                        trigger: Trigger::Closed,
                        who: None,
                        head: None,
                        commits: None,
                        from_thread: false,
                    }));
                    let record_head = |n: i64| {
                        repo.read_review_record(n)
                            .filter(|r| r.posted)
                            .map(|r| r.head)
                    };
                    let swept = events_from_sweep(
                        &rows,
                        &viewer,
                        &mut state,
                        &named,
                        cfg.loop_cfg.min_number,
                        &record_head,
                        repo_mode,
                    );
                    events.extend(swept);
                    next_sweep = now + cfg.listen.sweep;
                }
                Err(e) => {
                    next_sweep = now + backoff.failed("sweep the pull requests", e.last_line());
                    tick_failed = true;
                }
            }
        }

        // In numbers mode an event about anything not watched is dropped here,
        // after the watermark has moved past it, so a thread about something
        // else is read once and never again.
        for event in &events {
            if !repo_mode && !watching.contains(&event.number) {
                continue;
            }
            if event.trigger != Trigger::Closed && event.who.is_none() {
                // Nothing to look up cheaply here; the actor comes with the
                // thread only through its latest comment, which the sweep
                // does not carry.
            }
            events_seen += 1;
            log!("{}", describe(repo, event));
            if event.trigger == Trigger::Closed {
                state.items.remove(&event.number);
                state.pending.remove(&event.number);
                continue;
            }
            state.note(event, now);
        }
        save(&state);

        let due_now: Vec<i64> = state
            .pending
            .iter()
            .filter(|(n, p)| {
                (repo_mode || watching.contains(n))
                    && due(p, now, &cfg.listen, opts.once)
                    && state.items.get(n).is_none_or(|w| w.retry_after <= now)
            })
            .map(|(n, _)| *n)
            .collect();
        for number in due_now {
            let Some(mut p) = state.pending.get(&number).cloned() else {
                continue;
            };
            let named_item = named.contains(&number);
            let mention = p.triggers.contains(&Trigger::Mentioned);
            let f = match facts(repo, cfg, number, p.kind, named_item, mention) {
                Ok(f) => f,
                Err(e) => {
                    let w = state.watched(number, p.kind);
                    w.failures += 1;
                    w.retry_after = now + dispatch_backoff_secs(w.failures);
                    logwarn!("#{number}: could not read it: {}", e.last_line());
                    tick_failed = true;
                    save(&state);
                    continue;
                }
            };
            if settle(&mut p, &f) {
                if f.request_answered {
                    log!(
                        "#{number}: the review asked of you is the one on record, so that was \
                         only an update"
                    );
                } else {
                    log!("#{number}: no review is asked of you now, so that was only an update");
                }
            }
            if settle_mention(&mut p, &f) {
                log!(
                    "#{number}: nobody mentioned you since the review on record, so that was only \
                     an update"
                );
            }
            if p.triggers.contains(&Trigger::ReviewRequested) || f.request_answered {
                // Answered now, or by the review on record, whichever way it
                // arrived. A standing note or a review posted as a comment
                // leaves the request open, so the next sweep would otherwise
                // take it for the author asking again.
                state.watched(number, p.kind).requested_noticed = true;
            }
            let action = plan(&p, &f, &cfg.listen);
            match &action {
                Action::Ignore(why) => {
                    logdim!("#{number}: ignoring {why}");
                    state.pending.remove(&number);
                }
                Action::Drop => {
                    log!("#{number}: closed, no longer watched");
                    state.items.remove(&number);
                    state.pending.remove(&number);
                }
                Action::Capped(pr) => {
                    let w = state.watched(number, p.kind);
                    if !w.said_capped {
                        let what = if *pr == number {
                            "rechecked".to_string()
                        } else {
                            format!("its pull request #{pr} was rechecked")
                        };
                        log!(
                            "#{number}: {what} {} time{} already; run `spar review {pr}` to look \
                             again",
                            cfg.listen.max_rechecks,
                            plural(cfg.listen.max_rechecks as usize)
                        );
                        w.said_capped = true;
                    }
                    state.pending.remove(&number);
                }
                Action::BelongsToResume => {
                    let w = state.watched(number, p.kind);
                    if !w.said_resume {
                        log!("#{number}: in custody, `spar resume {number}` continues it");
                        w.said_resume = true;
                    }
                    state.pending.remove(&number);
                }
                action if action.runs() => {
                    if opts.dry_run {
                        log!(
                            "#{number}: would {} after {}, dry run so nothing runs",
                            action.phrase(number),
                            p.because()
                        );
                        state.pending.remove(&number);
                    } else {
                        log!(
                            "#{number}: about to {} after {}",
                            action.phrase(number),
                            p.because()
                        );
                        let acted_on = match action {
                            Action::Recheck(pr) => *pr,
                            _ => number,
                        };
                        let record_before = repo.read_review_record(acted_on);
                        let failed_before = repo.write_summary().failed;
                        let run = dispatch(agents, cfg, repo, action, number, &p);
                        dispatches += 1;
                        let spent = spend::drain();
                        if let Err(e) = repo.record_spend(&spent) {
                            logdim!("could not record what this run spent: {e}");
                        }
                        crate::cli::print_outcome(&run, &spent);
                        if proc::interrupted() {
                            log!("interrupted while working on #{number}; its worktree was kept");
                            save(&state);
                            break;
                        }
                        // The commit spar just read is not news to the next
                        // sweep. Only a record this dispatch wrote says which
                        // that was: one it left alone holds an older commit,
                        // and taking that for the head would raise the same
                        // push again on every sweep.
                        let record_after = repo.read_review_record(acted_on);
                        if record_after != record_before {
                            if let Some(record) = record_after {
                                state.watched(acted_on, ItemKind::Pr).head = Some(record.head);
                            }
                        }
                        // A review GitHub never received has not happened,
                        // whatever its findings say, and clearing its trigger
                        // would lose it for good.
                        let unposted = repo.write_summary().failed > failed_before;
                        let w = state.watched(number, p.kind);
                        // Nothing posted because the head moved under it: the
                        // pending item stays, and the next look reads the new
                        // head.
                        let moved = run.status == Status::Moved && !unposted;
                        if run.status == Status::Error || moved || unposted {
                            w.failures += 1;
                            let wait = retry_wait(moved, w.failures, &cfg.listen);
                            // From now rather than the start of the tick, which
                            // a long review leaves far behind.
                            w.retry_after = clock::now_secs() + wait;
                            let gave_up = w.failures >= MAX_FAILURES;
                            if gave_up {
                                logwarn!("#{number}: giving up on it until it changes again");
                                state.give_up(number, p.kind);
                            } else {
                                if moved {
                                    log!(
                                        "#{number}: its head moved while spar read it, so it runs \
                                         again on the new head in {}",
                                        spend::clock(Duration::from_secs(wait))
                                    );
                                } else if unposted {
                                    logwarn!(
                                        "#{number}: not everything it wrote reached GitHub, so it \
                                         runs again in {}",
                                        spend::clock(Duration::from_secs(wait))
                                    );
                                }
                                if let Some(p) = state.pending.get_mut(&number) {
                                    p.first_seen = now;
                                }
                            }
                            // A moved head failed nothing: it is still pending,
                            // and the next `--once` reads the new head.
                            if !moved || gave_up {
                                tick_failed = true;
                            }
                        } else {
                            w.failures = 0;
                            w.retry_after = 0;
                            w.last_dispatched = Some(now);
                            state.pending.remove(&number);
                        }
                    }
                }
                _ => {}
            }
            save(&state);
        }
        if proc::interrupted() {
            break Ending::Interrupted;
        }

        if opts.once {
            break Ending::Once {
                failed: tick_failed,
            };
        }
        if !repo_mode && named.iter().all(|n| !state.items.contains_key(n)) {
            log!("every named item is closed, nothing left to watch");
            break Ending::Done;
        }
        if now.saturating_sub(last_prune) >= 3600 {
            prune_seen(&mut state, now);
            last_prune = now;
            save(&state);
        }

        let acts_on = |n: i64| repo_mode || watching.contains(&n);
        let next = [next_poll, next_sweep]
            .into_iter()
            .chain(next_due(&state, &cfg.listen, &acts_on))
            .min()
            .unwrap_or(now + FLOOR_SECS);
        let wait = next.saturating_sub(clock::now_secs()).clamp(1, 3600);
        if proc::sleep_unless_interrupted(Duration::from_secs(wait)) {
            break Ending::Interrupted;
        }
    };

    save(&state);
    drop(lock);
    log!(
        "listened for {}: {events_seen} event{}, {dispatches} dispatch{}",
        spend::clock(Duration::from_secs(
            clock::now_secs().saturating_sub(started)
        )),
        plural(events_seen),
        if dispatches == 1 { "" } else { "es" }
    );
    let writes = crate::cli::report_writes(repo);
    Ok(match ending {
        Ending::Interrupted => 130.max(writes),
        Ending::Once { failed: true } => 1.max(writes),
        Ending::Once { failed: false } | Ending::Done => writes,
    })
}

fn read_state(repo: &Repo) -> ListenState {
    let path = repo.listen_state_path();
    match std::fs::read_to_string(&path) {
        Ok(text) => match serde_json::from_str::<ListenState>(&text) {
            Ok(state) => state,
            Err(e) => {
                logdim!("could not read {}: {e}. Starting fresh.", path.display());
                ListenState::default()
            }
        },
        Err(_) => ListenState::default(),
    }
}

fn write_state(repo: &Repo, state: &ListenState) {
    let mut state = state.clone();
    state.version = STATE_VERSION;
    if let Err(e) = crate::repo::write_json_atomic(&repo.listen_state_path(), &state) {
        logdim!("could not write the listen state: {e}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Author;

    fn cfg() -> ListenCfg {
        ListenCfg::default()
    }

    fn user(login: &str) -> Login {
        Login {
            login: login.into(),
            ..Login::default()
        }
    }

    fn team(slug: &str) -> Login {
        Login {
            slug: slug.into(),
            ..Login::default()
        }
    }

    fn thread(id: &str, reason: &str, kind: &str, number: i64, at: &str) -> Thread {
        Thread {
            id: id.into(),
            reason: reason.into(),
            updated_at: at.into(),
            subject: Subject {
                title: format!("thing {number}"),
                url: Some(format!(
                    "https://api.github.com/repos/o/r/{}/{number}",
                    if kind == "PullRequest" {
                        "pulls"
                    } else {
                        "issues"
                    }
                )),
                latest_comment_url: None,
                kind: kind.into(),
            },
        }
    }

    fn row(number: i64, head: &str, author: &str, state: &str) -> PrSweepRow {
        PrSweepRow {
            number,
            title: format!("PR {number}"),
            head_ref_oid: head.into(),
            author: Some(Author {
                login: author.into(),
            }),
            state: state.into(),
            ..Default::default()
        }
    }

    fn pending(kind: ItemKind, triggers: &[Trigger], now: u64) -> Pending {
        Pending {
            kind,
            first_seen: now,
            last_seen: now,
            triggers: triggers.iter().copied().collect(),
            who: Vec::new(),
            head_from: None,
            head_to: None,
        }
    }

    fn open_pr() -> Facts {
        Facts {
            number: 7,
            open: true,
            ..Default::default()
        }
    }

    fn response(status: u16, headers: &[(&str, &str)]) -> ApiResponse {
        ApiResponse {
            status,
            headers: headers
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            body: String::new(),
        }
    }

    // -- timing ----------------------------------------------------------------

    #[test]
    fn the_poll_interval_is_the_largest_of_the_config_the_header_and_the_floor() {
        let mut c = cfg();
        assert_eq!(60, poll_interval(&c, None));
        assert_eq!(90, poll_interval(&c, Some("90")));
        assert_eq!(60, poll_interval(&c, Some("30")));
        assert_eq!(60, poll_interval(&c, Some("soon")));
        c.interval = 5;
        assert_eq!(15, poll_interval(&c, None));
    }

    #[test]
    fn a_rate_limit_answer_says_how_long_to_wait_and_caps_it_at_an_hour() {
        let now = 1_000_000;
        assert_eq!(
            Some(120),
            rate_limit_wait(&response(429, &[("retry-after", "120")]), now)
        );
        assert_eq!(
            Some(600),
            rate_limit_wait(
                &response(
                    403,
                    &[
                        ("x-ratelimit-remaining", "0"),
                        ("x-ratelimit-reset", "1000600")
                    ]
                ),
                now
            )
        );
        assert_eq!(
            Some(3600),
            rate_limit_wait(&response(403, &[("retry-after", "99999")]), now)
        );
        assert_eq!(
            Some(60),
            rate_limit_wait(&response(429, &[("retry-after", "1")]), now)
        );
    }

    #[test]
    fn a_forbidden_answer_without_a_rate_limit_header_is_a_failure_not_a_wait() {
        assert_eq!(None, rate_limit_wait(&response(403, &[]), 0));
        assert_eq!(
            None,
            rate_limit_wait(&response(403, &[("x-ratelimit-remaining", "40")]), 0)
        );
        assert_eq!(
            None,
            rate_limit_wait(&response(200, &[("retry-after", "5")]), 0)
        );
    }

    #[test]
    fn next_link_reads_the_next_page_and_nothing_else() {
        let mut headers = BTreeMap::new();
        headers.insert(
            "link".to_string(),
            "<https://api.github.com/x?page=2>; rel=\"next\", <https://api.github.com/x?page=9>; rel=\"last\"".to_string(),
        );
        assert_eq!(
            Some("https://api.github.com/x?page=2".to_string()),
            next_link(&headers)
        );
        headers.insert(
            "link".to_string(),
            "<https://api.github.com/x?page=1>; rel=\"prev\"".to_string(),
        );
        assert_eq!(None, next_link(&headers));
        assert_eq!(None, next_link(&BTreeMap::new()));
    }

    // -- notifications ------------------------------------------------------------

    #[test]
    fn a_thread_becomes_an_event_keyed_by_its_number_and_reason() {
        let mut state = ListenState::default();
        let threads = vec![
            thread(
                "1",
                "review_requested",
                "PullRequest",
                7,
                "2026-10-20T10:00:00Z",
            ),
            thread("2", "mention", "Issue", 42, "2026-10-20T10:01:00Z"),
            thread("3", "comment", "PullRequest", 8, "2026-10-20T10:02:00Z"),
            thread("4", "assign", "PullRequest", 9, "2026-10-20T10:03:00Z"),
            thread("5", "team_mention", "Issue", 43, "2026-10-20T10:04:00Z"),
            thread(
                "6",
                "state_change",
                "PullRequest",
                10,
                "2026-10-20T10:05:00Z",
            ),
        ];
        let events = events_from_threads(&threads, &mut state);
        let got: Vec<(i64, ItemKind, Trigger)> = events
            .iter()
            .map(|e| (e.number, e.kind, e.trigger))
            .collect();
        assert_eq!(
            vec![
                (7, ItemKind::Pr, Trigger::ReviewRequested),
                (42, ItemKind::Issue, Trigger::Mentioned),
                (8, ItemKind::Pr, Trigger::Replied),
                (9, ItemKind::Pr, Trigger::Assigned),
                (43, ItemKind::Issue, Trigger::Mentioned),
                (10, ItemKind::Pr, Trigger::Replied),
            ],
            got
        );
    }

    #[test]
    fn a_thread_seen_at_the_same_update_time_is_not_an_event_twice() {
        let mut state = ListenState::default();
        let same = vec![thread(
            "1",
            "comment",
            "PullRequest",
            7,
            "2026-10-20T10:00:00Z",
        )];
        assert_eq!(1, events_from_threads(&same, &mut state).len());
        assert_eq!(0, events_from_threads(&same, &mut state).len());
        let moved = vec![thread(
            "1",
            "comment",
            "PullRequest",
            7,
            "2026-10-20T10:05:00Z",
        )];
        assert_eq!(1, events_from_threads(&moved, &mut state).len());
    }

    #[test]
    fn a_thread_about_a_release_or_discussion_is_ignored() {
        let mut state = ListenState::default();
        let threads = vec![
            thread("1", "subscribed", "Release", 1, "2026-10-20T10:00:00Z"),
            thread("2", "mention", "Discussion", 2, "2026-10-20T10:01:00Z"),
            Thread {
                subject: Subject {
                    url: None,
                    kind: "PullRequest".into(),
                    ..Default::default()
                },
                ..thread("3", "comment", "PullRequest", 3, "2026-10-20T10:02:00Z")
            },
        ];
        assert!(events_from_threads(&threads, &mut state).is_empty());
        // Seen and past the watermark all the same, so they are never read
        // again.
        assert_eq!(3, state.seen.len());
    }

    #[test]
    fn the_watermark_advances_to_the_newest_update_seen() {
        let mut state = ListenState {
            watermark: "2026-10-20T09:00:00Z".into(),
            ..Default::default()
        };
        let threads = vec![
            thread("1", "comment", "PullRequest", 7, "2026-10-20T10:02:00Z"),
            thread("2", "comment", "PullRequest", 8, "2026-10-20T10:01:00Z"),
        ];
        events_from_threads(&threads, &mut state);
        assert_eq!("2026-10-20T10:02:00Z", state.watermark);
    }

    // -- the sweep ----------------------------------------------------------------

    fn no_record(_: i64) -> Option<String> {
        None
    }

    #[test]
    fn a_sweep_notices_a_head_that_moved_and_says_it_once() {
        let mut state = ListenState::default();
        let named = BTreeSet::new();
        let first = events_from_sweep(
            &[row(7, "aaa", "alice", "OPEN")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            true,
        );
        assert!(first.is_empty(), "{first:?}");
        let moved = events_from_sweep(
            &[row(7, "bbb", "alice", "OPEN")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            true,
        );
        assert_eq!(1, moved.len());
        assert_eq!(Trigger::Pushed, moved[0].trigger);
        assert_eq!(Some(("aaa".to_string(), "bbb".to_string())), moved[0].head);
        let again = events_from_sweep(
            &[row(7, "bbb", "alice", "OPEN")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            true,
        );
        assert!(again.is_empty(), "{again:?}");
        assert_eq!("alice", state.items[&7].author);
    }

    #[test]
    fn the_first_sweep_treats_a_reviewed_pull_request_that_already_moved_as_due() {
        let mut state = ListenState::default();
        let record = |n: i64| (n == 7).then(|| "aaa".to_string());
        let events = events_from_sweep(
            &[row(7, "bbb", "alice", "OPEN"), row(8, "ccc", "bob", "OPEN")],
            "me",
            &mut state,
            &BTreeSet::new(),
            0,
            &record,
            true,
        );
        assert_eq!(1, events.len());
        assert_eq!(7, events[0].number);
        assert_eq!(Trigger::Pushed, events[0].trigger);
    }

    #[test]
    fn a_sweep_notices_a_review_request_once_not_every_five_minutes() {
        let mut state = ListenState::default();
        let mut asked = row(7, "aaa", "alice", "OPEN");
        asked.review_requests = vec![user("ME")];
        asked.assignees = vec![user("me")];
        let rows = [asked];
        let first = events_from_sweep(
            &rows,
            "me",
            &mut state,
            &BTreeSet::new(),
            0,
            &no_record,
            true,
        );
        let triggers: BTreeSet<Trigger> = first.iter().map(|e| e.trigger).collect();
        assert_eq!(
            [Trigger::ReviewRequested, Trigger::Assigned]
                .into_iter()
                .collect::<BTreeSet<_>>(),
            triggers
        );
        let second = events_from_sweep(
            &rows,
            "me",
            &mut state,
            &BTreeSet::new(),
            0,
            &no_record,
            true,
        );
        assert!(second.is_empty(), "{second:?}");
    }

    #[test]
    fn a_sweep_notices_a_review_requested_again_after_a_review() {
        let mut state = ListenState::default();
        let mut asked = row(7, "aaa", "alice", "OPEN");
        asked.review_requests = vec![user("me")];
        let asked = [asked];
        let reviewed = [row(7, "aaa", "alice", "OPEN")];
        let mut sweep = |rows: &[PrSweepRow]| -> Vec<Trigger> {
            events_from_sweep(
                rows,
                "me",
                &mut state,
                &BTreeSet::new(),
                0,
                &no_record,
                true,
            )
            .iter()
            .map(|e| e.trigger)
            .collect()
        };
        assert_eq!(vec![Trigger::ReviewRequested], sweep(&asked));
        // The review cleared the request.
        assert!(sweep(&reviewed).is_empty());
        assert!(sweep(&reviewed).is_empty());
        // The author asked again.
        assert_eq!(vec![Trigger::ReviewRequested], sweep(&asked));
        assert!(sweep(&asked).is_empty());
    }

    #[test]
    fn a_sweep_drops_a_pull_request_that_closed_or_vanished() {
        let mut state = ListenState::default();
        let named = BTreeSet::new();
        events_from_sweep(
            &[row(7, "aaa", "alice", "OPEN"), row(8, "bbb", "bob", "OPEN")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            true,
        );
        let events = events_from_sweep(
            &[row(7, "aaa", "alice", "MERGED")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            true,
        );
        let closed: Vec<i64> = events
            .iter()
            .filter(|e| e.trigger == Trigger::Closed)
            .map(|e| e.number)
            .collect();
        assert_eq!(vec![7, 8], closed);

        // In numbers mode a pull request missing from the rows means it was
        // not asked about, not that it closed.
        let mut state = ListenState::default();
        let named: BTreeSet<i64> = [7, 8].into_iter().collect();
        events_from_sweep(
            &[row(7, "aaa", "alice", "OPEN"), row(8, "bbb", "bob", "OPEN")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            false,
        );
        let events = events_from_sweep(
            &[row(7, "aaa", "alice", "OPEN")],
            "me",
            &mut state,
            &named,
            0,
            &no_record,
            false,
        );
        assert!(events.is_empty(), "{events:?}");
    }

    #[test]
    fn a_sweep_ignores_a_number_below_the_floor_unless_it_was_named() {
        let mut state = ListenState::default();
        let named: BTreeSet<i64> = [3].into_iter().collect();
        let record = |_: i64| Some("old".to_string());
        let events = events_from_sweep(
            &[
                row(3, "new", "alice", "OPEN"),
                row(4, "new", "alice", "OPEN"),
                row(500, "new", "alice", "OPEN"),
            ],
            "me",
            &mut state,
            &named,
            480,
            &record,
            true,
        );
        let numbers: Vec<i64> = events.iter().map(|e| e.number).collect();
        assert_eq!(vec![3, 500], numbers);
        assert!(!state.items.contains_key(&4));
    }

    /// A notification puts a pull request below the floor on the watch, and
    /// the sweep, which skips it, used to call it closed.
    #[test]
    fn a_pull_request_below_the_floor_that_is_still_open_is_not_called_closed() {
        let mut state = ListenState::default();
        state.watched(4, ItemKind::Pr);
        let events = events_from_sweep(
            &[
                row(4, "new", "alice", "OPEN"),
                row(500, "new", "alice", "OPEN"),
            ],
            "me",
            &mut state,
            &BTreeSet::new(),
            480,
            &no_record,
            true,
        );
        assert!(
            events.iter().all(|e| e.trigger != Trigger::Closed),
            "{events:?}"
        );
        let gone = events_from_sweep(
            &[row(500, "new", "alice", "OPEN")],
            "me",
            &mut state,
            &BTreeSet::new(),
            480,
            &no_record,
            true,
        );
        assert_eq!(
            vec![(4, Trigger::Closed)],
            gone.iter()
                .map(|e| (e.number, e.trigger))
                .collect::<Vec<_>>()
        );
    }

    // -- the table -------------------------------------------------------------------

    #[test]
    fn a_review_request_nobody_is_still_making_is_only_an_update() {
        // react-native-pubky#45: the thread began as a review request, so
        // GitHub kept calling it one when spar's own approval updated it.
        let threads = [thread(
            "1",
            "review_requested",
            "PullRequest",
            7,
            "2026-10-21T14:51:16Z",
        )];
        let events = events_from_threads(&threads, &mut ListenState::default());
        let mut waiting = BTreeMap::new();
        for e in &events {
            merge(&mut waiting, e, 0);
        }
        let reviewed = Facts {
            has_posted_record: true,
            ..open_pr()
        };
        let mut p = waiting.remove(&7).expect("pending");
        assert!(settle(&mut p, &reviewed));
        assert_eq!(
            [Trigger::Replied].into_iter().collect::<BTreeSet<_>>(),
            p.triggers
        );
        assert!(matches!(plan(&p, &reviewed, &cfg()), Action::Ignore(_)));

        // On a pull request spar never reviewed it is not a reason to start.
        let mut p = pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0);
        assert!(settle(&mut p, &open_pr()));
        assert!(matches!(plan(&p, &open_pr(), &cfg()), Action::Ignore(_)));

        // A request still standing is left as it is.
        let asked = Facts {
            review_pending: true,
            ..open_pr()
        };
        let mut p = pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0);
        assert!(!settle(&mut p, &asked));
        assert!(p.triggers.contains(&Trigger::ReviewRequested));
        assert_eq!(Action::Review, plan(&p, &asked, &cfg()));

        // A request still standing that the review on record answered is
        // only an update too, and an update asks for no second look.
        let answered = Facts {
            has_posted_record: true,
            review_pending: true,
            request_answered: true,
            ..open_pr()
        };
        let mut p = pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0);
        assert!(settle(&mut p, &answered));
        assert_eq!(
            [Trigger::Replied].into_iter().collect::<BTreeSet<_>>(),
            p.triggers
        );
        assert!(matches!(plan(&p, &answered, &cfg()), Action::Ignore(_)));

        // Nothing to settle without a request.
        let mut p = pending(ItemKind::Pr, &[Trigger::Pushed], 0);
        assert!(!settle(&mut p, &open_pr()));
        assert_eq!(
            [Trigger::Pushed].into_iter().collect::<BTreeSet<_>>(),
            p.triggers
        );
    }

    #[test]
    fn a_review_request_counts_for_the_viewer_or_a_team_the_viewer_is_in() {
        let teams = |team: &str| match team {
            "example/ours" => Some(true),
            "example/theirs" => Some(false),
            _ => None,
        };
        let pending = |requests: &[Login]| review_pending(requests, "me", &teams);
        assert!(!pending(&[]));
        assert!(pending(&[user("ME")]));
        assert!(!pending(&[user("alice")]));
        assert!(pending(&[team("example/ours")]));
        // Approving clears the viewer's own request and leaves a CODEOWNERS
        // team the viewer is not in, which used to keep the request alive.
        assert!(!pending(&[team("example/theirs"), user("alice")]));
        assert!(pending(&[team("example/theirs"), team("example/ours")]));
        // A team GitHub would not answer for keeps the request.
        assert!(pending(&[team("example/unknown")]));
        // Asked by name, no team is looked up.
        let never = |_: &str| -> Option<bool> { panic!("looked a team up") };
        assert!(review_pending(
            &[team("example/ours"), user("me")],
            "me",
            &never
        ));
    }

    /// A review posted as a comment leaves its request open, and a first sweep
    /// has never seen that request, so it read as the author asking again and
    /// got a "nothing has changed" note on every pull request reviewed that way.
    #[test]
    fn a_request_made_before_the_review_on_record_was_answered_by_it() {
        let teams = |team: &str| match team {
            "example/ours" => Some(true),
            _ => Some(false),
        };
        let made = |at: &str, who: Login| ReviewRequested { at: at.into(), who };
        let answered = |requests: &[ReviewRequested]| {
            request_answered(requests, "me", &teams, "2026-10-20T12:00:00Z")
        };
        assert!(answered(&[made("2026-10-20T11:00:00Z", user("me"))]));
        assert!(answered(&[made("2026-10-20T12:00:00Z", user("ME"))]));
        assert!(answered(&[made(
            "2026-10-20T11:00:00Z",
            team("example/ours")
        )]));
        // Asked again after the review: the newest request decides.
        assert!(!answered(&[
            made("2026-10-20T11:00:00Z", user("me")),
            made("2026-10-20T13:00:00Z", user("me")),
        ]));
        assert!(!answered(&[
            made("2026-10-20T11:00:00Z", user("me")),
            made("2026-10-20T13:00:00Z", team("example/ours")),
        ]));
        // Somebody else asked later, which asks nothing of the viewer.
        assert!(answered(&[
            made("2026-10-20T11:00:00Z", user("me")),
            made("2026-10-20T13:00:00Z", user("alice")),
            made("2026-10-20T13:00:00Z", team("example/theirs")),
        ]));
        // Nothing on the timeline to go by, or no time to compare with.
        assert!(!answered(&[]));
        assert!(!answered(&[made("2026-10-20T11:00:00Z", user("alice"))]));
        assert!(!answered(&[made("", user("me"))]));
        assert!(!request_answered(
            &[made("2026-10-20T11:00:00Z", user("me"))],
            "me",
            &teams,
            ""
        ));
    }

    #[test]
    fn a_review_request_or_a_mention_on_a_reviewed_pull_request_is_a_recheck() {
        let f = Facts {
            has_posted_record: true,
            ..open_pr()
        };
        for triggers in [
            &[Trigger::ReviewRequested][..],
            &[Trigger::Mentioned],
            &[Trigger::Pushed, Trigger::Replied, Trigger::ReviewRequested],
        ] {
            assert_eq!(
                Action::Recheck(7),
                plan(&pending(ItemKind::Pr, triggers, 0), &f, &cfg()),
                "{triggers:?}"
            );
        }
    }

    /// reardencode/rbitcoin#1137: another bot's review on a pull request spar
    /// had approved, with no new commit and nobody asking, got a second look
    /// that said nothing new at length.
    #[test]
    fn a_push_a_reply_or_an_assignment_on_a_reviewed_pull_request_asks_for_nothing() {
        let f = Facts {
            has_posted_record: true,
            ..open_pr()
        };
        for triggers in [
            &[Trigger::Pushed][..],
            &[Trigger::Replied],
            &[Trigger::Assigned],
            &[Trigger::Pushed, Trigger::Replied],
        ] {
            assert!(
                matches!(
                    plan(&pending(ItemKind::Pr, triggers, 0), &f, &cfg()),
                    Action::Ignore(_)
                ),
                "{triggers:?}"
            );
        }
    }

    #[test]
    fn a_mention_from_before_the_review_on_record_is_only_an_update() {
        let reviewed = Facts {
            has_posted_record: true,
            ..open_pr()
        };
        let mut p = pending(ItemKind::Pr, &[Trigger::Mentioned], 0);
        assert!(settle_mention(&mut p, &reviewed));
        assert_eq!(
            [Trigger::Replied].into_iter().collect::<BTreeSet<_>>(),
            p.triggers
        );
        assert!(matches!(plan(&p, &reviewed, &cfg()), Action::Ignore(_)));

        // Made since the review, it asks.
        let asked = Facts {
            mentioned: true,
            ..reviewed.clone()
        };
        let mut p = pending(ItemKind::Pr, &[Trigger::Mentioned], 0);
        assert!(!settle_mention(&mut p, &asked));
        assert_eq!(Action::Recheck(7), plan(&p, &asked, &cfg()));

        // On a pull request spar never reviewed there is no review to be
        // older than, and a mention starts the first one.
        let mut p = pending(ItemKind::Pr, &[Trigger::Mentioned], 0);
        assert!(!settle_mention(&mut p, &open_pr()));
        assert_eq!(Action::Review, plan(&p, &open_pr(), &cfg()));

        // An issue is held to its reviewed pull request's review.
        let linked = Facts {
            number: 42,
            open: true,
            linked_pr_with_record: Some(108),
            ..Default::default()
        };
        let mut p = pending(ItemKind::Issue, &[Trigger::Mentioned], 0);
        assert!(settle_mention(&mut p, &linked));
        assert!(matches!(plan(&p, &linked, &cfg()), Action::Ignore(_)));
        let asked = Facts {
            mentioned: true,
            ..linked
        };
        let mut p = pending(ItemKind::Issue, &[Trigger::Mentioned], 0);
        assert!(!settle_mention(&mut p, &asked));
        assert_eq!(Action::Recheck(108), plan(&p, &asked, &cfg()));
    }

    #[test]
    fn a_review_request_or_an_assignment_on_an_unreviewed_pull_request_follows_the_config() {
        let f = open_pr();
        let mut c = cfg();
        assert_eq!(
            Action::Review,
            plan(
                &pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0),
                &f,
                &c
            )
        );
        assert_eq!(
            Action::Review,
            plan(&pending(ItemKind::Pr, &[Trigger::Assigned], 0), &f, &c)
        );
        assert_eq!(
            Action::Review,
            plan(&pending(ItemKind::Pr, &[Trigger::Mentioned], 0), &f, &c)
        );
        c.on_review_requested = ReviewOrIgnore::Ignore;
        c.on_assigned = ReviewOrIgnore::Ignore;
        assert!(matches!(
            plan(
                &pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0),
                &f,
                &c
            ),
            Action::Ignore(_)
        ));
        assert!(matches!(
            plan(&pending(ItemKind::Pr, &[Trigger::Assigned], 0), &f, &c),
            Action::Ignore(_)
        ));
        // A mention is always answered with a review.
        assert_eq!(
            Action::Review,
            plan(&pending(ItemKind::Pr, &[Trigger::Mentioned], 0), &f, &c)
        );
    }

    #[test]
    fn a_push_to_an_unreviewed_pull_request_is_ignored_unless_it_was_named() {
        let f = open_pr();
        assert!(matches!(
            plan(&pending(ItemKind::Pr, &[Trigger::Pushed], 0), &f, &cfg()),
            Action::Ignore(_)
        ));
        assert!(matches!(
            plan(&pending(ItemKind::Pr, &[Trigger::Replied], 0), &f, &cfg()),
            Action::Ignore(_)
        ));
        let named = Facts {
            named: true,
            ..open_pr()
        };
        assert_eq!(
            Action::Review,
            plan(
                &pending(ItemKind::Pr, &[Trigger::Pushed], 0),
                &named,
                &cfg()
            )
        );
        assert_eq!(
            Action::Review,
            plan(
                &pending(ItemKind::Pr, &[Trigger::Replied], 0),
                &named,
                &cfg()
            )
        );
    }

    #[test]
    fn your_own_pull_request_follows_on_own_pr_and_a_push_to_it_is_ignored() {
        let f = Facts {
            author_is_viewer: true,
            has_posted_record: true,
            ..open_pr()
        };
        let mut c = cfg();
        assert_eq!(
            Action::Checkin { reply_only: false },
            plan(&pending(ItemKind::Pr, &[Trigger::Replied], 0), &f, &c)
        );
        assert_eq!(
            Action::Checkin { reply_only: false },
            plan(
                &pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0),
                &f,
                &c
            )
        );
        assert!(matches!(
            plan(&pending(ItemKind::Pr, &[Trigger::Pushed], 0), &f, &c),
            Action::Ignore(_)
        ));
        c.on_own_pr = OwnPr::Reply;
        assert_eq!(
            Action::Checkin { reply_only: true },
            plan(&pending(ItemKind::Pr, &[Trigger::Mentioned], 0), &f, &c)
        );
        c.on_own_pr = OwnPr::Ignore;
        assert!(matches!(
            plan(&pending(ItemKind::Pr, &[Trigger::Replied], 0), &f, &c),
            Action::Ignore(_)
        ));
    }

    #[test]
    fn a_pull_request_in_custody_belongs_to_resume_and_a_capped_one_waits_for_a_person() {
        let custody = Facts {
            has_custody_state: true,
            ..open_pr()
        };
        assert_eq!(
            Action::BelongsToResume,
            plan(
                &pending(ItemKind::Pr, &[Trigger::Pushed], 0),
                &custody,
                &cfg()
            )
        );
        let capped = Facts {
            has_posted_record: true,
            recheck_capped: true,
            ..open_pr()
        };
        assert_eq!(
            Action::Capped(7),
            plan(
                &pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0),
                &capped,
                &cfg()
            )
        );
        assert!(matches!(
            plan(
                &pending(ItemKind::Pr, &[Trigger::Pushed], 0),
                &capped,
                &cfg()
            ),
            Action::Ignore(_)
        ));
    }

    /// The issue route used to recheck its pull request unconditionally, so a
    /// mention on the issue went round the cap and the own pull request rule
    /// both.
    #[test]
    fn an_issue_mention_keeps_to_its_pull_requests_cap_and_owner() {
        let linked = Facts {
            number: 42,
            open: true,
            linked_pr_with_record: Some(108),
            ..Default::default()
        };
        let capped = Facts {
            recheck_capped: true,
            ..linked.clone()
        };
        assert_eq!(
            Action::Capped(108),
            plan(
                &pending(ItemKind::Issue, &[Trigger::Mentioned], 0),
                &capped,
                &cfg()
            )
        );
        let own = Facts {
            author_is_viewer: true,
            ..linked
        };
        assert!(matches!(
            plan(
                &pending(ItemKind::Issue, &[Trigger::Mentioned], 0),
                &own,
                &cfg()
            ),
            Action::Ignore(_)
        ));
    }

    #[test]
    fn an_issue_mention_without_a_pull_request_is_ignored_and_with_one_rechecks_it() {
        let issue = Facts {
            number: 42,
            open: true,
            ..Default::default()
        };
        assert!(matches!(
            plan(
                &pending(ItemKind::Issue, &[Trigger::Mentioned], 0),
                &issue,
                &cfg()
            ),
            Action::Ignore(_)
        ));
        assert!(matches!(
            plan(
                &pending(ItemKind::Issue, &[Trigger::Replied], 0),
                &issue,
                &cfg()
            ),
            Action::Ignore(_)
        ));
        let linked = Facts {
            linked_pr_with_record: Some(108),
            ..issue.clone()
        };
        assert_eq!(
            Action::Recheck(108),
            plan(
                &pending(ItemKind::Issue, &[Trigger::Mentioned], 0),
                &linked,
                &cfg()
            )
        );
        // Only a mention asks. An issue thread that began with an assignment
        // says so on every later comment, and a comment asks for nothing, on a
        // named issue too.
        assert!(matches!(
            plan(
                &pending(ItemKind::Issue, &[Trigger::Assigned], 0),
                &linked,
                &cfg()
            ),
            Action::Ignore(_)
        ));
        let named = Facts {
            named: true,
            ..linked
        };
        assert!(matches!(
            plan(
                &pending(ItemKind::Issue, &[Trigger::Replied], 0),
                &named,
                &cfg()
            ),
            Action::Ignore(_)
        ));
    }

    #[test]
    fn a_closed_item_is_dropped_and_one_below_the_floor_is_ignored_unless_named() {
        let closed = Facts {
            open: false,
            has_posted_record: true,
            ..open_pr()
        };
        assert_eq!(
            Action::Drop,
            plan(
                &pending(ItemKind::Pr, &[Trigger::Pushed], 0),
                &closed,
                &cfg()
            )
        );
        let f = Facts {
            has_posted_record: true,
            ..open_pr()
        };
        assert_eq!(
            Action::Drop,
            plan(
                &pending(ItemKind::Pr, &[Trigger::Pushed, Trigger::Closed], 0),
                &f,
                &cfg()
            )
        );
        let low = Facts {
            below_floor: true,
            has_posted_record: true,
            ..open_pr()
        };
        assert!(matches!(
            plan(&pending(ItemKind::Pr, &[Trigger::Pushed], 0), &low, &cfg()),
            Action::Ignore(_)
        ));
        let named_low = Facts { named: true, ..low };
        assert_eq!(
            Action::Recheck(7),
            plan(
                &pending(ItemKind::Pr, &[Trigger::ReviewRequested], 0),
                &named_low,
                &cfg()
            )
        );
    }

    // -- settling --------------------------------------------------------------------

    #[test]
    fn an_item_is_due_once_quiet_for_the_settle_time_or_at_max_wait_anyway() {
        let c = cfg();
        let mut p = pending(ItemKind::Pr, &[Trigger::Pushed], 1000);
        assert!(!due(&p, 1000, &c, false));
        assert!(!due(&p, 1000 + c.settle - 1, &c, false));
        assert!(due(&p, 1000 + c.settle, &c, false));
        // Noise every minute keeps resetting the quiet period.
        p.last_seen = 1000 + c.max_wait - 30;
        assert!(!due(&p, 1000 + c.max_wait - 1, &c, false));
        assert!(due(&p, 1000 + c.max_wait, &c, false));
        assert!(due(&p, 1000, &c, true), "--once waits for nothing");
    }

    #[test]
    fn events_merge_into_one_pending_record_per_item_and_the_next_due_is_the_earliest() {
        let c = cfg();
        let mut pending = BTreeMap::new();
        let push = Event {
            number: 7,
            kind: ItemKind::Pr,
            trigger: Trigger::Pushed,
            who: None,
            head: Some(("aaa".into(), "bbb".into())),
            commits: None,
            from_thread: false,
        };
        merge(&mut pending, &push, 1000);
        let reply = Event {
            trigger: Trigger::Replied,
            who: Some("alice".into()),
            head: Some(("bbb".into(), "ccc".into())),
            ..push.clone()
        };
        merge(&mut pending, &reply, 1060);
        let other = Event {
            number: 8,
            ..push.clone()
        };
        merge(&mut pending, &other, 1100);
        assert_eq!(2, pending.len());
        let p = &pending[&7];
        assert_eq!(1000, p.first_seen);
        assert_eq!(1060, p.last_seen);
        assert_eq!(Some("aaa".to_string()), p.head_from);
        assert_eq!(Some("ccc".to_string()), p.head_to);
        assert_eq!(vec!["alice".to_string()], p.who);
        assert_eq!("a push and a reply", p.because());
        let mut state = ListenState {
            pending,
            ..Default::default()
        };
        let all = |_: i64| true;
        assert_eq!(Some(1060 + c.settle), next_due(&state, &c, &all));
        assert_eq!(None, next_due(&ListenState::default(), &c, &all));

        // Waiting out a failure is not being due, or the loop wakes every
        // second until the wait ends.
        state.watched(7, ItemKind::Pr).retry_after = 5000;
        assert_eq!(Some(1100 + c.settle), next_due(&state, &c, &all));
        state.watched(8, ItemKind::Pr).retry_after = 6000;
        assert_eq!(Some(5000), next_due(&state, &c, &all));
        // Nor is something this run does not act on.
        assert_eq!(Some(6000), next_due(&state, &c, &|n| n == 8));
    }

    // -- durations, state, backoff ------------------------------------------------------

    #[test]
    fn since_accepts_minutes_hours_days_and_combinations() {
        assert_eq!(Duration::from_secs(1800), parse_duration("30m").unwrap());
        assert_eq!(Duration::from_secs(7200), parse_duration("2h").unwrap());
        assert_eq!(Duration::from_secs(86_400), parse_duration("1d").unwrap());
        assert_eq!(
            Duration::from_secs(5400),
            parse_duration(" 1h30m ").unwrap()
        );
        assert_eq!(Duration::from_secs(45), parse_duration("45s").unwrap());
    }

    #[test]
    fn since_rejects_a_bare_number_and_says_what_it_takes() {
        for bad in ["", "30", "2 hours", "h", "1w", "1h30"] {
            let err = parse_duration(bad).unwrap_err().to_string();
            assert!(err.contains("like 30m, 2h or 1d"), "{bad:?}: {err}");
        }
    }

    #[test]
    fn listen_state_round_trips_through_json_and_old_seen_entries_are_pruned() {
        let mut state = ListenState {
            version: STATE_VERSION,
            watermark: "2026-10-20T10:00:00Z".into(),
            last_modified: Some("Tue, 20 Oct 2026 10:00:00 GMT".into()),
            ..Default::default()
        };
        state
            .seen
            .insert("old".into(), "2026-10-01T10:00:00Z".into());
        state
            .seen
            .insert("new".into(), "2026-10-20T09:00:00Z".into());
        state.seen.insert("junk".into(), "yesterday".into());
        state.watched(7, ItemKind::Pr).head = Some("aaa".into());
        state
            .pending
            .insert(7, pending(ItemKind::Pr, &[Trigger::Pushed], 5));
        let text = serde_json::to_string_pretty(&state).unwrap();
        assert!(text.contains("\"pushed\""), "{text}");
        assert!(text.contains("\"kind\": \"pr\""), "{text}");
        let back: ListenState = serde_json::from_str(&text).unwrap();
        assert_eq!(state, back);

        let now = clock::parse_rfc3339("2026-10-20T10:00:00Z").unwrap();
        prune_seen(&mut state, now);
        let left: Vec<&String> = state.seen.keys().collect();
        assert_eq!(vec!["junk", "new"], left);
    }

    #[test]
    fn gh_failures_back_off_from_a_minute_to_fifteen_and_dispatches_from_fifteen_to_six_hours() {
        assert_eq!(60, backoff_secs(1));
        assert_eq!(120, backoff_secs(2));
        assert_eq!(480, backoff_secs(4));
        assert_eq!(900, backoff_secs(5));
        assert_eq!(900, backoff_secs(40));
        assert_eq!(900, dispatch_backoff_secs(1));
        assert_eq!(3600, dispatch_backoff_secs(3));
        assert_eq!(6 * 3600, dispatch_backoff_secs(9));
    }

    /// A pull request can sit minutes behind its branch. A look that stops
    /// for that, or for a push while it ran, goes again once the push settles,
    /// not a quarter of an hour later and doubling.
    #[test]
    fn a_head_that_moved_runs_again_once_it_settles_and_a_failure_backs_off() {
        let c = cfg();
        for failures in [1, 2, 4] {
            assert_eq!(c.settle, retry_wait(true, failures, &c));
            assert_eq!(
                dispatch_backoff_secs(failures),
                retry_wait(false, failures, &c)
            );
        }
        let quick = ListenCfg { settle: 1, ..cfg() };
        assert_eq!(FLOOR_SECS, retry_wait(true, 1, &quick));
    }

    /// A first review given up on while GitHub lagged came back as the push
    /// alone once GitHub caught up, and a push to a pull request spar has not
    /// reviewed is ignored, so the request was lost for good.
    #[test]
    fn giving_up_holds_what_the_item_was_waiting_on_until_it_changes() {
        let mut state = ListenState::default();
        let asked = Event {
            number: 7,
            kind: ItemKind::Pr,
            trigger: Trigger::ReviewRequested,
            who: None,
            head: None,
            commits: None,
            from_thread: true,
        };
        state.note(&asked, 0);
        state.give_up(7, ItemKind::Pr);
        assert!(state.pending.is_empty(), "{state:?}");
        assert_eq!(
            [Trigger::ReviewRequested]
                .into_iter()
                .collect::<BTreeSet<_>>(),
            state.items[&7].held
        );

        let shown = Event {
            trigger: Trigger::Pushed,
            head: Some(("aaa".into(), "bbb".into())),
            from_thread: false,
            ..asked.clone()
        };
        state.note(&shown, 600);
        let p = &state.pending[&7];
        assert_eq!(
            [Trigger::Pushed, Trigger::ReviewRequested]
                .into_iter()
                .collect::<BTreeSet<_>>(),
            p.triggers
        );
        assert!(state.items[&7].held.is_empty(), "{state:?}");
        let asked_now = Facts {
            review_pending: true,
            ..open_pr()
        };
        assert_eq!(Action::Review, plan(p, &asked_now, &cfg()));
        // Brought back once, not on every change after.
        state.pending.clear();
        state.note(&shown, 700);
        assert_eq!(
            [Trigger::Pushed].into_iter().collect::<BTreeSet<_>>(),
            state.pending[&7].triggers
        );
    }

    #[test]
    fn number_from_url_reads_the_last_segment() {
        assert_eq!(
            Some(108),
            number_from_url("https://api.github.com/repos/o/r/pulls/108")
        );
        assert_eq!(
            Some(42),
            number_from_url("https://api.github.com/repos/o/r/issues/42/")
        );
        assert_eq!(
            None,
            number_from_url("https://api.github.com/repos/o/r/pulls")
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_held_lock_refuses_a_second_listener_however_old_and_a_left_file_is_taken_over() {
        let dir = std::env::temp_dir().join(format!(
            "spar-listen-lock-{}-{}",
            std::process::id(),
            clock::now_secs()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("listen.lock");

        // Held is held, however long ago it was taken: nothing has to keep a
        // lock fresh while one review runs for an hour.
        let held = Lock::at(path.clone(), 1000).expect("first lock");
        for now in [1000, 1000 + 86_400] {
            let err = Lock::at(path.clone(), now).unwrap_err().to_string();
            assert!(err.contains("already watching"), "{err}");
            assert!(err.contains(&std::process::id().to_string()), "{err}");
        }
        assert!(path.exists(), "a refused listener leaves the lock alone");
        drop(held);
        assert!(!path.exists(), "dropping the lock removes the file");

        // A file a listener left behind, even one naming a pid that is alive,
        // as a reboot can arrange, holds nothing.
        std::fs::write(
            &path,
            serde_json::to_string(&LockFile {
                pid: std::process::id(),
                started: "x".into(),
            })
            .unwrap(),
        )
        .unwrap();
        let taken = Lock::at(path.clone(), 1000).expect("a left file is taken over");
        drop(taken);
        let _ = std::fs::remove_dir_all(&dir);
    }
}