snyvi 1.28.0

A fast, beautiful viewer for the documents your agents produce
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
//! The daemon updates itself.
//!
//! At three or four releases a day, "run the installer again" is not an
//! update process. So the daemon is the updater: it reads `latest.json` off
//! the newest GitHub release a few times a day, stages the downloads for its
//! own channel under `<data>/updates/<version>/`, checks every sha256 the
//! manifest names, and -- once a day, at a quiet moment, through the doors in
//! `door` below -- swaps the files by `rename` and hands off to the new binary
//! with the planned restart of `server.rs`. The window shows a pill and
//! clicks it; the CLI has a manual twin in `snyvi update`; the page never
//! talks to GitHub.
//!
//! What is trusted: the manifest is signed with minisign and the public key
//! is compiled in (`packaging/minisign.pub`), so a manifest that did not come
//! from the release job is refused before a byte is downloaded. The sha256 in
//! the manifest is checked as each download lands and once more on the file
//! just placed, so a truncated download or a full disk is a retry, never a
//! half-written binary. The old file stays beside the new one as `.prev`, and
//! `snyvi update --back` or a successor that never answers puts it back.
//!
//! What is silent: every channel where the files are the reader's own -- a
//! tarball anywhere, the bundle in Applications, the folder Inno or Scoop
//! made on Windows. Told, never touched: a `.deb` (root owns it) and a cargo
//! build (the reader chose to compile). Off: a dev build, which is anything
//! under a `target/` directory or a daemon serving `ui/` off disk.
//!
//! Two clocks. Checks are every six hours or so on a monotonic timer, since
//! they cost one small GET and mostly a 304. Applies are at most one a day,
//! counted from `last_applied` on the wall clock and written to disk, so a
//! restart does not open a second slot and a crash-restart does not move it:
//! only the planned restart's marker says an apply happened. The
//! `hotfix_below` field in the manifest is the one thing that moves a machine
//! sooner, and it is set by hand in the release job.

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::Duration;

/// The release key. Its private half is a repository secret the release job
/// signs with; a manifest anyone else wrote fails here.
pub const PUBLIC_KEY: &str = include_str!("../packaging/minisign.pub");

/// Where the newest release's manifest is, and where a release's downloads
/// are. GitHub serves both as static files with no rate limit.
const REPO: &str = "snymrova/snyvi";

/// The floor: an automatic apply at most this long after the last one, plus
/// up to `SLOT_JITTER` so a fleet does not move at once.
const SLOT: i64 = 24 * 3600;
const SLOT_JITTER: i64 = 3600;
/// Between checks, on a monotonic timer, give or take `CHECK_JITTER`.
pub const CHECK_EVERY: Duration = Duration::from_secs(6 * 3600);
pub const CHECK_JITTER: Duration = Duration::from_secs(30 * 60);
/// The first check after a start: late enough not to race the window's first
/// paint, early enough that `Check now` finds an answer from this morning.
pub const FIRST_CHECK: Duration = Duration::from_secs(30);
pub const FIRST_CHECK_JITTER: Duration = Duration::from_secs(60);
/// A window that has been in the background this long, with the panes
/// quiet, is one nobody is reading: door 2.
pub const BACKGROUND: Duration = Duration::from_secs(10 * 60);
/// A staged update the pill has shown for a day without a click is one the
/// reader is not going to click: the pill turns amber, and says why.
pub const PILL_AMBER: i64 = 24 * 3600;
/// How long an applied version runs before its `.prev` may go.
const KEEP_PREV: i64 = 24 * 3600;
/// Starts of a just-applied version that never bound before it is taken
/// back out: under systemd a crash is restarted every two seconds, so three
/// is six seconds of a daemon that will not come up. See `first_start`.
const BOOT_TRIES: u32 = 2;
/// A download larger than this is not one of ours.
const DOWNLOAD_MAX: u64 = 256 << 20;
/// A manifest larger than this is not one either.
const MANIFEST_MAX: u64 = 1 << 20;

// ---------- the channel ----------

/// How this snyvi was installed, and so what an update can do to it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Channel {
    /// A tarball anywhere: the files are the reader's own, and are swapped.
    Tar,
    /// `snyvi.app`, in Applications or wherever it was dragged; the cask too.
    Mac,
    /// The folder the Inno installer or Scoop made; a zip unpacked anywhere.
    Win,
    /// `/usr/bin/snyvi` from the package: root owns it, so the reader is told.
    Deb,
    /// `~/.cargo/bin`: the reader chose to compile, and is told.
    Cargo,
    /// A tarball or a zip in a folder this user cannot write -- copied into
    /// /usr/local/bin with sudo, say: told, since a swap would only fail.
    Locked,
    /// A build under `target/`, or a daemon serving `ui/` off disk: never
    /// checked, never touched.
    Dev,
}

impl Channel {
    /// The table in the plan, as one pure function. `receipt` is what
    /// `install.sh` wrote to `<config>/install.json`, when it wrote one;
    /// `dev_env` says `SNYVI_UI_DIR` is set.
    pub fn detect(exe: &Path, receipt: Option<&str>, dev_env: bool) -> Channel {
        if dev_env || exe.components().any(|c| c.as_os_str() == "target") {
            return Channel::Dev;
        }
        if let Some(ch) = receipt.and_then(Channel::named) {
            return ch;
        }
        let s = exe.to_string_lossy().replace('\\', "/");
        if s.contains("/.cargo/bin/") {
            return Channel::Cargo;
        }
        if s.contains(".app/Contents/MacOS/") {
            return Channel::Mac;
        }
        // A Windows path, told by its shape rather than by where this runs,
        // so the table in the tests holds on every platform: a drive letter,
        // also behind the `\\?\` that canonicalising puts in front of one.
        let bare = s.strip_prefix("//?/").unwrap_or(&s).as_bytes();
        if bare.len() > 1 && bare[0].is_ascii_alphabetic() && bare[1] == b':' {
            return Channel::Win;
        }
        if ["/usr/bin/", "/usr/sbin/", "/usr/lib/", "/usr/libexec/"]
            .iter()
            .any(|p| s.starts_with(p))
        {
            return Channel::Deb;
        }
        Channel::Tar
    }

    pub fn named(name: &str) -> Option<Channel> {
        Some(match name {
            "tar" => Channel::Tar,
            "mac" => Channel::Mac,
            "win" => Channel::Win,
            "deb" => Channel::Deb,
            "cargo" => Channel::Cargo,
            "locked" => Channel::Locked,
            "dev" => Channel::Dev,
            _ => return None,
        })
    }

    pub fn name(self) -> &'static str {
        match self {
            Channel::Tar => "tar",
            Channel::Mac => "mac",
            Channel::Win => "win",
            Channel::Deb => "deb",
            Channel::Cargo => "cargo",
            Channel::Locked => "locked",
            Channel::Dev => "dev",
        }
    }

    /// Whether an update is applied here without asking, or only told of.
    pub fn silent(self) -> bool {
        matches!(self, Channel::Tar | Channel::Mac | Channel::Win)
    }

    /// The lines a told-only channel's reader runs, for About and the CLI.
    /// `app` says snyvi-app is installed beside: its package depends on
    /// `snyvi (= version)`, so both debs go through apt in one transaction,
    /// or the first one in refuses to leave the other behind.
    pub fn how(self, arch: &str, app: bool) -> Vec<String> {
        match self {
            Channel::Deb => {
                let mut debs = vec![format!("snyvi-linux-{arch}.deb")];
                if app {
                    debs.push(format!("snyvi-app-linux-{arch}.deb"));
                }
                let mut lines: Vec<String> = debs
                    .iter()
                    .map(|d| {
                        format!(
                            "curl -fsSLO https://github.com/{REPO}/releases/latest/download/{d}"
                        )
                    })
                    .collect();
                let local: Vec<String> = debs.iter().map(|d| format!("./{d}")).collect();
                lines.push(format!("sudo apt install {}", local.join(" ")));
                lines
            }
            Channel::Cargo => vec!["cargo install snyvi".into()],
            _ => vec![],
        }
    }
}

/// What the release names its downloads by.
#[derive(Clone, Copy, Debug)]
pub struct Platform {
    pub os: &'static str,
    pub arch: &'static str,
}

impl Platform {
    pub const fn here() -> Platform {
        let os = if cfg!(target_os = "linux") {
            "linux"
        } else if cfg!(target_os = "macos") {
            "macos"
        } else if cfg!(windows) {
            "windows"
        } else {
            ""
        };
        let arch = if cfg!(target_arch = "x86_64") {
            "x64"
        } else if cfg!(target_arch = "aarch64") {
            "arm64"
        } else {
            ""
        };
        Platform { os, arch }
    }

    /// The manifest's key for this channel here: `linux-x64`, `macos-arm64`,
    /// `windows-x64`, `deb-x64`.
    pub fn key(&self, channel: Channel) -> String {
        match channel {
            Channel::Deb => format!("deb-{}", self.arch),
            _ => format!("{}-{}", self.os, self.arch),
        }
    }
}

// ---------- the manifest ----------

/// `latest.json`, as `packaging/manifest.py` writes it.
#[derive(Clone, Debug, Deserialize)]
pub struct Manifest {
    pub version: String,
    // `channel` ("daily") is in the file for a slower train later; nothing
    // reads it yet, and serde passes over a field it is not asked for.
    #[serde(default)]
    pub notes: String,
    #[serde(default)]
    pub app_min: Option<String>,
    #[serde(default)]
    pub hotfix_below: Option<String>,
    /// `platform key -> role -> [name, sha256]`.
    #[serde(default)]
    pub assets: BTreeMap<String, BTreeMap<String, (String, String)>>,
}

/// One download the manifest names for this machine.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Asset {
    pub role: String,
    pub name: String,
    pub sha256: String,
}

impl Manifest {
    pub fn parse(bytes: &[u8]) -> Result<Manifest> {
        let m: Manifest = serde_json::from_slice(bytes).context("reading latest.json")?;
        semver::Version::parse(&m.version).with_context(|| {
            format!(
                "latest.json names a version that is not one: {:?}",
                m.version
            )
        })?;
        Ok(m)
    }

    pub fn version(&self) -> semver::Version {
        semver::Version::parse(&self.version).expect("checked in parse")
    }

    /// The downloads a channel takes on a platform. `with_app` says a
    /// `snyvi-app` sits beside the daemon on Linux, so the window is swapped
    /// too. A told-only channel takes nothing.
    pub fn wanted(
        &self,
        channel: Channel,
        platform: &Platform,
        with_app: bool,
    ) -> Result<Vec<Asset>> {
        let roles: Vec<&str> = match channel {
            Channel::Tar if with_app => vec!["snyvi", "app"],
            Channel::Tar => vec!["snyvi"],
            Channel::Mac => vec!["bundle"],
            Channel::Win => vec!["zip"],
            _ => return Ok(vec![]),
        };
        let key = platform.key(channel);
        let table = self
            .assets
            .get(&key)
            .ok_or_else(|| anyhow!("{} names no downloads for {key}", self.version))?;
        roles
            .into_iter()
            .map(|role| -> Result<Asset> {
                let (name, sha256) = table.get(role).ok_or_else(|| {
                    anyhow!("{} names no {role} download for {key}", self.version)
                })?;
                if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
                    bail!("{name}: the manifest's checksum is not a sha256");
                }
                Ok(Asset {
                    role: role.into(),
                    name: name.clone(),
                    sha256: sha256.to_ascii_lowercase(),
                })
            })
            .collect()
    }
}

// ---------- the network, behind a seam ----------

/// What a GET came back with.
pub enum Got {
    /// The ETag sent matched: nothing has changed since.
    NotModified,
    Body {
        bytes: Vec<u8>,
        etag: Option<String>,
    },
}

/// The network, so tests never reach GitHub.
pub trait Fetch: Send + Sync {
    /// A small file, with `If-None-Match` when an ETag is known.
    fn get(&self, url: &str, etag: Option<&str>) -> Result<Got>;
    /// A large one, streamed to `to`. Returns the bytes written.
    fn download(&self, url: &str, to: &Path) -> Result<u64>;
}

/// The real one: `ureq`, five seconds to connect, a `snyvi/<version>` user
/// agent, and nothing else in the request.
pub struct Http;

fn user_agent() -> String {
    format!("snyvi/{}", crate::version::VERSION)
}

impl Fetch for Http {
    fn get(&self, url: &str, etag: Option<&str>) -> Result<Got> {
        let mut req = ureq::get(url)
            .header("User-Agent", &user_agent())
            .config()
            .timeout_global(Some(Duration::from_secs(15)))
            .http_status_as_error(false)
            .build();
        if let Some(e) = etag {
            req = req.header("If-None-Match", e);
        }
        let mut r = req.call().with_context(|| format!("GET {url}"))?;
        match r.status().as_u16() {
            304 => Ok(Got::NotModified),
            200 => {
                let etag = r
                    .headers()
                    .get("etag")
                    .and_then(|v| v.to_str().ok())
                    .map(str::to_string);
                let bytes = r
                    .body_mut()
                    .with_config()
                    .limit(MANIFEST_MAX)
                    .read_to_vec()
                    .with_context(|| format!("reading {url}"))?;
                Ok(Got::Body { bytes, etag })
            }
            s => bail!("GET {url}: HTTP {s}"),
        }
    }

    fn download(&self, url: &str, to: &Path) -> Result<u64> {
        let mut r = ureq::get(url)
            .header("User-Agent", &user_agent())
            .config()
            .timeout_connect(Some(Duration::from_secs(5)))
            .timeout_recv_body(Some(Duration::from_secs(300)))
            .http_status_as_error(false)
            .build()
            .call()
            .with_context(|| format!("GET {url}"))?;
        if r.status().as_u16() != 200 {
            bail!("GET {url}: HTTP {}", r.status().as_u16());
        }
        let mut file =
            fs::File::create(to).with_context(|| format!("creating {}", to.display()))?;
        let mut reader = r.body_mut().with_config().limit(DOWNLOAD_MAX).reader();
        let n =
            std::io::copy(&mut reader, &mut file).with_context(|| format!("downloading {url}"))?;
        file.sync_all().ok();
        Ok(n)
    }
}

/// Where the manifest and the downloads are. GitHub's layout, or a flat
/// directory for the bench (`SNYVI_UPDATE_URL`).
#[derive(Clone, Debug)]
pub enum Source {
    GitHub,
    Flat(String),
}

impl Source {
    pub fn from_env() -> Source {
        match std::env::var("SNYVI_UPDATE_URL") {
            Ok(u) if !u.is_empty() => {
                Source::Flat(if u.ends_with('/') { u } else { format!("{u}/") })
            }
            _ => Source::GitHub,
        }
    }
    /// The newest release's manifest.
    pub fn manifest(&self) -> String {
        match self {
            Source::GitHub => {
                format!("https://github.com/{REPO}/releases/latest/download/latest.json")
            }
            Source::Flat(base) => format!("{base}latest.json"),
        }
    }
    /// One release's manifest, for `snyvi update --to`.
    pub fn manifest_for(&self, version: &str) -> String {
        match self {
            Source::GitHub => {
                format!("https://github.com/{REPO}/releases/download/v{version}/latest.json")
            }
            Source::Flat(base) => format!("{base}v{version}/latest.json"),
        }
    }
    pub fn asset(&self, version: &str, name: &str) -> String {
        match self {
            Source::GitHub => {
                format!("https://github.com/{REPO}/releases/download/v{version}/{name}")
            }
            Source::Flat(base) => format!("{base}{name}"),
        }
    }
}

// ---------- the state ----------

/// What the updater knows, in memory and mirrored to
/// `<data>/updates/state.json`. Every timestamp is wall time, in seconds,
/// because the floor has to survive a restart.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct State {
    /// When the manifest was last read, and its ETag for the next read.
    pub checked_at: Option<i64>,
    pub etag: Option<String>,
    /// A newer version the manifest named, whether or not it can be applied.
    pub available: Option<String>,
    /// The version staged and verified, ready to apply.
    pub ready: Option<String>,
    /// A version that was applied and did not come up, so is not tried again,
    /// and when: the pill says so for a day, About for as long as it is so.
    pub failed: Option<String>,
    pub failed_at: Option<i64>,
    /// A version the reader went back from (`snyvi update --back`): not
    /// staged again on its own either, and not called a failure.
    pub skipped: Option<String>,
    /// When `ready` first became so, for the pill's ageing.
    pub since: Option<i64>,
    /// When the last update was applied, by the daemon that came up on it.
    pub last_applied: Option<i64>,
    /// When the next automatic apply may happen.
    pub slot: Option<i64>,
    /// A manual check or `snyvi update` found something newer: the floor
    /// does not apply to it.
    pub asked: bool,
    /// The version being applied at a planned exit, and the sha256 of the
    /// daemon file placed, so the daemon that comes up can tell the swap held.
    pub applying: Option<String>,
    pub applying_sha: Option<String>,
    /// How many times a daemon has started while `applying` was set and
    /// not yet bound. See `first_start`.
    pub boot_tries: u32,
    /// The slot and `last_applied` from before the apply, put back when it
    /// is rolled back, so the release that fixes it is not held a day.
    pub prev_slot: Option<i64>,
    pub prev_last_applied: Option<i64>,
    /// The version the last apply landed and the sha256 of the file it
    /// placed: what `--back` remembers as the one not to stage again, and
    /// what `current` reads.
    pub applied: Option<String>,
    pub applied_sha: Option<String>,
    /// The oldest window the applied version wants; a running window older
    /// than it is relaunched once.
    pub app_min: Option<String>,
    /// From the last manifest read.
    pub latest_app_min: Option<String>,
    pub hotfix_below: Option<String>,
    pub notes: Option<String>,
    /// The last check's failure, if it failed; shown in About and by the CLI,
    /// never as a pill.
    pub error: Option<String>,
    /// "Later" on the update card: the offer of `snoozed_for` is not made
    /// again before this. Here and not in a page, so every window agrees; a
    /// newer version than the one put off is offered at once.
    pub snoozed_until: Option<i64>,
    pub snoozed_for: Option<String>,
}

/// The longest "Later" is kept: two days. A page asks for "tomorrow morning",
/// which is always less; anything more is a page's mistake.
pub const SNOOZE_MAX: i64 = 2 * 86400;

/// One file the stager unpacked and hashed, in `<version>/staged.json`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StagedFile {
    pub role: String,
    pub path: PathBuf,
    pub sha256: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Staged {
    pub version: String,
    pub app_min: Option<String>,
    pub files: Vec<StagedFile>,
}

/// `state.json`, whole or not at all: written beside, flushed, and renamed
/// over. A power cut mid-write used to leave half a file, which reads as
/// no state, and a daemon that forgot `applying` could not tell a bad
/// update from a crash.
fn write_state(dir: &Path, s: &State) -> Result<()> {
    use std::io::Write;
    fs::create_dir_all(dir)?;
    let path = dir.join("state.json");
    let tmp = dir.join("state.json.tmp");
    let mut f = fs::File::create(&tmp)?;
    f.write_all(serde_json::to_string_pretty(s)?.as_bytes())?;
    f.sync_all()?;
    drop(f);
    fs::rename(&tmp, &path)?;
    Ok(())
}

fn read_state(dir: &Path) -> State {
    fs::read_to_string(dir.join("state.json"))
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default()
}

// ---------- the updater ----------

pub struct Updater {
    pub channel: Channel,
    pub platform: Platform,
    /// The daemon's file, by the path recorded at start, and the window's
    /// beside it when there is one (Linux); the bundle on macOS is found
    /// from the daemon's path.
    exe: PathBuf,
    app: Option<PathBuf>,
    /// `<data>/updates`.
    dir: PathBuf,
    /// `<config>/updates.json`, the off switch.
    switch: PathBuf,
    source: Source,
    fetch: Box<dyn Fetch>,
    /// None only if the key compiled in cannot be read, in which case no
    /// manifest is ever taken; a daemon that cannot update still starts.
    key: Option<minisign_verify::PublicKey>,
    running: semver::Version,
    /// `current`, worked out once per start.
    current: Mutex<Option<semver::Version>>,
    state: Mutex<State>,
    /// Whether the automatic path runs at all. `SNYVI_UPDATES=off` wins over
    /// the file, for CI, packagers and the dev loop.
    auto: AtomicBool,
    env_off: bool,
    /// One of check, apply and rollback at a time: an apply must not swap in
    /// files a check is removing, nor a rollback run under either.
    op: Mutex<()>,
}

/// What a check was asked for. `fresh` reads the manifest even when the
/// ETag says nothing changed; `lift` lets what it finds past the daily
/// floor. The timer is neither, `snyvi update check` only `fresh`, and
/// Check now and `snyvi update` both.
#[derive(Clone, Copy, Debug, Default)]
pub struct Ask {
    pub fresh: bool,
    pub lift: bool,
}

impl Ask {
    pub const TIMER: Ask = Ask {
        fresh: false,
        lift: false,
    };
    #[cfg(test)]
    pub const PERSON: Ask = Ask {
        fresh: true,
        lift: true,
    };
}

impl Updater {
    /// The daemon's updater. `exe` is the path recorded at start.
    pub fn new(paths: &crate::config::Paths, exe: &Path, fetch: Box<dyn Fetch>) -> Updater {
        // The installer's receipt, when it describes the folder this binary
        // is in: a receipt left by a per-user install says nothing about a
        // package installed over it later, and a daemon that believed it
        // would try to rename /usr/bin/snyvi.
        let receipt = fs::read_to_string(paths.config_dir.join("install.json"))
            .ok()
            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
            .filter(|v| match v["bin_dir"].as_str() {
                Some(dir) => {
                    let dir = Path::new(dir);
                    let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
                    exe.parent() == Some(dir.as_path())
                }
                None => true,
            })
            .and_then(|v| v["channel"].as_str().map(str::to_string));
        let mut channel = Channel::detect(
            exe,
            receipt.as_deref(),
            std::env::var_os("SNYVI_UI_DIR").is_some(),
        );
        // A swap is two renames in the folder the file is in (the bundle's,
        // on a Mac), so that folder has to be this user's to write.
        let folder = match channel {
            Channel::Mac => bundle_of(exe).and_then(|b| b.parent().map(Path::to_path_buf)),
            _ => exe.parent().map(Path::to_path_buf),
        };
        if channel.silent() && !folder.as_deref().is_some_and(writable) {
            channel = Channel::Locked;
        }
        let app = exe
            .parent()
            .map(|d| d.join(crate::platform::exe("snyvi-app")))
            .filter(|p| p.is_file());
        let key = match std::env::var("SNYVI_UPDATE_KEY") {
            // The bench's key, and only with the bench's source: a key from
            // the environment against the real release would be a way to
            // make a daemon take anyone's manifest.
            Ok(k) if matches!(Source::from_env(), Source::Flat(_)) => {
                minisign_verify::PublicKey::from_base64(k.trim()).ok()
            }
            _ => release_key(),
        };
        let dir = paths.data_dir.join("updates");
        let switch = paths.config_dir.join("updates.json");
        let state = read_state(&dir);
        let env_off = std::env::var("SNYVI_UPDATES")
            .is_ok_and(|v| matches!(v.as_str(), "off" | "0" | "false"));
        let file_on = fs::read_to_string(&switch)
            .ok()
            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
            .and_then(|v| v["auto"].as_bool())
            .unwrap_or(true);
        Updater {
            channel,
            platform: Platform::here(),
            exe: exe.to_path_buf(),
            app,
            dir,
            switch,
            source: Source::from_env(),
            fetch,
            key,
            running: semver::Version::parse(crate::version::VERSION)
                .expect("CARGO_PKG_VERSION is semver"),
            current: Mutex::new(None),
            state: Mutex::new(state),
            auto: AtomicBool::new(file_on && !env_off),
            env_off,
            op: Mutex::new(()),
        }
    }

    /// The op lock, taken whatever a panic left in it: the lock guards no
    /// data, and a check that panicked must not read as one still running
    /// until the daemon restarts.
    fn op(&self) -> std::sync::MutexGuard<'_, ()> {
        self.op.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// A check, an apply or a rollback is under way. The restart watcher
    /// waits it out rather than blocking on it.
    pub fn busy(&self) -> bool {
        matches!(self.op.try_lock(), Err(std::sync::TryLockError::WouldBlock))
    }

    /// The version at the recorded path: the one compiled into this process,
    /// or -- when the updater placed a newer-numbered file there and it is
    /// still that file -- the one it placed. They differ only when a release
    /// is the same build under another number, which is what the bench
    /// ships; the file is hashed only then, and once per start.
    fn current(&self) -> semver::Version {
        let mut c = self.current.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(v) = &*c {
            return v.clone();
        }
        let s = self.state();
        let mut v = self.running.clone();
        if let (Some(applied), Some(sha)) = (s.applied.as_deref(), s.applied_sha.as_deref()) {
            if let Ok(a) = semver::Version::parse(applied) {
                if a > v && sha256_file(&self.exe).ok().as_deref() == Some(sha) {
                    v = a;
                }
            }
        }
        *c = Some(v.clone());
        v
    }

    fn forget_current(&self) {
        *self.current.lock().unwrap_or_else(|e| e.into_inner()) = None;
    }

    pub fn state(&self) -> State {
        self.state.lock().unwrap_or_else(|e| e.into_inner()).clone()
    }

    fn edit(&self, f: impl FnOnce(&mut State)) {
        let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner());
        f(&mut s);
        let _ = write_state(&self.dir, &s);
    }

    /// The lines a told-only install's reader runs.
    pub fn how(&self) -> Vec<String> {
        match self.channel {
            Channel::Locked => locked_how(&self.platform, &self.exe, self.app.is_some()),
            ch => ch.how(self.platform.arch, self.app.is_some()),
        }
    }

    /// A failure outside a check -- an apply or a rollback that could not
    /// swap -- kept where About and the CLI show it.
    pub fn fail(&self, what: String) {
        self.edit(|s| s.error = Some(what));
    }

    /// Whether the checker runs: the file says on, and the environment does
    /// not say off, and this is not a dev build.
    pub fn auto(&self) -> bool {
        self.auto.load(Ordering::Relaxed) && self.channel != Channel::Dev
    }

    /// `snyvi update on|off`, and the switch in About. The environment's
    /// `off` cannot be turned on from here, and says so.
    /// Put the offer off until `until` ("Later"), or bring it back (`None`):
    /// only the version on offer now, so a newer one is not put off with it.
    pub fn snooze(&self, until: Option<i64>, now: i64) -> Result<()> {
        self.edit(|s| match until {
            Some(t) => {
                s.snoozed_until = Some(t.clamp(now, now + SNOOZE_MAX));
                s.snoozed_for = s.ready.clone().or_else(|| s.available.clone());
            }
            None => {
                s.snoozed_until = None;
                s.snoozed_for = None;
            }
        });
        Ok(())
    }

    pub fn set_auto(&self, on: bool) -> Result<bool> {
        if let Some(dir) = self.switch.parent() {
            fs::create_dir_all(dir)?;
        }
        fs::write(&self.switch, format!("{{ \"auto\": {on} }}\n"))
            .with_context(|| format!("writing {}", self.switch.display()))?;
        self.auto.store(on && !self.env_off, Ordering::Relaxed);
        Ok(self.auto())
    }

    /// Whether the daily floor holds right now: not asked, no hotfix above
    /// what runs, and the slot still in the future.
    pub fn floor_holds(&self, now: i64) -> bool {
        let current = self.current();
        let s = self.state();
        !s.asked
            && !hotfix_wanted(s.hotfix_below.as_deref(), &current)
            && s.slot.is_some_and(|slot| now < slot)
    }

    /// Whether a staged version should be applied now, given who is here.
    pub fn should_apply(&self, now: i64, doors: &Doors) -> Option<Reason> {
        if self.state().ready.is_none() || !self.auto() || self.busy() || self.floor_holds(now) {
            return None;
        }
        door(doors)
    }

    /// The `update` block of health and About, and the `update` event.
    pub fn json(&self, now: i64, stale: bool) -> serde_json::Value {
        let s = self.state();
        let slot_open = !self.floor_holds(now);
        let told = !self.channel.silent() && self.channel != Channel::Dev;
        let failed_recent = s.failed.is_some() && s.failed_at.is_some_and(|t| now - t < PILL_AMBER);
        // A dev build is stale after every `cargo build`; that is not news.
        let stale = stale && self.channel != Channel::Dev;
        // What the pill draws: a version staged behind the floor is not news
        // yet; one that failed to start is, for a day.
        // "Later": the version on offer, until the time the reader said. A
        // newer one is news again at once, and a failure is never put off.
        let offered = s.ready.clone().or_else(|| s.available.clone());
        let snoozed = s.snoozed_until.is_some_and(|t| t > now)
            && s.snoozed_for.is_some()
            && s.snoozed_for == offered;
        let show = failed_recent
            || (!snoozed
                && (((s.asked || slot_open)
                    && (s.ready.is_some() || (told && s.available.is_some())))
                    || stale));
        serde_json::json!({
            "channel": self.channel.name(),
            "auto": self.auto(),
            "env_off": self.env_off,
            "checked": s.checked_at,
            "available": s.available,
            "ready": s.ready,
            "failed": s.failed,
            "failed_recent": failed_recent,
            "skipped": s.skipped,
            "since": s.since,
            "amber": s.since.is_some_and(|t| now - t > PILL_AMBER),
            "last_applied": s.last_applied,
            "slot": s.slot,
            "slot_open": slot_open,
            "asked": s.asked,
            "notes": s.notes,
            "error": s.error,
            "how": self.how(),
            "show": show,
            "snoozed_until": if snoozed { s.snoozed_until } else { None },
            "stale": stale,
            "prev": self.can_go_back(),
        })
    }

    // ----- checking -----

    /// Read the manifest, and stage what it names when it is newer. See
    /// `Ask` for what a person's check does that the timer's does not. `to`
    /// is one release's manifest, for `--to`, and may go down.
    pub fn check(&self, ask: Ask, to: Option<&str>) -> Result<Checked> {
        // A person's check waits for one under way -- the timer's, staging
        // the very release they asked about -- and then answers from what it
        // left; the timer's own check just skips its turn.
        let _one = if ask.fresh {
            self.op()
        } else {
            match self.op.try_lock() {
                Ok(g) => g,
                Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
                Err(std::sync::TryLockError::WouldBlock) => {
                    bail!("a check, an apply or a rollback is already running")
                }
            }
        };
        if self.channel == Channel::Dev {
            bail!("a development build does not update itself");
        }
        let now = crate::store::now();
        // The last failure stays until a check reads a manifest: a 304 says
        // nothing about whether what failed would work now.
        let result = self.check_inner(ask, to, now);
        match &result {
            Ok(_) => {}
            Err(e) => {
                let text = format!("{e:#}");
                self.edit(|s| {
                    s.checked_at = Some(now);
                    s.error = Some(text);
                });
            }
        }
        result
    }

    /// A newer version is known and wanted here, and nothing is staged for
    /// it: a stage failed, or an apply did and dropped what was staged. The
    /// manifest has not changed, so its ETag would answer 304 until the next
    /// release; the timer's check has to read it whole to try again.
    fn stuck(&self) -> bool {
        let s = self.state();
        let Some(v) = s.available.as_deref() else {
            return false;
        };
        self.channel.silent()
            && s.ready.as_deref() != Some(v)
            && s.failed.as_deref() != Some(v)
            && s.skipped.as_deref() != Some(v)
            && semver::Version::parse(v).is_ok_and(|v| v > self.current())
    }

    fn check_inner(&self, ask: Ask, to: Option<&str>, now: i64) -> Result<Checked> {
        let url = match to {
            Some(v) => self.source.manifest_for(v),
            None => self.source.manifest(),
        };
        let etag = if ask.fresh || to.is_some() || self.stuck() {
            None
        } else {
            self.state().etag
        };
        let (bytes, etag) = match self.fetch.get(&url, etag.as_deref())? {
            Got::NotModified => {
                self.edit(|s| s.checked_at = Some(now));
                let s = self.state();
                let current = self.current();
                let latest = s
                    .available
                    .as_deref()
                    .and_then(|v| semver::Version::parse(v).ok())
                    .unwrap_or_else(|| current.clone());
                return Ok(Checked {
                    running: current,
                    latest,
                    ready: s.ready,
                    told: !self.channel.silent(),
                });
            }
            Got::Body { bytes, etag } => (bytes, etag),
        };
        let sig = match self.fetch.get(&format!("{url}.minisig"), None)? {
            Got::Body { bytes, .. } => bytes,
            Got::NotModified => bail!("{url}.minisig: not modified, with no ETag sent"),
        };
        let key = self.key.as_ref().ok_or_else(|| {
            anyhow!(
                "the release key in this build could not be read, so no manifest can be trusted"
            )
        })?;
        verify(key, &bytes, &sig)?;
        let m = Manifest::parse(&bytes)?;
        let latest = m.version();
        let current = self.current();
        let newer = latest > current;
        let wanted = match to {
            Some(_) => latest != current,
            None => newer,
        };
        // A version that did not come up is not staged again, checked on a
        // timer or asked; `--to` names it, and that is another matter.
        let failed_before = to.is_none() && {
            let s = self.state();
            s.failed.as_deref() == Some(m.version.as_str())
                || s.skipped.as_deref() == Some(m.version.as_str())
        };
        let to_stage = wanted && self.channel.silent() && !failed_before;
        // The ETag is kept only once nothing is left to do with what it
        // names; kept before a stage that then failed, it made every later
        // check a 304 and the failure permanent. `--to` reads another
        // manifest, whose ETag is not this one's.
        let settled = to.is_none() && !to_stage;
        self.edit(|s| {
            s.checked_at = Some(now);
            s.error = None;
            if settled {
                s.etag = etag.clone();
            }
            s.notes = Some(m.notes.clone()).filter(|n| !n.is_empty());
            s.latest_app_min = m.app_min.clone();
            s.hotfix_below = m.hotfix_below.clone();
            s.available = wanted.then(|| m.version.clone());
            if ask.lift && newer && !failed_before {
                s.asked = true;
            }
            if !wanted {
                s.ready = None;
                s.since = None;
            }
            // Another version is about to be staged, and staging removes
            // what was: `ready` must not name a version whose files are gone.
            if to_stage && s.ready.as_deref() != Some(m.version.as_str()) {
                s.ready = None;
            }
            // Going below: the version gone below is not staged again by
            // the next check, a day later, undoing it.
            if to.is_some() && latest < current {
                s.skipped = Some(current.to_string());
            }
        });
        let mut ready = None;
        if to_stage {
            self.stage(&m)?;
            ready = Some(m.version.clone());
            self.edit(|s| {
                s.ready = ready.clone();
                s.since = Some(s.since.unwrap_or(now));
                if s.failed.as_deref() == Some(m.version.as_str()) {
                    s.failed = None;
                }
                if to.is_none() {
                    s.etag = etag;
                }
            });
        } else if !wanted {
            // Nothing newer: what was staged is not wanted any more (an
            // apply landed, or the release was pulled), and neither is what
            // the last apply left behind, once that has run a day.
            self.drop_staged();
            self.clean_prev(now);
        }
        Ok(Checked {
            running: current,
            latest,
            ready,
            told: !self.channel.silent(),
        })
    }

    // ----- staging -----

    /// Download every asset for this channel into `<dir>/<version>/`, verify
    /// each sha256 as it lands, unpack, and write `staged.json`. Any other
    /// staged version goes first: one at a time. Idempotent: a version
    /// already staged and intact is not fetched again.
    fn stage(&self, m: &Manifest) -> Result<()> {
        let wanted = m.wanted(self.channel, &self.platform, self.app.is_some())?;
        if wanted.is_empty() {
            bail!("nothing to stage on the {} channel", self.channel.name());
        }
        let vdir = self.dir.join(&m.version);
        if let Ok(entries) = fs::read_dir(&self.dir) {
            for e in entries.flatten() {
                if e.path().is_dir() && e.file_name() != m.version.as_str() {
                    let _ = fs::remove_dir_all(e.path());
                }
            }
        }
        if let Some(staged) = self.staged() {
            if staged.version == m.version
                && staged
                    .files
                    .iter()
                    .all(|f| sha256_file(&f.path).ok().as_deref() == Some(f.sha256.as_str()))
            {
                return Ok(());
            }
        }
        fs::create_dir_all(&vdir).with_context(|| format!("creating {}", vdir.display()))?;
        let _ = fs::remove_file(vdir.join("staged.json"));
        for a in &wanted {
            let path = vdir.join(&a.name);
            if path.is_file() && sha256_file(&path).ok().as_deref() == Some(a.sha256.as_str()) {
                continue;
            }
            let url = self.source.asset(&m.version, &a.name);
            let landed = self.fetch.download(&url, &path);
            let sum = landed.and_then(|_| sha256_file(&path));
            match sum {
                Ok(sum) if sum == a.sha256 => {}
                Ok(sum) => {
                    let _ = fs::remove_file(&path);
                    bail!(
                        "{}: sha256 {} does not match the manifest's {}",
                        a.name,
                        &sum[..12],
                        &a.sha256[..12]
                    );
                }
                Err(e) => {
                    let _ = fs::remove_file(&path);
                    return Err(e);
                }
            }
        }
        let unpacked = vdir.join("unpacked");
        let _ = fs::remove_dir_all(&unpacked);
        fs::create_dir_all(&unpacked)?;
        let mut files = Vec::new();
        for a in &wanted {
            let archive = vdir.join(&a.name);
            let into = unpacked.join(&a.role);
            fs::create_dir_all(&into)?;
            if a.name.ends_with(".zip") {
                unzip(&archive, &into)?;
            } else {
                untar(&archive, &into)?;
            }
            match a.role.as_str() {
                "snyvi" => {
                    // The tarballs are Linux's, whatever this runs on.
                    let path = find(&into, "snyvi", false)?;
                    files.push(StagedFile {
                        role: "snyvi".into(),
                        sha256: sha256_file(&path)?,
                        path,
                    });
                }
                "app" => {
                    let path = find(&into, "snyvi-app", false)?;
                    files.push(StagedFile {
                        role: "app".into(),
                        sha256: sha256_file(&path)?,
                        path,
                    });
                }
                "bundle" => {
                    let path = find(&into, "snyvi.app", true)?;
                    let bin = path.join("Contents/MacOS/snyvi");
                    files.push(StagedFile {
                        role: "bundle".into(),
                        sha256: sha256_file(&bin)?,
                        path,
                    });
                }
                "zip" => {
                    let path = find(&into, "snyvi.exe", false)?;
                    files.push(StagedFile {
                        role: "snyvi".into(),
                        sha256: sha256_file(&path)?,
                        path,
                    });
                    if let Ok(app) = find(&into, "snyvi-app.exe", false) {
                        files.push(StagedFile {
                            role: "app".into(),
                            sha256: sha256_file(&app)?,
                            path: app,
                        });
                    }
                }
                other => bail!("no such role {other}"),
            }
        }
        let staged = Staged {
            version: m.version.clone(),
            app_min: m.app_min.clone(),
            files,
        };
        fs::write(
            vdir.join("staged.json"),
            serde_json::to_string_pretty(&staged)?,
        )?;
        Ok(())
    }

    /// What is staged, if a version is and its record is whole.
    pub fn staged(&self) -> Option<Staged> {
        let version = self.state().ready?;
        let text = fs::read_to_string(self.dir.join(&version).join("staged.json")).ok()?;
        serde_json::from_str(&text).ok()
    }

    /// Forget what is staged and remove it; the next check stages afresh.
    pub fn drop_staged(&self) {
        if let Ok(entries) = fs::read_dir(&self.dir) {
            for e in entries.flatten() {
                if e.path().is_dir() {
                    let _ = fs::remove_dir_all(e.path());
                }
            }
        }
        self.edit(|s| {
            s.ready = None;
            s.since = None;
        });
    }

    // ----- applying -----

    /// The files an apply replaces here, and where the old ones go.
    fn targets(&self) -> Vec<(String, PathBuf)> {
        match self.channel {
            Channel::Mac => bundle_of(&self.exe)
                .map(|b| vec![("bundle".to_string(), b)])
                .unwrap_or_default(),
            _ => {
                let mut t = vec![("snyvi".to_string(), self.exe.clone())];
                if let Some(app) = &self.app {
                    t.push(("app".to_string(), app.clone()));
                }
                t
            }
        }
    }

    /// Swap the staged files in. The old ones become `.prev`; each file
    /// placed is hashed again before the next is touched. Called at the
    /// planned exit, before the successor is started.
    pub fn apply(&self) -> Result<String> {
        if !self.channel.silent() {
            bail!(
                "the {} channel is told, not updated in place",
                self.channel.name()
            );
        }
        let _one = self.op();
        let staged = self.staged().ok_or_else(|| anyhow!("nothing is staged"))?;
        if !staged
            .files
            .iter()
            .any(|f| f.role != "app" && self.targets().iter().any(|(r, _)| *r == f.role))
        {
            bail!("the staged files do not include the daemon");
        }
        let targets = self.targets();
        let mut daemon_sha = None;
        let mut placed: Vec<&Path> = Vec::new();
        for f in &staged.files {
            let Some((_, target)) = targets.iter().find(|(role, _)| *role == f.role) else {
                // A window in the zip when none is installed here: not ours
                // to place.
                continue;
            };
            let swapped = if f.role == "bundle" {
                swap_dir(&f.path, target, &f.sha256)
            } else {
                swap_file(&f.path, target, &f.sha256)
            };
            if let Err(e) = swapped {
                // All or nothing: a daemon of one version beside a window
                // of another is not an install anyone asked for. What was
                // placed goes back from its `.prev`.
                for t in placed.iter().rev() {
                    let _ = remove_any(t);
                    let _ = fs::rename(prev_of(t), t);
                }
                return Err(e);
            }
            placed.push(target.as_path());
            if f.role != "app" {
                daemon_sha = Some(f.sha256.clone());
            }
        }
        #[cfg(windows)]
        set_display_version(&staged.version);
        self.edit(|s| {
            s.applying = Some(staged.version.clone());
            s.applying_sha = daemon_sha;
            s.app_min = staged.app_min.clone();
            s.boot_tries = 0;
            s.prev_slot = s.slot;
            s.prev_last_applied = s.last_applied;
        });
        Ok(staged.version)
    }

    /// Whether the daemon's `.prev` is there to go back to. A window's
    /// alone is not a version to go back to.
    pub fn can_go_back(&self) -> bool {
        self.targets()
            .first()
            .is_some_and(|(_, t)| prev_of(t).exists())
    }

    /// Put `.prev` back, if there is one. What `snyvi update --back` asks
    /// for (`asked`), and what a successor that never answered gets. Either
    /// way the version left is not staged again on its own; only the second
    /// is called a failure. A rollback that put some files back and not
    /// others still records it: the version left is half gone either way.
    pub fn rollback(&self, asked: bool) -> Result<bool> {
        let _one = self.op();
        if !self.can_go_back() {
            return Ok(false);
        }
        let mut any = false;
        let mut failed = None;
        for (_, target) in self.targets() {
            let prev = prev_of(&target);
            if !prev.exists() {
                continue;
            }
            let bad = with_suffix(&target, ".bad");
            let _ = remove_any(&bad);
            let _ = fs::rename(&target, &bad);
            if let Err(e) = fs::rename(&prev, &target) {
                // The file that was there goes back, so the name is never
                // left empty.
                let _ = fs::rename(&bad, &target);
                failed = Some(anyhow!(e).context(format!("putting {} back", prev.display())));
                break;
            }
            let _ = remove_any(&bad);
            any = true;
        }
        if any {
            let now = crate::store::now();
            self.edit(|s| {
                let v = s.applying.take().or_else(|| s.applied.take());
                s.applying_sha = None;
                s.applied_sha = None;
                s.boot_tries = 0;
                if asked {
                    s.skipped = v;
                } else {
                    s.failed = v;
                    s.failed_at = Some(now);
                }
                s.ready = None;
                s.since = None;
                s.slot = s.prev_slot.take();
                s.last_applied = s.prev_last_applied.take();
            });
            self.forget_current();
        }
        match failed {
            Some(e) => Err(e),
            None => Ok(any),
        }
    }

    /// `.prev` is deleted on a successful check once the version that
    /// replaced it has run a day, not at once: Check now straight after an
    /// update must leave `--back` something to go back to, and on Windows
    /// the old window holds its file open for as long as it is up, so a
    /// file that will not go is left for the check after.
    fn clean_prev(&self, now: i64) {
        // What was set aside still running is no one's to go back to: it
        // goes as soon as it can, whatever the day.
        for (_, target) in self.targets() {
            for old in set_aside(&prev_of(&target)) {
                let _ = remove_any(&old);
            }
        }
        if self
            .state()
            .last_applied
            .is_some_and(|t| now - t < KEEP_PREV)
        {
            return;
        }
        for (_, target) in self.targets() {
            let _ = remove_any(&prev_of(&target));
        }
    }

    /// The daemon that comes up says what the last exit did, once it holds
    /// the port: one that panics in a migration or on bind has not started,
    /// and `first_start` is still counting it. `planned_apply` is the
    /// marker's word; only then can this be an update, so a crash never
    /// writes `last_applied` and a flapping daemon never moves its slot.
    /// Success is the file at the recorded path hashing to what was placed;
    /// the version alone would not tell a swap that held from one that did
    /// not when the numbers are the same, which the bench relies on.
    pub fn note_started(&self, planned_apply: bool, now: i64) -> Option<Started> {
        let s = self.state();
        if s.boot_tries > 0 && s.applying.is_none() {
            self.edit(|s| s.boot_tries = 0);
        }
        let applying = s.applying.clone()?;
        let held = planned_apply
            && (s
                .applying_sha
                .as_deref()
                .is_some_and(|sha| sha256_file(&self.exe).ok().as_deref() == Some(sha))
                || self.running.to_string() == applying);
        if held {
            let slot = now + SLOT + jitter(SLOT_JITTER);
            self.edit(|s| {
                s.applied = Some(applying.clone());
                s.applied_sha = s.applying_sha.take();
                s.applying = None;
                s.boot_tries = 0;
                s.last_applied = Some(now);
                s.slot = Some(slot);
                s.ready = None;
                s.available = None;
                s.since = None;
                s.asked = false;
                s.failed = None;
                if s.skipped.as_deref() == Some(applying.as_str()) {
                    s.skipped = None;
                }
            });
            self.drop_staged();
            self.forget_current();
            Some(Started::Applied(applying))
        } else {
            self.edit(|s| {
                s.applying = None;
                s.applying_sha = None;
                s.boot_tries = 0;
                s.failed = Some(applying.clone());
                s.failed_at = Some(now);
                s.ready = None;
                s.since = None;
            });
            self.drop_staged();
            self.forget_current();
            Some(Started::Failed(applying))
        }
    }

    /// Whether a window of this version is older than the update that was
    /// applied wants, so the daemon should relaunch it. A window that says
    /// no number -- `window=1`, from before 1.7 -- is older than any.
    /// Answered once: the wish is cleared here.
    pub fn window_is_too_old(&self, window: Option<&str>) -> bool {
        let Some(min) = self.state().app_min else {
            return false;
        };
        let Ok(min) = semver::Version::parse(&min) else {
            return false;
        };
        let old = match window.and_then(|v| semver::Version::parse(v).ok()) {
            Some(v) => v < min,
            None => true,
        };
        self.edit(|s| s.app_min = None);
        old
    }

    /// Where the window binary is, for the relaunch.
    pub fn app_path(&self) -> Option<PathBuf> {
        match self.channel {
            Channel::Mac => bundle_of(&self.exe).map(|b| b.join("Contents/MacOS/snyvi-app")),
            _ => self.app.clone(),
        }
    }
}

/// What `first_start` found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FirstStart {
    /// Nothing is being applied, or this start is within the tries.
    Go,
    /// The version being applied has started `BOOT_TRIES` times and never
    /// bound; `.prev` is back in place, and the caller starts that instead.
    RolledBack(String),
}

/// Run by `snyvi serve` before anything else -- before the config, the
/// store or the port -- so it runs even when those are what a bad release
/// breaks. A version applied and not yet bound counts its starts in
/// `state.json`; past `BOOT_TRIES` it is taken back out. Under systemd,
/// where the old process has exited 75 and nobody is watching, this is the
/// only rollback there is; by spawn, `relaunch` in the old process watches
/// as well. A binary that dies before `main` is beyond it: systemd gives up
/// after its start limit, and the reader runs `snyvi update --back`.
pub fn first_start(paths: &crate::config::Paths, exe: &Path) -> FirstStart {
    let dir = paths.data_dir.join("updates");
    let mut s = read_state(&dir);
    let Some(applying) = s.applying.clone() else {
        return FirstStart::Go;
    };
    s.boot_tries += 1;
    if s.boot_tries <= BOOT_TRIES {
        let _ = write_state(&dir, &s);
        return FirstStart::Go;
    }
    let u = Updater::new(paths, exe, Box::new(Http));
    match u.rollback(false) {
        Ok(true) => FirstStart::RolledBack(applying),
        // Some files went back and not others -- the daemon's, not the
        // window's. `rollback` has recorded it; the daemon's own file is the
        // previous one again, and that is what starts.
        Err(_) if read_state(&dir).applying.is_none() => FirstStart::RolledBack(applying),
        // Nothing to put back: this is what there is, and it goes on
        // trying, counted, rather than stopping the only daemon there is.
        _ => {
            let _ = write_state(&dir, &s);
            FirstStart::Go
        }
    }
}

/// What a check found.
#[derive(Clone, Debug)]
pub struct Checked {
    pub running: semver::Version,
    pub latest: semver::Version,
    pub ready: Option<String>,
    /// A told-only channel: nothing was staged, the reader runs a command.
    pub told: bool,
}

impl Checked {
    pub fn newer(&self) -> bool {
        self.latest > self.running
    }
}

/// What the daemon that came up learned of the last exit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Started {
    Applied(String),
    Failed(String),
}

// ---------- the policy ----------

/// Who is here, for the doors.
#[derive(Clone, Copy, Debug)]
pub struct Doors {
    pub windows: usize,
    /// Streams that are pages, not agents.
    pub pages: usize,
    /// Since a page last said it was in front.
    pub focus_age: Duration,
    /// A pane with an agent mid-turn or a program printing.
    pub busy: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
    /// No window, no page, nothing busy.
    NobodyHere,
    /// A window or a page is open, and has been in the background a while.
    InBackground,
}

impl Reason {
    pub fn say(self) -> &'static str {
        match self {
            Reason::NobodyHere => "nobody is here",
            Reason::InBackground => "the window has been in the background a while",
        }
    }
}

/// The doors an update goes through once the floor is open. A window in
/// front is not one: that is the pill, and a click. The floor itself is
/// `Updater::floor_holds`, kept apart so this stays a function of who is
/// here and nothing else.
pub fn door(d: &Doors) -> Option<Reason> {
    if d.busy {
        return None;
    }
    if d.windows == 0 && d.pages == 0 {
        return Some(Reason::NobodyHere);
    }
    if d.focus_age >= BACKGROUND {
        return Some(Reason::InBackground);
    }
    None
}

/// `hotfix_below` above what runs: the floor does not apply.
fn hotfix_wanted(below: Option<&str>, running: &semver::Version) -> bool {
    below
        .and_then(|v| semver::Version::parse(v).ok())
        .is_some_and(|v| *running < v)
}

/// Up to `max` seconds, from the OS.
fn jitter(max: i64) -> i64 {
    let mut b = [0u8; 8];
    if getrandom::fill(&mut b).is_err() {
        return 0;
    }
    (u64::from_le_bytes(b) % (max as u64 + 1)) as i64
}

/// A duration up to `max`, for the checker's timer.
pub fn jitter_d(max: Duration) -> Duration {
    Duration::from_secs(jitter(max.as_secs() as i64) as u64)
}

// ---------- verifying ----------

/// The key compiled in. Read with carriage returns taken out: a checkout on
/// Windows may write the file with CRLF line endings, and the line it is
/// read from must be the key and nothing else.
fn release_key() -> Option<minisign_verify::PublicKey> {
    minisign_verify::PublicKey::decode(&PUBLIC_KEY.replace('\r', "")).ok()
}

/// The manifest against the release key. Prehashed and legacy signatures
/// both: they are the same key either way.
pub fn verify(key: &minisign_verify::PublicKey, manifest: &[u8], signature: &[u8]) -> Result<()> {
    let sig_text = std::str::from_utf8(signature).context("latest.json.minisig is not text")?;
    let sig = minisign_verify::Signature::decode(sig_text)
        .map_err(|e| anyhow!("latest.json.minisig: {e}"))?;
    key.verify(manifest, &sig, true)
        .map_err(|e| anyhow!("latest.json is not signed by the release key ({e}); refusing it"))
}

pub fn sha256_file(path: &Path) -> Result<String> {
    use sha2::Digest;
    let mut f = fs::File::open(path).with_context(|| format!("opening {}", path.display()))?;
    let mut h = sha2::Sha256::new();
    let mut buf = vec![0u8; 1 << 16];
    loop {
        let n = f.read(&mut buf)?;
        if n == 0 {
            break;
        }
        h.update(&buf[..n]);
    }
    Ok(format!("{:x}", h.finalize()))
}

// ---------- the files ----------

fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
    let mut s = path.as_os_str().to_os_string();
    s.push(suffix);
    PathBuf::from(s)
}

fn prev_of(path: &Path) -> PathBuf {
    with_suffix(path, ".prev")
}

/// A `.prev` out of the way of the next one: removed, or -- one still
/// running, which Windows will not delete but will rename: a window started
/// before the last update -- renamed aside, for `clean_prev` to take later.
/// Left where it was, the swap after it would fail on every try.
fn clear_prev(prev: &Path) {
    if remove_any(prev).is_ok() || !prev.exists() {
        return;
    }
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let _ = fs::rename(prev, with_suffix(prev, &format!(".{nanos}.old")));
}

/// The `.prev`s `clear_prev` set aside.
fn set_aside(prev: &Path) -> Vec<PathBuf> {
    let (Some(dir), Some(name)) = (prev.parent(), prev.file_name().and_then(|n| n.to_str())) else {
        return vec![];
    };
    let Ok(entries) = fs::read_dir(dir) else {
        return vec![];
    };
    entries
        .flatten()
        .map(|e| e.path())
        .filter(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .and_then(|n| n.strip_prefix(name))
                .and_then(|rest| rest.strip_prefix('.'))
                .is_some_and(|rest| rest.ends_with(".old"))
        })
        .collect()
}

fn remove_any(path: &Path) -> std::io::Result<()> {
    match fs::symlink_metadata(path) {
        Ok(m) if m.is_dir() => fs::remove_dir_all(path),
        Ok(_) => fs::remove_file(path),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

/// Whether this process may create a file in `dir`: asked by doing it,
/// since permission bits do not know about read-only mounts or ACLs.
fn writable(dir: &Path) -> bool {
    let probe = dir.join(format!(".snyvi-write-{}", std::process::id()));
    match fs::File::create(&probe) {
        Ok(_) => {
            let _ = fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

/// The `.app` a path inside a bundle belongs to.
fn bundle_of(exe: &Path) -> Option<PathBuf> {
    exe.ancestors()
        .find(|p| p.extension().is_some_and(|e| e == "app"))
        .map(Path::to_path_buf)
}

/// What a reader runs to update an install this user cannot write, in the
/// shape each platform's download has: the Windows installer (there is no
/// Windows tarball), the whole bundle on a Mac (whose tar is bsdtar, with no
/// `--wildcards`), and on Linux the one file out of each tarball, snyvi-app's
/// too when it sits beside, so the pair never ends up a version apart.
fn locked_how(platform: &Platform, exe: &Path, app: bool) -> Vec<String> {
    let url = |name: &str| {
        format!("curl -fsSLO https://github.com/{REPO}/releases/latest/download/{name}")
    };
    let dir = exe.parent().unwrap_or(Path::new(".")).display().to_string();
    let arch = platform.arch;
    match platform.os {
        "windows" => {
            let setup = format!("snyvi-windows-{arch}-setup.exe");
            vec![
                url(&setup).replacen("curl", "curl.exe", 1),
                format!(".\\{setup}"),
            ]
        }
        "macos" => {
            let tgz = format!("snyvi-macos-{arch}.tar.gz");
            let last = match bundle_of(exe) {
                Some(bundle) => {
                    let into = bundle
                        .parent()
                        .unwrap_or(Path::new("/Applications"))
                        .display()
                        .to_string();
                    format!(
                        "sudo rm -rf '{}' && sudo mv snyvi-*/snyvi.app '{into}/'",
                        bundle.display()
                    )
                }
                None => format!("sudo cp snyvi-*/snyvi.app/Contents/MacOS/snyvi '{dir}/'"),
            };
            vec![url(&tgz), format!("tar -xzf {tgz}"), last]
        }
        os => {
            let mut lines = Vec::new();
            let mut names = vec!["snyvi"];
            if app {
                names.push("snyvi-app");
            }
            for name in names {
                let tgz = format!("{name}-{os}-{arch}.tar.gz");
                lines.push(url(&tgz));
                lines.push(format!(
                    "sudo tar -xzf {tgz} --strip-components=1 -C '{dir}' --wildcards '*/{name}'"
                ));
            }
            lines
        }
    }
}

/// Bring `staged` beside `target` (a rename on one filesystem, a copy
/// across two), check it, move the old file to `.prev`, and move the new one
/// in. The running process keeps its file: a rename moves the name, not the
/// inode, and on Windows a running executable can be renamed though never
/// overwritten. Any failure leaves the old file where it was.
fn swap_file(staged: &Path, target: &Path, sha256: &str) -> Result<()> {
    let incoming = with_suffix(target, ".new");
    let _ = remove_any(&incoming);
    if fs::rename(staged, &incoming).is_err() {
        fs::copy(staged, &incoming)
            .with_context(|| format!("copying {} beside {}", staged.display(), target.display()))?;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&incoming, fs::Permissions::from_mode(0o755))?;
    }
    if sha256_file(&incoming)? != sha256 {
        let _ = remove_any(&incoming);
        bail!("{}: not the file that was verified", incoming.display());
    }
    let prev = prev_of(target);
    clear_prev(&prev);
    // On Unix the old file is linked to `.prev` and the new one renamed over
    // it: one rename, so there is never a moment with nothing at the name
    // for a start to find. Windows will not rename over a running
    // executable, so there it is two.
    #[cfg(unix)]
    let linked = target.exists() && fs::hard_link(target, &prev).is_ok();
    #[cfg(not(unix))]
    let linked = false;
    if !linked && target.exists() {
        fs::rename(target, &prev).with_context(|| format!("moving {} aside", target.display()))?;
    }
    if let Err(e) = fs::rename(&incoming, target) {
        if linked {
            let _ = fs::remove_file(&prev);
        } else {
            let _ = fs::rename(&prev, target);
        }
        let _ = remove_any(&incoming);
        return Err(e).with_context(|| format!("moving {} in", incoming.display()));
    }
    if sha256_file(target)? != sha256 {
        let _ = remove_any(target);
        let _ = fs::rename(&prev, target);
        bail!("{}: not the file that was placed", target.display());
    }
    Ok(())
}

/// The same for a bundle: `snyvi.app` → `snyvi.app.prev`, the staged one in.
fn swap_dir(staged: &Path, target: &Path, sha256: &str) -> Result<()> {
    let incoming = with_suffix(target, ".new");
    let _ = remove_any(&incoming);
    if fs::rename(staged, &incoming).is_err() {
        copy_dir(staged, &incoming)?;
    }
    let bin = incoming.join("Contents/MacOS/snyvi");
    if sha256_file(&bin)? != sha256 {
        let _ = remove_any(&incoming);
        bail!("{}: not the bundle that was verified", incoming.display());
    }
    let prev = prev_of(target);
    clear_prev(&prev);
    if target.exists() {
        fs::rename(target, &prev).with_context(|| format!("moving {} aside", target.display()))?;
    }
    if let Err(e) = fs::rename(&incoming, target) {
        let _ = fs::rename(&prev, target);
        return Err(e).with_context(|| format!("moving {} in", incoming.display()));
    }
    Ok(())
}

fn copy_dir(from: &Path, to: &Path) -> Result<()> {
    fs::create_dir_all(to)?;
    for e in fs::read_dir(from)? {
        let e = e?;
        let dest = to.join(e.file_name());
        let m = e.metadata()?;
        if m.is_dir() {
            copy_dir(&e.path(), &dest)?;
        } else if m.file_type().is_symlink() {
            #[cfg(unix)]
            std::os::unix::fs::symlink(fs::read_link(e.path())?, &dest)?;
            #[cfg(not(unix))]
            fs::copy(e.path(), &dest)?;
        } else {
            fs::copy(e.path(), &dest)?;
        }
    }
    Ok(())
}

/// A file or directory of that name under `dir`, a few levels down: the
/// tarballs hold a versioned top directory, the zip a folder.
fn find(dir: &Path, name: &str, want_dir: bool) -> Result<PathBuf> {
    fn walk(dir: &Path, name: &str, want_dir: bool, depth: u8) -> Option<PathBuf> {
        let mut dirs = Vec::new();
        for e in fs::read_dir(dir).ok()?.flatten() {
            let p = e.path();
            let is_dir = p.is_dir();
            if e.file_name() == name && is_dir == want_dir {
                return Some(p);
            }
            if is_dir {
                dirs.push(p);
            }
        }
        if depth == 0 {
            return None;
        }
        dirs.into_iter()
            .find_map(|d| walk(&d, name, want_dir, depth - 1))
    }
    walk(dir, name, want_dir, 3).ok_or_else(|| anyhow!("no {name} in the download"))
}

fn untar(archive: &Path, into: &Path) -> Result<()> {
    let f = fs::File::open(archive).with_context(|| format!("opening {}", archive.display()))?;
    let gz = flate2::read::GzDecoder::new(std::io::BufReader::new(f));
    let mut tar = tar::Archive::new(gz);
    tar.set_preserve_permissions(true);
    tar.unpack(into)
        .with_context(|| format!("unpacking {}", archive.display()))
}

/// A zip as `Compress-Archive` writes one: stored or deflated entries, no
/// zip64, read through the central directory so a data descriptor after an
/// entry changes nothing. Small enough to be here rather than a crate that
/// would bring its own compressors along.
pub fn unzip(archive: &Path, into: &Path) -> Result<()> {
    let mut f =
        fs::File::open(archive).with_context(|| format!("opening {}", archive.display()))?;
    let len = f.metadata()?.len();
    let tail_len = len.min(66 << 10);
    f.seek(SeekFrom::Start(len - tail_len))?;
    let mut tail = vec![0u8; tail_len as usize];
    f.read_exact(&mut tail)?;
    let eocd = tail
        .windows(4)
        .rposition(|w| w == [0x50, 0x4b, 0x05, 0x06])
        .ok_or_else(|| anyhow!("{}: not a zip", archive.display()))?;
    fn u16at(b: &[u8], i: usize) -> usize {
        u16::from_le_bytes([b[i], b[i + 1]]) as usize
    }
    fn u32at(b: &[u8], i: usize) -> u64 {
        u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as u64
    }
    let entries = u16at(&tail, eocd + 10);
    let cd_size = u32at(&tail, eocd + 12);
    let cd_off = u32at(&tail, eocd + 16);
    if cd_off == 0xffff_ffff || entries == 0xffff {
        bail!("{}: zip64 is not read here", archive.display());
    }
    f.seek(SeekFrom::Start(cd_off))?;
    let mut cd = vec![0u8; cd_size as usize];
    f.read_exact(&mut cd)?;
    let mut at = 0;
    for _ in 0..entries {
        if cd.len() < at + 46 || cd[at..at + 4] != [0x50, 0x4b, 0x01, 0x02] {
            bail!(
                "{}: central directory is not as expected",
                archive.display()
            );
        }
        let method = u16at(&cd, at + 10);
        let csize = u32at(&cd, at + 20);
        let usize_ = u32at(&cd, at + 24);
        let (n, m, k) = (
            u16at(&cd, at + 28),
            u16at(&cd, at + 30),
            u16at(&cd, at + 32),
        );
        let local = u32at(&cd, at + 42);
        let name = String::from_utf8_lossy(&cd[at + 46..at + 46 + n]).replace('\\', "/");
        at += 46 + n + m + k;
        if name.split('/').any(|p| p == "..") || name.starts_with('/') {
            bail!(
                "{}: refuses a path outside the folder: {name}",
                archive.display()
            );
        }
        let dest = into.join(&name);
        if name.ends_with('/') {
            fs::create_dir_all(&dest)?;
            continue;
        }
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent)?;
        }
        f.seek(SeekFrom::Start(local))?;
        let mut lh = [0u8; 30];
        f.read_exact(&mut lh)?;
        if lh[..4] != [0x50, 0x4b, 0x03, 0x04] {
            bail!(
                "{}: entry {name} is not where the directory says",
                archive.display()
            );
        }
        let skip = u16at(&lh, 26) + u16at(&lh, 28);
        f.seek(SeekFrom::Current(skip as i64))?;
        let mut out = fs::File::create(&dest)?;
        let mut raw = (&mut f).take(csize);
        let written = match method {
            0 => std::io::copy(&mut raw, &mut out)?,
            8 => std::io::copy(&mut flate2::read::DeflateDecoder::new(raw), &mut out)?,
            other => bail!(
                "{}: entry {name} uses compression method {other}",
                archive.display()
            ),
        };
        if written != usize_ {
            bail!(
                "{}: entry {name} is {written} bytes, not {usize_}",
                archive.display()
            );
        }
    }
    Ok(())
}

/// Settings > Apps shows the number the installer wrote; after a swap it is
/// this one. Best effort, and nothing depends on it.
#[cfg(windows)]
fn set_display_version(version: &str) {
    let _ = std::process::Command::new("reg")
        .args([
            "add",
            r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\{77914D41-28F1-4AB8-AA82-692BB637B9B2}_is1",
            "/v",
            "DisplayVersion",
            "/d",
            version,
            "/f",
        ])
        .creation_flags(crate::platform::CREATE_NO_WINDOW)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
}
#[cfg(windows)]
use std::os::windows::process::CommandExt;

// ---------- tests ----------

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use std::sync::Arc;
    use std::sync::Mutex as StdMutex;

    fn p(s: &str) -> PathBuf {
        PathBuf::from(s)
    }

    #[test]
    fn the_channel_is_read_off_the_path_and_the_receipt() {
        let d = |s: &str| Channel::detect(&p(s), None, false);
        assert_eq!(d("/home/a/.local/bin/snyvi"), Channel::Tar);
        assert_eq!(d("/opt/snyvi/snyvi"), Channel::Tar);
        assert_eq!(d("/usr/local/bin/snyvi"), Channel::Tar);
        assert_eq!(d("/usr/bin/snyvi"), Channel::Deb);
        assert_eq!(d("/usr/lib/snyvi/snyvi"), Channel::Deb);
        assert_eq!(d("/home/a/.cargo/bin/snyvi"), Channel::Cargo);
        assert_eq!(
            d("/Applications/snyvi.app/Contents/MacOS/snyvi"),
            Channel::Mac
        );
        assert_eq!(
            d("/Users/a/Applications/snyvi.app/Contents/MacOS/snyvi"),
            Channel::Mac
        );
        assert_eq!(
            d(r"C:\Users\a\AppData\Local\Programs\snyvi\snyvi.exe"),
            Channel::Win
        );
        assert_eq!(
            d(r"C:\Users\a\scoop\apps\snyvi\current\snyvi.exe"),
            Channel::Win
        );
        assert_eq!(
            d(r"\\?\C:\Users\a\AppData\Local\Programs\snyvi\snyvi.exe"),
            Channel::Win,
            "canonicalised"
        );
        assert_eq!(
            d("/home/a/Projects/snyvi/target/release/snyvi"),
            Channel::Dev
        );
        assert_eq!(
            Channel::detect(&p("/home/a/.local/bin/snyvi"), None, true),
            Channel::Dev
        );
        // The receipt wins over the path, except for a dev build.
        assert_eq!(
            Channel::detect(&p("/opt/snyvi/snyvi"), Some("deb"), false),
            Channel::Deb
        );
        assert_eq!(
            Channel::detect(&p("/home/a/snyvi/target/debug/snyvi"), Some("tar"), false),
            Channel::Dev
        );
        assert_eq!(
            Channel::detect(&p("/opt/snyvi/snyvi"), Some("nonsense"), false),
            Channel::Tar
        );
        assert!(Channel::Tar.silent() && Channel::Mac.silent() && Channel::Win.silent());
        assert!(!Channel::Deb.silent() && !Channel::Cargo.silent() && !Channel::Dev.silent());
    }

    #[test]
    fn a_told_reader_is_given_lines_that_work_where_they_are() {
        // Both debs in one apt transaction when the window's is installed:
        // snyvi-app depends on `snyvi (= version)`, so dpkg -i of either
        // alone leaves the pair broken.
        let deb = Channel::Deb.how("x64", true);
        assert_eq!(deb.len(), 3);
        assert_eq!(
            deb[2],
            "sudo apt install ./snyvi-linux-x64.deb ./snyvi-app-linux-x64.deb"
        );
        assert_eq!(
            Channel::Deb.how("arm64", false).last().unwrap(),
            "sudo apt install ./snyvi-linux-arm64.deb"
        );

        let linux = Platform {
            os: "linux",
            arch: "x64",
        };
        let l = locked_how(&linux, &p("/usr/local/bin/snyvi"), true);
        assert_eq!(l.len(), 4, "{l:?}");
        assert!(l[1].contains("-C '/usr/local/bin'") && l[1].ends_with("'*/snyvi'"));
        assert!(l[2].ends_with("snyvi-app-linux-x64.tar.gz") && l[3].ends_with("'*/snyvi-app'"));

        // No --wildcards for bsdtar, and the bundle goes in whole.
        let mac = Platform {
            os: "macos",
            arch: "arm64",
        };
        let m = locked_how(
            &mac,
            &p("/Applications/snyvi.app/Contents/MacOS/snyvi"),
            false,
        );
        assert!(m.iter().all(|s| !s.contains("--wildcards")), "{m:?}");
        assert_eq!(
            m[2],
            "sudo rm -rf '/Applications/snyvi.app' && sudo mv snyvi-*/snyvi.app '/Applications/'"
        );

        // There is no Windows tarball; the installer is what there is.
        let win = Platform {
            os: "windows",
            arch: "x64",
        };
        let w = locked_how(&win, &p(r"C:\Program Files\snyvi\snyvi.exe"), true);
        assert!(w[0].starts_with("curl.exe ") && w[0].ends_with("/snyvi-windows-x64-setup.exe"));
        assert!(w.iter().all(|s| !s.contains(".tar.gz")), "{w:?}");
    }

    const MANIFEST: &str = r#"{
      "version": "1.7.0", "channel": "daily", "notes": "https://x/v1.7.0", "app_min": "1.6.0", "hotfix_below": null,
      "assets": {
        "linux-x64": { "snyvi": ["snyvi-linux-x64.tar.gz", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], "app": ["snyvi-app-linux-x64.tar.gz", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"] },
        "macos-arm64": { "bundle": ["snyvi-macos-arm64.tar.gz", "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"] },
        "windows-x64": { "zip": ["snyvi-windows-x64.zip", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"], "setup": ["snyvi-windows-x64-setup.exe", "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"] },
        "deb-x64": { "snyvi": ["snyvi-linux-x64.deb", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"] }
      }
    }"#;

    #[test]
    fn the_manifest_names_each_channels_downloads() {
        let m = Manifest::parse(MANIFEST.as_bytes()).unwrap();
        let linux = Platform {
            os: "linux",
            arch: "x64",
        };
        let names = |w: Vec<Asset>| w.into_iter().map(|a| a.name).collect::<Vec<_>>();
        assert_eq!(
            names(m.wanted(Channel::Tar, &linux, false).unwrap()),
            ["snyvi-linux-x64.tar.gz"]
        );
        assert_eq!(
            names(m.wanted(Channel::Tar, &linux, true).unwrap()),
            ["snyvi-linux-x64.tar.gz", "snyvi-app-linux-x64.tar.gz"]
        );
        assert_eq!(
            names(
                m.wanted(
                    Channel::Mac,
                    &Platform {
                        os: "macos",
                        arch: "arm64"
                    },
                    false
                )
                .unwrap()
            ),
            ["snyvi-macos-arm64.tar.gz"]
        );
        assert_eq!(
            names(
                m.wanted(
                    Channel::Win,
                    &Platform {
                        os: "windows",
                        arch: "x64"
                    },
                    true
                )
                .unwrap()
            ),
            ["snyvi-windows-x64.zip"]
        );
        // Told channels take nothing; a platform the release does not build
        // for is an error, not an empty list, so the check says so.
        assert!(m.wanted(Channel::Deb, &linux, false).unwrap().is_empty());
        assert!(m.wanted(Channel::Cargo, &linux, false).unwrap().is_empty());
        assert!(m
            .wanted(
                Channel::Tar,
                &Platform {
                    os: "linux",
                    arch: "riscv"
                },
                false
            )
            .is_err());
        assert!(m
            .wanted(
                Channel::Mac,
                &Platform {
                    os: "macos",
                    arch: "x64"
                },
                false
            )
            .is_err());
        assert!(Manifest::parse(br#"{"version": "one"}"#).is_err());
    }

    #[test]
    fn the_doors_open_for_nobody_and_for_a_window_left_behind() {
        let d = |windows, pages, mins: u64, busy| {
            door(&Doors {
                windows,
                pages,
                focus_age: Duration::from_secs(mins * 60),
                busy,
            })
        };
        assert_eq!(d(0, 0, 0, false), Some(Reason::NobodyHere));
        assert_eq!(d(0, 0, 0, true), None, "busy panes hold every door");
        assert_eq!(
            d(1, 1, 0, false),
            None,
            "a window in front is the pill, not a door"
        );
        assert_eq!(d(1, 1, 9, false), None);
        assert_eq!(d(1, 1, 10, false), Some(Reason::InBackground));
        assert_eq!(
            d(0, 1, 0, false),
            None,
            "a browser tab in front counts as someone here"
        );
        assert_eq!(d(0, 1, 30, false), Some(Reason::InBackground));
        assert_eq!(d(1, 1, 30, true), None);
    }

    #[test]
    fn a_hotfix_above_what_runs_opens_the_floor() {
        let v = semver::Version::parse("1.6.2").unwrap();
        assert!(hotfix_wanted(Some("1.6.3"), &v));
        assert!(!hotfix_wanted(Some("1.6.2"), &v));
        assert!(!hotfix_wanted(Some("1.6.0"), &v));
        assert!(!hotfix_wanted(None, &v));
        assert!(!hotfix_wanted(Some("soon"), &v));
    }

    // ----- the stager and the swap, against a fake network -----

    /// A `Fetch` over a map of URLs, counting what was asked for. A download
    /// may be cut short, to see that nothing is marked ready from it.
    struct Fake {
        files: StdMutex<BTreeMap<String, Vec<u8>>>,
        truncate: StdMutex<Option<String>>,
        asked: StdMutex<Vec<String>>,
    }

    impl Fake {
        fn new() -> Fake {
            Fake {
                files: Default::default(),
                truncate: Default::default(),
                asked: Default::default(),
            }
        }
        fn put(&self, name: &str, bytes: Vec<u8>) {
            self.files.lock().unwrap().insert(name.to_string(), bytes);
        }
    }

    impl Fetch for Fake {
        fn get(&self, url: &str, etag: Option<&str>) -> Result<Got> {
            self.asked.lock().unwrap().push(url.to_string());
            let name = url.rsplit('/').next().unwrap();
            match self.files.lock().unwrap().get(name) {
                Some(b) if etag == Some(format!("\"{}\"", b.len()).as_str()) => {
                    Ok(Got::NotModified)
                }
                Some(b) => Ok(Got::Body {
                    bytes: b.clone(),
                    etag: Some(format!("\"{}\"", b.len())),
                }),
                None => bail!("GET {url}: HTTP 404"),
            }
        }
        fn download(&self, url: &str, to: &Path) -> Result<u64> {
            self.asked.lock().unwrap().push(url.to_string());
            let name = url.rsplit('/').next().unwrap();
            let files = self.files.lock().unwrap();
            let Some(b) = files.get(name) else {
                bail!("GET {url}: HTTP 404")
            };
            let cut = self.truncate.lock().unwrap().as_deref() == Some(name);
            let bytes = if cut { &b[..b.len() / 2] } else { &b[..] };
            fs::write(to, bytes)?;
            Ok(bytes.len() as u64)
        }
    }

    /// The test key pair's public half, and a manifest it signed; see
    /// `tests/fixtures/update/README`. The release key is not used here.
    const TEST_PUB: &str = include_str!("../tests/fixtures/update/test.pub");
    const SIGNED: &[u8] = include_bytes!("../tests/fixtures/update/latest.json");
    const SIGNATURE: &[u8] = include_bytes!("../tests/fixtures/update/latest.json.minisig");
    /// What that manifest's `linux-x64` daemon download is: a tarball whose
    /// `snyvi` is a line of text.
    const TARBALL: &[u8] = include_bytes!("../tests/fixtures/update/snyvi-linux-x64.tar.gz");

    #[test]
    fn a_manifest_is_taken_from_the_key_and_from_nobody_else() {
        let key = minisign_verify::PublicKey::decode(TEST_PUB).unwrap();
        verify(&key, SIGNED, SIGNATURE).unwrap();
        let mut tampered = SIGNED.to_vec();
        let at = tampered
            .windows(5)
            .position(|w| w == b"1.9.9")
            .expect("the fixture names 1.9.9");
        tampered[at + 4] = b'8';
        assert!(
            verify(&key, &tampered, SIGNATURE).is_err(),
            "a changed byte fails"
        );
        let release = release_key().expect("the release key reads, on every platform");
        assert!(
            verify(&release, SIGNED, SIGNATURE).is_err(),
            "the release key does not vouch for the test key's manifest"
        );
        assert!(verify(&key, SIGNED, b"untrusted comment: nothing\n").is_err());
    }

    fn sha(bytes: &[u8]) -> String {
        use sha2::Digest;
        format!("{:x}", sha2::Sha256::digest(bytes))
    }

    /// A gzipped tarball holding `<top>/<name>` with the given bytes.
    fn tarball(top: &str, name: &str, bytes: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        {
            let gz = flate2::write::GzEncoder::new(&mut out, flate2::Compression::fast());
            let mut tar = tar::Builder::new(gz);
            let mut h = tar::Header::new_gnu();
            h.set_size(bytes.len() as u64);
            h.set_mode(0o755);
            h.set_cksum();
            tar.append_data(&mut h, format!("{top}/{name}"), bytes)
                .unwrap();
            tar.into_inner().unwrap().finish().unwrap();
        }
        out
    }

    /// A zip holding `<top>/<name>` stored, and `<top>/<other>` deflated.
    fn zip(top: &str, entries: &[(&str, &[u8], bool)]) -> Vec<u8> {
        let mut out = Vec::new();
        let mut cd = Vec::new();
        let crc = |b: &[u8]| {
            // CRC-32, the plain table-less way: it is a test.
            let mut c = 0xffff_ffffu32;
            for &x in b {
                c ^= x as u32;
                for _ in 0..8 {
                    c = if c & 1 != 0 {
                        (c >> 1) ^ 0xedb8_8320
                    } else {
                        c >> 1
                    };
                }
            }
            !c
        };
        for &(name, bytes, deflate) in entries {
            let name = format!("{top}/{name}");
            let data = if deflate {
                let mut e =
                    flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
                e.write_all(bytes).unwrap();
                e.finish().unwrap()
            } else {
                bytes.to_vec()
            };
            let off = out.len() as u32;
            let method: u16 = if deflate { 8 } else { 0 };
            let mut lh = Vec::new();
            lh.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04, 20, 0, 0, 0]);
            lh.extend_from_slice(&method.to_le_bytes());
            lh.extend_from_slice(&[0; 4]);
            lh.extend_from_slice(&crc(bytes).to_le_bytes());
            lh.extend_from_slice(&(data.len() as u32).to_le_bytes());
            lh.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
            lh.extend_from_slice(&(name.len() as u16).to_le_bytes());
            lh.extend_from_slice(&[0, 0]);
            lh.extend_from_slice(name.as_bytes());
            out.extend_from_slice(&lh);
            out.extend_from_slice(&data);
            cd.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02, 20, 0, 20, 0, 0, 0]);
            cd.extend_from_slice(&method.to_le_bytes());
            cd.extend_from_slice(&[0; 4]);
            cd.extend_from_slice(&crc(bytes).to_le_bytes());
            cd.extend_from_slice(&(data.len() as u32).to_le_bytes());
            cd.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
            cd.extend_from_slice(&(name.len() as u16).to_le_bytes());
            cd.extend_from_slice(&[0; 12]);
            cd.extend_from_slice(&off.to_le_bytes());
            cd.extend_from_slice(name.as_bytes());
        }
        let cd_off = out.len() as u32;
        out.extend_from_slice(&cd);
        out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0]);
        out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
        out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
        out.extend_from_slice(&(cd.len() as u32).to_le_bytes());
        out.extend_from_slice(&cd_off.to_le_bytes());
        out.extend_from_slice(&[0, 0]);
        out
    }

    /// A signed manifest is fixed by the fixture, so the stager is tested
    /// below the signature: `stage` and `apply` take the parsed manifest.
    fn paths(dir: &Path) -> crate::config::Paths {
        crate::config::Paths {
            data_dir: dir.join("data"),
            config_dir: dir.join("config"),
            docs_dir: dir.join("data/docs"),
            db_path: dir.join("data/snyvi.db"),
            token_path: dir.join("config/token"),
        }
    }

    impl Fetch for Arc<Fake> {
        fn get(&self, url: &str, etag: Option<&str>) -> Result<Got> {
            self.as_ref().get(url, etag)
        }
        fn download(&self, url: &str, to: &Path) -> Result<u64> {
            self.as_ref().download(url, to)
        }
    }

    fn updater(dir: &Path, exe: &Path, fetch: impl Fetch + 'static) -> Updater {
        let mut u = Updater::new(&paths(dir), exe, Box::new(fetch));
        u.source = Source::Flat("http://fake/".into());
        u.channel = Channel::Tar;
        u.platform = Platform {
            os: "linux",
            arch: "x64",
        };
        u
    }

    fn manifest_for(version: &str, tar_sha: &str) -> Manifest {
        Manifest::parse(
            format!(
                r#"{{ "version": "{version}", "app_min": "1.0.0", "assets": {{ "linux-x64": {{ "snyvi": ["snyvi-linux-x64.tar.gz", "{tar_sha}"] }} }} }}"#
            )
            .as_bytes(),
        )
        .unwrap()
    }

    /// "Later" puts off the version on offer until the time given, in every
    /// window, and no longer than two days; a newer version is offered at
    /// once, and a failure to start is never put off.
    #[test]
    fn later_puts_off_this_version_and_not_the_next() {
        let tmp = tempdir();
        let exe = tmp.join("snyvi");
        fs::write(&exe, b"x").unwrap();
        let u = updater(&tmp, &exe, Fake::new());
        u.edit(|s| {
            s.ready = Some("9.9.9".into());
            s.asked = true;
        });
        let now = 1_000_000;
        assert_eq!(u.json(now, false)["show"], true);
        u.snooze(Some(now + 3600), now).unwrap();
        let j = u.json(now, false);
        assert_eq!(
            (j["show"].clone(), j["snoozed_until"].clone()),
            (serde_json::json!(false), serde_json::json!(now + 3600))
        );
        assert_eq!(u.json(now + 3601, false)["show"], true, "only until then");
        u.edit(|s| s.ready = Some("9.9.10".into()));
        assert_eq!(u.json(now, false)["show"], true, "a newer version is news");
        u.snooze(Some(now + 10 * 86400), now).unwrap();
        assert_eq!(u.state().snoozed_until, Some(now + SNOOZE_MAX));
        u.snooze(None, now).unwrap();
        assert_eq!(u.json(now, false)["show"], true);
        let _ = fs::remove_dir_all(&tmp);
    }

    #[test]
    fn a_prev_set_aside_is_found_and_nothing_else() {
        let tmp = tempdir();
        let prev = prev_of(&tmp.join("snyvi-app.exe"));
        for n in [
            "snyvi-app.exe.prev",
            "snyvi-app.exe.prev.123.old",
            "snyvi-app.exe.prevx.old",
            "snyvi.exe.prev.1.old",
        ] {
            fs::write(tmp.join(n), b"x").unwrap();
        }
        assert_eq!(
            set_aside(&prev),
            vec![tmp.join("snyvi-app.exe.prev.123.old")]
        );
        clear_prev(&prev);
        assert!(!prev.exists(), "a .prev nothing holds is simply removed");
        let _ = fs::remove_dir_all(&tmp);
    }

    #[test]
    fn a_tarball_is_staged_verified_swapped_in_and_rolled_back() {
        let tmp = tempdir();
        let bin = tmp.join("bin");
        fs::create_dir_all(&bin).unwrap();
        let exe = bin.join("snyvi");
        fs::write(&exe, b"old daemon").unwrap();
        let new = b"new daemon".to_vec();
        let tgz = tarball("snyvi-9.9.9-x86_64-unknown-linux-musl", "snyvi", &new);
        let fake = Fake::new();
        fake.put("snyvi-linux-x64.tar.gz", tgz.clone());
        let u = updater(&tmp, &exe, fake);
        let m = manifest_for("9.9.9", &sha(&tgz));

        u.stage(&m).unwrap();
        u.edit(|s| s.ready = Some("9.9.9".into()));
        let staged = u.staged().expect("staged.json is written");
        assert_eq!(staged.files.len(), 1);
        assert_eq!(
            staged.files[0].sha256,
            sha(&new),
            "the unpacked binary is hashed, not the tarball"
        );
        assert!(staged.files[0]
            .path
            .starts_with(tmp.join("data/updates/9.9.9")));

        assert_eq!(u.apply().unwrap(), "9.9.9");
        assert_eq!(fs::read(&exe).unwrap(), new, "the new file is at the path");
        assert_eq!(
            fs::read(bin.join("snyvi.prev")).unwrap(),
            b"old daemon",
            "the old one is beside it"
        );
        let s = u.state();
        assert_eq!(s.applying.as_deref(), Some("9.9.9"));
        assert_eq!(s.applying_sha.as_deref(), Some(sha(&new).as_str()));
        assert!(u.can_go_back());

        // The daemon that comes up on the new file: the swap held.
        assert_eq!(
            u.note_started(true, 1_000_000),
            Some(Started::Applied("9.9.9".into()))
        );
        let s = u.state();
        assert_eq!(s.last_applied, Some(1_000_000));
        assert!(
            s.slot.unwrap() >= 1_000_000 + SLOT
                && s.slot.unwrap() <= 1_000_000 + SLOT + SLOT_JITTER
        );
        assert!(s.ready.is_none() && s.applying.is_none() && !s.asked);
        assert!(
            !tmp.join("data/updates/9.9.9").exists(),
            "the staged copy is gone"
        );
        assert!(u.floor_holds(1_000_000 + 3600), "the next day's slot holds");
        assert!(!u.floor_holds(1_000_000 + SLOT + SLOT_JITTER + 1));

        // Back, asked for: the old file returns, and the version that was
        // applied is remembered so it is not staged again on its own --
        // skipped, not failed, since nothing went wrong with it.
        assert!(u.rollback(true).unwrap());
        assert_eq!(fs::read(&exe).unwrap(), b"old daemon");
        assert!(!bin.join("snyvi.prev").exists());
        let s = u.state();
        assert_eq!(s.skipped.as_deref(), Some("9.9.9"));
        assert!(s.failed.is_none());
        assert_eq!(s.slot, None, "the slot from before the apply is back");
        assert_eq!(s.last_applied, None);
        assert!(!u.rollback(true).unwrap(), "nothing to go back to twice");
    }

    #[test]
    fn the_version_at_the_path_is_the_one_placed_while_the_file_is_that_file() {
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"placed").unwrap();
        let u = updater(&tmp, &exe, Fake::new());
        let compiled = u.running.clone();
        let higher = format!(
            "{}.{}.{}",
            compiled.major,
            compiled.minor,
            compiled.patch + 5
        );
        u.edit(|s| {
            s.applied = Some(higher.clone());
            s.applied_sha = Some(sha(b"placed"));
        });
        assert_eq!(
            u.current().to_string(),
            higher,
            "the file placed is still there"
        );
        fs::write(&exe, b"something else").unwrap();
        u.forget_current();
        assert_eq!(
            u.current(),
            compiled,
            "a file the updater did not place is only what it says it is"
        );
        // A hotfix is measured against the version at the path.
        u.edit(|s| {
            s.slot = Some(i64::MAX);
            s.hotfix_below = Some(higher.clone());
        });
        assert!(!u.floor_holds(0), "below the hotfix: the floor opens");
    }

    #[test]
    fn a_cut_download_stages_nothing_and_leaves_no_file() {
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"old daemon").unwrap();
        let tgz = tarball("top", "snyvi", b"new daemon");
        let fake = Fake::new();
        fake.put("snyvi-linux-x64.tar.gz", tgz.clone());
        *fake.truncate.lock().unwrap() = Some("snyvi-linux-x64.tar.gz".into());
        let u = updater(&tmp, &exe, fake);
        let err = u.stage(&manifest_for("9.9.9", &sha(&tgz))).unwrap_err();
        assert!(err.to_string().contains("does not match"), "{err}");
        assert!(
            !tmp.join("data/updates/9.9.9/snyvi-linux-x64.tar.gz")
                .exists(),
            "the partial file is removed"
        );
        assert!(u.staged().is_none());
        assert_eq!(fs::read(&exe).unwrap(), b"old daemon");
    }

    #[test]
    fn a_swap_whose_file_is_not_the_one_verified_leaves_the_old_one() {
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"old daemon").unwrap();
        let staged = tmp.join("staged");
        fs::write(&staged, b"something else").unwrap();
        let err = swap_file(&staged, &exe, &sha(b"new daemon")).unwrap_err();
        assert!(
            err.to_string().contains("not the file that was verified"),
            "{err}"
        );
        assert_eq!(fs::read(&exe).unwrap(), b"old daemon");
        assert!(!tmp.join("bin/snyvi.prev").exists() && !tmp.join("bin/snyvi.new").exists());
    }

    #[test]
    fn a_crash_restart_does_not_count_as_an_apply() {
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"new daemon").unwrap();
        let u = updater(&tmp, &exe, Fake::new());
        assert_eq!(u.note_started(false, 5), None, "nothing was being applied");
        u.edit(|s| {
            s.applying = Some("9.9.9".into());
            s.applying_sha = Some(sha(b"new daemon"));
        });
        // The file is right, but the exit was not planned: whatever put it
        // there, this daemon cannot say an update landed, and it says failed
        // rather than opening a slot it did not earn.
        assert_eq!(
            u.note_started(false, 5),
            Some(Started::Failed("9.9.9".into()))
        );
        assert_eq!(u.state().last_applied, None);
        assert_eq!(u.state().failed.as_deref(), Some("9.9.9"));
    }

    #[test]
    fn a_zip_is_read_through_its_directory() {
        let tmp = tempdir();
        let z = zip(
            "snyvi-1.0.0-x86_64-pc-windows-msvc",
            &[
                ("snyvi.exe", &b"daemon bytes"[..], false),
                (
                    "snyvi-app.exe",
                    &b"window bytes, deflated, longer than the rest"[..],
                    true,
                ),
                ("README.md", &b"# hi"[..], true),
            ],
        );
        let path = tmp.join("a.zip");
        fs::write(&path, &z).unwrap();
        let into = tmp.join("out");
        unzip(&path, &into).unwrap();
        assert_eq!(
            fs::read(into.join("snyvi-1.0.0-x86_64-pc-windows-msvc/snyvi.exe")).unwrap(),
            b"daemon bytes"
        );
        assert_eq!(
            fs::read(into.join("snyvi-1.0.0-x86_64-pc-windows-msvc/snyvi-app.exe")).unwrap(),
            b"window bytes, deflated, longer than the rest"
        );
        assert_eq!(
            find(&into, "snyvi.exe", false).unwrap(),
            into.join("snyvi-1.0.0-x86_64-pc-windows-msvc/snyvi.exe")
        );
        let bad = zip("..", &[("snyvi.exe", &b"x"[..], false)]);
        fs::write(&path, &bad).unwrap();
        assert!(
            unzip(&path, &into).is_err(),
            "a path that climbs out is refused"
        );
    }

    #[test]
    fn the_check_stages_a_newer_version_and_drops_a_staged_one_that_is_not_newer() {
        // The fixture manifest says 1.9.9 and names linux-x64 assets whose
        // hashes are of the bytes below, so a whole check runs against the
        // fake: signature, parse, compare, stage.
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"old daemon").unwrap();
        let fake = Fake::new();
        fake.put("latest.json", SIGNED.to_vec());
        fake.put("latest.json.minisig", SIGNATURE.to_vec());
        fake.put("snyvi-linux-x64.tar.gz", TARBALL.to_vec());
        let mut u = updater(&tmp, &exe, fake);
        u.key = Some(minisign_verify::PublicKey::decode(TEST_PUB).unwrap());
        // On 1.0.0 whatever this build's own version is, so a bump past the
        // fixture's 1.9.9 does not turn the check into "nothing newer".
        u.running = semver::Version::parse("1.0.0").unwrap();
        u.forget_current();
        let c = u.check(Ask::TIMER, None).unwrap();
        assert!(c.newer());
        assert_eq!(c.ready.as_deref(), Some("1.9.9"));
        let s = u.state();
        assert_eq!(s.available.as_deref(), Some("1.9.9"));
        assert_eq!(s.ready.as_deref(), Some("1.9.9"));
        assert!(s.since.is_some() && !s.asked && s.error.is_none());
        assert_eq!(s.latest_app_min.as_deref(), Some("1.6.0"));
        // Asked, with nothing newer: what was staged goes, and the floor
        // stays -- lifting it for a release not out yet let that release
        // past the day's slot whenever it came.
        u.running = semver::Version::parse("1.9.9").unwrap();
        u.forget_current();
        let c = u.check(Ask::PERSON, None).unwrap();
        assert!(!c.newer() && c.ready.is_none());
        let s = u.state();
        assert!(!s.asked && s.ready.is_none() && s.available.is_none());
        assert!(!tmp.join("data/updates/1.9.9").exists());
        // A dev build never checks.
        u.channel = Channel::Dev;
        assert!(u.check(Ask::PERSON, None).is_err());
    }

    /// A daemon on 1.0.0 whose manifest names 1.9.9, signed by the test
    /// key, and the fake it reads, to change under it.
    fn checker(tmp: &Path) -> (Updater, Arc<Fake>) {
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"old daemon").unwrap();
        let fake = Arc::new(Fake::new());
        fake.put("latest.json", SIGNED.to_vec());
        fake.put("latest.json.minisig", SIGNATURE.to_vec());
        let mut u = updater(tmp, &exe, fake.clone());
        u.key = Some(minisign_verify::PublicKey::decode(TEST_PUB).unwrap());
        u.running = semver::Version::parse("1.0.0").unwrap();
        u.forget_current();
        (u, fake)
    }

    #[test]
    fn a_stage_that_failed_is_tried_again_by_the_next_timer_check() {
        let tmp = tempdir();
        let (u, fake) = checker(&tmp);
        // The download is not there yet: the check fails, and keeps no ETag
        // for a manifest it has not finished with.
        assert!(u.check(Ask::TIMER, None).is_err());
        let s = u.state();
        assert_eq!(s.available.as_deref(), Some("1.9.9"));
        assert!(s.ready.is_none() && s.etag.is_none() && s.error.is_some());
        // The next timer check reads the manifest whole and stages.
        fake.put("snyvi-linux-x64.tar.gz", TARBALL.to_vec());
        let c = u.check(Ask::TIMER, None).unwrap();
        assert_eq!(c.ready.as_deref(), Some("1.9.9"));
        let s = u.state();
        assert!(s.etag.is_some() && s.error.is_none());
        // An apply that failed dropped what was staged; the ETag would say
        // 304 until the next release, so it is not sent.
        u.drop_staged();
        let c = u.check(Ask::TIMER, None).unwrap();
        assert_eq!(c.ready.as_deref(), Some("1.9.9"));
        // Staged: the ETag is sent, the answer is 304, and an error from
        // elsewhere is left for About to show.
        u.fail("could not apply: no room".into());
        fake.asked.lock().unwrap().clear();
        let c = u.check(Ask::TIMER, None).unwrap();
        assert_eq!(c.ready.as_deref(), Some("1.9.9"));
        assert_eq!(
            *fake.asked.lock().unwrap(),
            vec!["http://fake/latest.json".to_string()],
            "a 304, and nothing else fetched"
        );
        assert_eq!(u.state().error.as_deref(), Some("could not apply: no room"));
    }

    #[test]
    fn only_a_person_who_found_something_newer_lifts_the_floor() {
        let tmp = tempdir();
        let (u, fake) = checker(&tmp);
        fake.put("snyvi-linux-x64.tar.gz", TARBALL.to_vec());
        u.check(Ask::TIMER, None).unwrap();
        assert!(!u.state().asked, "the timer never lifts it");
        u.check(
            Ask {
                fresh: true,
                lift: false,
            },
            None,
        )
        .unwrap();
        assert!(!u.state().asked, "nor does `snyvi update check`");
        u.check(Ask::PERSON, None).unwrap();
        assert!(u.state().asked, "Check now, with 1.9.9 out, does");
    }

    #[test]
    fn going_below_skips_the_version_gone_below() {
        let tmp = tempdir();
        let (mut u, fake) = checker(&tmp);
        fake.put("snyvi-linux-x64.tar.gz", TARBALL.to_vec());
        u.running = semver::Version::parse("2.0.0").unwrap();
        u.forget_current();
        let c = u.check(Ask::PERSON, Some("1.9.9")).unwrap();
        assert_eq!(c.ready.as_deref(), Some("1.9.9"));
        let s = u.state();
        assert_eq!(s.skipped.as_deref(), Some("2.0.0"));
        assert!(s.etag.is_none(), "another release's manifest, not latest's");
    }

    #[test]
    fn an_apply_that_cannot_place_every_file_places_none() {
        let tmp = tempdir();
        let bin = tmp.join("bin");
        fs::create_dir_all(&bin).unwrap();
        let exe = bin.join("snyvi");
        fs::write(&exe, b"old daemon").unwrap();
        // Named as the updater looks for it beside the daemon: .exe on Windows.
        let app = bin.join(crate::platform::exe("snyvi-app"));
        fs::write(&app, b"old window").unwrap();
        let u = updater(&tmp, &exe, Fake::new());
        let vdir = tmp.join("data/updates/9.9.9");
        fs::create_dir_all(&vdir).unwrap();
        fs::write(vdir.join("snyvi"), b"new daemon").unwrap();
        fs::write(vdir.join("snyvi-app"), b"new window").unwrap();
        let staged = Staged {
            version: "9.9.9".into(),
            app_min: None,
            files: vec![
                StagedFile {
                    role: "snyvi".into(),
                    path: vdir.join("snyvi"),
                    sha256: sha(b"new daemon"),
                },
                // Not what is on disk: the second swap refuses it.
                StagedFile {
                    role: "app".into(),
                    path: vdir.join("snyvi-app"),
                    sha256: sha(b"another window"),
                },
            ],
        };
        fs::write(
            vdir.join("staged.json"),
            serde_json::to_string(&staged).unwrap(),
        )
        .unwrap();
        u.edit(|s| s.ready = Some("9.9.9".into()));
        assert!(u.apply().is_err());
        assert_eq!(
            fs::read(&exe).unwrap(),
            b"old daemon",
            "the daemon went back"
        );
        assert_eq!(fs::read(&app).unwrap(), b"old window");
        assert!(!bin.join("snyvi.prev").exists() && !prev_of(&app).exists());
        assert!(u.state().applying.is_none());
    }

    #[test]
    fn a_successor_that_never_binds_is_taken_back_out_on_its_third_start() {
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"new daemon").unwrap();
        fs::write(tmp.join("bin/snyvi.prev"), b"old daemon").unwrap();
        let p = paths(&tmp);
        let dir = p.data_dir.join("updates");
        let u = updater(&tmp, &exe, Fake::new());
        u.edit(|s| {
            s.applying = Some("9.9.9".into());
            s.applying_sha = Some(sha(b"new daemon"));
            s.slot = Some(7);
            s.prev_slot = Some(3);
        });
        assert_eq!(first_start(&p, &exe), FirstStart::Go);
        assert_eq!(first_start(&p, &exe), FirstStart::Go);
        assert_eq!(read_state(&dir).boot_tries, 2);
        assert_eq!(
            first_start(&p, &exe),
            FirstStart::RolledBack("9.9.9".into())
        );
        assert_eq!(fs::read(&exe).unwrap(), b"old daemon");
        let s = read_state(&dir);
        assert_eq!(s.failed.as_deref(), Some("9.9.9"));
        assert!(s.applying.is_none() && s.boot_tries == 0);
        assert_eq!(s.slot, Some(3), "the slot from before the apply is back");
        // Nothing being applied: a start is only a start.
        assert_eq!(first_start(&p, &exe), FirstStart::Go);
        assert_eq!(read_state(&dir).boot_tries, 0);
    }

    #[test]
    fn a_successor_that_binds_stops_being_counted() {
        let tmp = tempdir();
        let exe = tmp.join("bin/snyvi");
        fs::create_dir_all(exe.parent().unwrap()).unwrap();
        fs::write(&exe, b"new daemon").unwrap();
        let p = paths(&tmp);
        updater(&tmp, &exe, Fake::new()).edit(|s| {
            s.applying = Some("9.9.9".into());
            s.applying_sha = Some(sha(b"new daemon"));
        });
        assert_eq!(first_start(&p, &exe), FirstStart::Go);
        // Bound: the daemon reads the state the guard wrote.
        let u = updater(&tmp, &exe, Fake::new());
        assert_eq!(
            u.note_started(true, 1_000),
            Some(Started::Applied("9.9.9".into()))
        );
        assert_eq!(read_state(&p.data_dir.join("updates")).boot_tries, 0);
    }

    fn tempdir() -> PathBuf {
        let d = std::env::temp_dir().join(format!(
            "snyvi-update-{}-{}",
            std::process::id(),
            jitter(1 << 30)
        ));
        fs::create_dir_all(&d).unwrap();
        d
    }
}