openlatch-client 0.6.1

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
//! `openlatch update` — check for a new release and install it.
//!
//! | Invocation | Terminal | No terminal (MDM, CI, a pipe) |
//! | ---------- | -------- | ----------------------------- |
//! | `openlatch update` | check, then ask *Update now* / *Not now* | check, report the release, hint `--yes` |
//! | `openlatch update --yes` | check, then install without asking | the same, as `[n/N]` lines |
//! | `openlatch update --check` | check only | check only |
//!
//! `--apply` is a hidden alias of `--yes`, kept so existing scripts keep working.
//!
//! On a terminal (and in a log) the run is drawn on the rail (`src/cli/ui`), the
//! grammar `init` uses: Check → Download → Verify → Install → Restart → Confirm,
//! then a result card, or a `result=` line with no terminal. Nothing goes to
//! stdout. `--json` and `--quiet` bypass the rail: `--json` prints the JSON
//! documents this command always printed, `--quiet` prints nothing, and both
//! keep those documents' exit codes.
//!
//! With a daemon running, the daemon applies the update (`POST /admin/update`)
//! and the CLI polls `/admin/update/status` for the live stage and byte counts,
//! then `/health` until the new version answers. With none, the CLI applies in
//! process and reads the same live progress.
//!
//! Exit codes (rail):
//!
//! | Code | Meaning |
//! | ---- | ------- |
//! | 0 | Up to date, or updated and the new version is running |
//! | 7 | Declined, available but not applied, couldn't check, updated with no background service running, or a service still on the old version |
//! | 1 | Failed (`OL-1504` and the other stage failures), rolled back, or never came back (`OL-1502`) |
//! | 5 | Refused: a `cargo install` binary (`OL-1505`) |
//! | 6 | The daemon is up but its admin endpoint could not be used (`OL-1506`) |
//!
//! JSON mode keeps its own: a check always exits 0; an apply exits 0, 1, 5 or 6.

use std::sync::Arc;
use std::time::{Duration, Instant};

use clap::Args;
use serde_json::json;

use crate::cli::output::OutputConfig;
use crate::cli::ui::{self, Caps, Mode};
use crate::config;
use crate::error::OlError;
use crate::install_state;
use crate::update::{self, ApplyStage, CheckResult, Severity};

/// Arguments for `openlatch update`.
#[derive(Args, Clone, Debug, Default)]
pub struct UpdateArgs {
    /// Only check for a new release. Nothing is installed.
    #[arg(long)]
    pub check: bool,

    /// Install an available update without asking.
    #[arg(long, short = 'y')]
    pub yes: bool,

    /// Hidden alias of `--yes`, kept so existing `update --apply` scripts keep
    /// working.
    #[arg(long, hide = true)]
    pub apply: bool,

    /// Force the cargo-install gate to be bypassed. Maintainer escape
    /// hatch — `cargo install`-managed binaries get rewritten by
    /// self-replace, which voids `cargo install --version` tracking.
    /// Most users should run `cargo install --force --locked
    /// openlatch-client` instead.
    #[arg(long = "force-cargo")]
    pub force_cargo: bool,
}

impl UpdateArgs {
    /// Install without asking: `--apply` (as it always did), or `--yes`
    /// unless `--check` asked for a check only.
    fn applies(&self) -> bool {
        self.apply || (self.yes && !self.check)
    }
}

/// Everything a run reads from config once.
struct Ctx {
    current: String,
    registry: String,
    port: u16,
    egress: crate::egress::EgressConfig,
    auto: AutoUpdate,
}

impl Ctx {
    fn load() -> Self {
        // `Config::load` already merges the `OPENLATCH_NPM_REGISTRY` override
        // into `update.registry_origin`.
        let cfg = config::Config::load(None, None, false).ok();
        Self {
            current: env!("CARGO_PKG_VERSION").to_string(),
            registry: cfg
                .as_ref()
                .map(|c| c.update.registry_origin.clone())
                .unwrap_or_else(|| "https://registry.npmjs.org".to_string()),
            port: cfg.as_ref().map(|c| c.port).unwrap_or(7443),
            egress: cfg
                .as_ref()
                .map(|c| c.egress.clone())
                .unwrap_or_else(crate::egress::EgressConfig::direct),
            auto: AutoUpdate {
                on: cfg.as_ref().is_none_or(|c| c.update.auto_update),
                by_env: std::env::var_os("OPENLATCH_AUTO_UPDATE").is_some(),
                last_check: install_state::InstallState::load_or_default().last_check_at,
            },
        }
    }
}

/// Run `openlatch update`; returns the exit code.
pub fn run(args: &UpdateArgs, output: &OutputConfig) -> i32 {
    // Local current-thread tokio runtime: the CLI dispatcher is sync,
    // so spinning up a small runtime here is the cheapest way to call
    // the async `core::update` primitives without bleeding tokio into
    // every command.
    let runtime = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(rt) => rt,
        Err(e) => {
            output.print_info(&format!("failed to build local tokio runtime: {e}"));
            return 1;
        }
    };
    runtime.block_on(async {
        let ctx = Ctx::load();
        match Caps::detect(output) {
            Some(caps) => run_rail(args, output, &ctx, caps).await,
            None => run_json(args, output, &ctx).await,
        }
    })
}

// ---------------------------------------------------------------------------
// The rail
// ---------------------------------------------------------------------------

/// How often the daemon's status is polled, and `/health` after the restart.
const POLL: Duration = Duration::from_millis(250);
/// How often the in-process apply's progress is read.
const TICK: Duration = Duration::from_millis(100);
/// How long the new daemon has to answer after the restart.
const BACK_WITHIN: Duration = Duration::from_secs(60);
/// How long the daemon may report the same stage and byte count before the
/// run gives up on it.
const STALL: Duration = Duration::from_secs(120);
/// The drain the daemon runs before it restarts (see `run_apply_in_daemon`).
const DRAIN: Duration = Duration::from_secs(5);
/// Stages of a Live or Append rail that applies through a daemon (the
/// question adds one); only Plain shows the numbers, the transcript logs them.
const STAGES: usize = 6;

/// The release the check found.
#[derive(Debug, Clone)]
struct Release {
    from: String,
    to: String,
    severity: Severity,
    /// Tarball size the CDN advertised, when it did.
    size: Option<u64>,
}

async fn run_rail(args: &UpdateArgs, output: &OutputConfig, ctx: &Ctx, caps: Caps) -> i32 {
    let applies = args.applies();
    // Never hit the network for a binary this command cannot update. Still a
    // rail, so a log gets its `result=` line.
    if applies && refuses_cargo(args) {
        let _guard = ui::install(output, "update", 1);
        ui::intro("Updating OpenLatch");
        return stop(&Stop::new(cargo_refusal(CARGO_SUGGESTION), 5));
    }
    let plain = caps.mode == Mode::Plain;
    let asks = !applies && !args.check && !plain && crate::cli::prompt::interactive(output, false);

    // Plain writes nothing while a stage runs, so it checks before the rail
    // opens and numbers exactly the stages this run will have.
    let mut guard = if plain {
        None
    } else {
        open(output, STAGES + usize::from(asks))
    };
    let check = update::check(&ctx.current, &ctx.registry, &ctx.egress).await;
    let available = matches!(check, CheckResult::Available { .. });
    let daemon = if available && (applies || asks) {
        probe_daemon(ctx.port).await
    } else {
        DaemonState::NotRunning
    };
    if guard.is_none() {
        let total = match (available && applies, &daemon) {
            (false, _) => 1,
            (true, DaemonState::RunningAndReachable { .. }) => 6,
            (true, _) => 4,
        };
        guard = open(output, total);
    }
    let _guard = guard;
    let now = chrono::Utc::now();

    let release = match close_check(check, &ctx.current, &ctx.registry) {
        Ok(release) => release,
        Err(Outcome::UpToDate { version, .. }) => {
            let outcome = up_to_date(version, IDENTITY, ctx.port).await;
            return finish(&outcome, &ctx.auto, now);
        }
        Err(outcome) => return finish(&outcome, &ctx.auto, now),
    };
    if !applies && !asks {
        let outcome = Outcome::Available {
            release,
            check_only: args.check,
        };
        return finish(&outcome, &ctx.auto, now);
    }
    if !applies {
        if refuses_cargo(args) {
            return stop(&Stop::new(cargo_refusal(CARGO_SUGGESTION), 5));
        }
        let restarts = matches!(daemon, DaemonState::RunningAndReachable { .. });
        if !ask(&release, restarts) {
            return finish(&Outcome::Declined { release }, &ctx.auto, now);
        }
    }

    let applied = match daemon {
        DaemonState::RunningAndReachable { port, token } => {
            via_daemon(release, port, &token, args.force_cargo, Timing::REAL).await
        }
        DaemonState::NotRunning => in_process(release, ctx, args.force_cargo).await,
        DaemonState::RunningButUnauthenticated => Err(Stop::new(unauthenticated(), 6)),
    };
    match applied {
        Ok(outcome) => finish(&outcome, &ctx.auto, chrono::Utc::now()),
        Err(s) => stop(&s),
    }
}

/// This binary is the latest; the background service may not be. One still
/// serving an older version is not up to date where it counts.
///
/// `version` is the manifest version the registry was compared against;
/// the daemon is compared against `identity`, the version this binary would
/// itself report on `/health` ([`IDENTITY`]).
async fn up_to_date(version: String, identity: &str, port: u16) -> Outcome {
    let stale = daemon_version(port)
        .await
        .filter(|running| !is_version(running, identity));
    Outcome::UpToDate { version, stale }
}

/// Open the rail of `total` stages and its Check stage.
fn open(output: &OutputConfig, total: usize) -> Option<ui::RailGuard> {
    let guard = ui::install(output, "update", total);
    begin();
    guard
}

/// `┌  Updating OpenLatch`, and the Check stage running.
fn begin() {
    ui::intro("Updating OpenLatch");
    ui::stage_named("Check", "Checking for updates", "Checked for updates");
}

fn plain() -> bool {
    ui::caps().is_some_and(|c| c.mode == Mode::Plain)
}

/// Plain mode: a line written as is, never wrapped — `outro` is plain mode's
/// writer at the margin.
fn margin(text: &str) {
    ui::outro(text);
}

/// Close the Check stage: the release to install, or how the run ends.
fn close_check(check: CheckResult, current: &str, registry: &str) -> Result<Release, Outcome> {
    match check {
        CheckResult::UpToDate { current } => {
            ui::done(&format!("already on the latest ({current})"));
            Err(Outcome::UpToDate {
                version: current,
                stale: None,
            })
        }
        CheckResult::Failed { reason } => {
            let unreachable = reason.contains("send:") || reason.starts_with("http client");
            ui::failed(if unreachable {
                "couldn't reach the update server"
            } else {
                "the update server had no usable release"
            });
            ui::detail(&format!("Registry {registry}: {reason}"));
            Err(Outcome::CheckFailed {
                from: current.to_string(),
                host: host(registry),
                unreachable,
            })
        }
        CheckResult::Available {
            current,
            latest,
            severity,
            size,
            ..
        } => {
            let result = format!("{current} → {latest}");
            match severity {
                Severity::Critical => {
                    ui::done_toned(&format!("{result} · security fix"), ui::Tone::Fail)
                }
                Severity::Normal => ui::done(&result),
            }
            ui::detail(&format!(
                "Registry {registry} · latest {latest} · severity {}",
                severity.as_str()
            ));
            Ok(Release {
                from: current,
                to: latest,
                severity,
                size,
            })
        }
    }
}

/// `registry.npmjs.org` from `https://registry.npmjs.org/`.
fn host(origin: &str) -> String {
    let rest = origin.split_once("://").map_or(origin, |(_, rest)| rest);
    rest.split('/').next().unwrap_or(rest).to_string()
}

/// The question, as the rail draws it: title, question and the dim line.
fn question(release: &Release, restarts: bool) -> (String, String, Option<String>) {
    let title = format!("Update to {}", release.to);
    let question = match release.severity {
        Severity::Critical => format!("{} fixes a security issue. Update now?", release.to),
        Severity::Normal => format!("Update to {} now?", release.to),
    };
    let size = release.size.map(|s| format!("About {} MB", mb(s)));
    let line = match (size, restarts) {
        (Some(size), true) => Some(format!(
            "{size} · the background service restarts for a few seconds."
        )),
        (Some(size), false) => Some(format!("{size}.")),
        (None, true) => Some("The background service restarts for a few seconds.".to_string()),
        (None, false) => None,
    };
    (title, question, line)
}

/// Ask whether to install `release` now. Anything but a yes is a no.
fn ask(release: &Release, restarts: bool) -> bool {
    let (title, question, line) = question(release, restarts);
    ui::stage_named("Update", &title, &title);
    let lines: Vec<&str> = line.as_deref().into_iter().collect();
    let select = ui::Select {
        title: &title,
        question: &question,
        lines: &lines,
        yes: "Update now",
        no: "Not now",
        default_yes: true,
        timeout: None,
    };
    let yes = matches!(ui::select(&select), Some(ui::SelectOutcome::Answered(true)));
    answered(yes);
    yes
}

/// Close the question's stage: `◇  Update to 0.5.8 · yes`.
fn answered(yes: bool) {
    ui::done(if yes { "yes" } else { "not now" });
}

/// A stage of the apply, as the rail names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Step {
    Download,
    Verify,
    Install,
    Restart,
    Confirm,
}

impl Step {
    /// The rail stage a pipeline stage runs under.
    fn of(stage: ApplyStage) -> Self {
        match stage {
            ApplyStage::Check | ApplyStage::Download => Self::Download,
            ApplyStage::Extract | ApplyStage::Verify | ApplyStage::Sanity | ApplyStage::Reader => {
                Self::Verify
            }
            ApplyStage::Swap => Self::Install,
            ApplyStage::Drain | ApplyStage::Restart => Self::Restart,
            ApplyStage::Healthz => Self::Confirm,
        }
    }

    fn next(self) -> Option<Self> {
        match self {
            Self::Download => Some(Self::Verify),
            Self::Verify => Some(Self::Install),
            Self::Install => Some(Self::Restart),
            Self::Restart => Some(Self::Confirm),
            Self::Confirm => None,
        }
    }

    /// What the stage is, for its failure line: `Verify failed`.
    fn name(self) -> &'static str {
        match self {
            Self::Download => "Download",
            Self::Verify => "Verify",
            Self::Install => "Install",
            Self::Restart => "Restart",
            Self::Confirm => "Confirm",
        }
    }

    /// The `step=` a failure's `result=` line names.
    fn key(self) -> &'static str {
        match self {
            Self::Download => "download",
            Self::Verify => "verify",
            Self::Install => "install",
            Self::Restart => "restart",
            Self::Confirm => "confirm",
        }
    }

    fn done(self) -> &'static str {
        match self {
            Self::Download => "Downloaded",
            Self::Verify => "Verified",
            Self::Install => "Installed",
            Self::Restart => "Restarted the background service",
            Self::Confirm => "Confirmed",
        }
    }
}

/// A pipeline stage from its wire name in `/admin/update/status`.
fn apply_stage(wire: &str) -> Option<ApplyStage> {
    use ApplyStage::*;
    [
        Check, Download, Extract, Verify, Sanity, Reader, Swap, Drain, Restart, Healthz,
    ]
    .into_iter()
    .find(|s| s.as_str() == wire)
}

/// Download speed from successive byte samples, smoothed.
#[derive(Debug, Default)]
struct Rate {
    last: Option<(Instant, u64)>,
    bytes_per_sec: Option<f64>,
}

impl Rate {
    fn sample(&mut self, now: Instant, bytes: u64) {
        let Some((at, before)) = self.last else {
            self.last = Some((now, bytes));
            return;
        };
        let dt = now.saturating_duration_since(at).as_secs_f64();
        if dt < 0.2 || bytes < before {
            return;
        }
        let instant = (bytes - before) as f64 / dt;
        self.bytes_per_sec = Some(match self.bytes_per_sec {
            Some(r) => 0.7 * r + 0.3 * instant,
            None => instant,
        });
        self.last = Some((now, bytes));
    }
}

/// The meter's fraction and tail: `5.2 / 8.4 MB · 2.8 MB/s · 1s left`.
fn download_tail(
    done: u64,
    total: Option<u64>,
    bytes_per_sec: Option<f64>,
) -> (Option<f64>, String) {
    let total = total.filter(|t| *t > 0);
    let mut parts = vec![match total {
        Some(t) => format!("{} / {} MB", mb(done), mb(t)),
        None => format!("{} MB", mb(done)),
    }];
    let rate = bytes_per_sec.filter(|r| *r > 0.0);
    if let Some(r) = rate {
        parts.push(format!("{:.1} MB/s", r / MIB));
    }
    if let (Some(t), Some(r)) = (total, rate) {
        let left = (t.saturating_sub(done) as f64 / r).ceil() as u64;
        parts.push(if left < 60 {
            format!("{left}s left")
        } else {
            format!("{}m left", left.div_ceil(60))
        });
    }
    (total.map(|t| done as f64 / t as f64), parts.join(" · "))
}

const MIB: f64 = 1_048_576.0;

/// Bytes as MB with one decimal: `8.4`.
fn mb(bytes: u64) -> String {
    format!("{:.1}", bytes as f64 / MIB)
}

/// A duration with one decimal: `2.9s`.
fn secs(d: Duration) -> String {
    format!("{:.1}s", d.as_secs_f64())
}

/// The numbered stages of one apply on the rail: opened in order, each closed
/// with its result, the running one metered.
struct Apply {
    release: Release,
    step: Option<Step>,
    /// When the running stage opened.
    since: Instant,
    /// Bytes the download advertised, once it has.
    total: Option<u64>,
    rate: Rate,
    /// When the daemon was first seen draining.
    drain_at: Option<Instant>,
    /// When the restart began: the swap, drain or restart first reported, or
    /// the daemon going down, whichever came first. The Restart stage is
    /// timed from here even when the rail only reaches it later.
    restart_at: Option<Instant>,
}

impl Apply {
    fn new(release: Release, now: Instant) -> Self {
        Self {
            release,
            step: None,
            since: now,
            total: None,
            rate: Rate::default(),
            drain_at: None,
            restart_at: None,
        }
    }

    /// The restart has begun, at `at` if it had not already.
    fn restarting(&mut self, at: Instant) {
        self.restart_at.get_or_insert(at);
    }

    /// Move the rail on to `step`, closing every stage before it with its
    /// result. Never moves back.
    fn reach(&mut self, step: Step, now: Instant) {
        loop {
            let next = match self.step {
                Some(s) if s >= step => return,
                Some(s) => {
                    self.close(now);
                    match s.next() {
                        Some(n) => n,
                        None => return,
                    }
                }
                None => Step::Download,
            };
            self.open(next, now);
        }
    }

    fn open(&mut self, step: Step, now: Instant) {
        let running = match step {
            // Plain has no bar, so its heading carries the size.
            Step::Download => match (plain(), self.release.size) {
                (true, Some(size)) => format!("Downloading {} MB", mb(size)),
                _ => format!("Downloading {}", self.release.to),
            },
            Step::Verify => "Verifying the signature".to_string(),
            Step::Install => format!("Installing {}", self.release.to),
            Step::Restart => "Restarting the background service".to_string(),
            Step::Confirm => "Confirming the new version".to_string(),
        };
        ui::stage_named(step.name(), &running, step.done());
        self.step = Some(step);
        self.since = match step {
            Step::Restart => self.restart_at.map_or(now, |at| at.min(now)),
            _ => now,
        };
        // The long stages announce themselves so a log never looks stuck.
        if matches!(step, Step::Download | Step::Restart) {
            ui::announce();
        }
    }

    /// Close the running stage with its result.
    fn close(&mut self, now: Instant) {
        let Some(step) = self.step.take() else {
            return;
        };
        let took = now.saturating_duration_since(self.since);
        let result = match step {
            Step::Download => match self.total.or(self.release.size) {
                Some(total) => format!("{} MB in {}", mb(total), secs(took)),
                None => format!("in {}", secs(took)),
            },
            Step::Verify => "signed by OpenLatch".to_string(),
            Step::Install => format!("{} kept as a backup", self.release.from),
            Step::Restart => format!("back in {}", secs(took)),
            Step::Confirm => format!("running {}", self.release.to),
        };
        ui::done(&result);
    }

    /// Show the download's progress. A daemon that reports no bytes leaves
    /// the plain spinner.
    fn bytes(&mut self, done: Option<u64>, total: Option<u64>, now: Instant) {
        let Some(done) = done.filter(|_| self.step == Some(Step::Download)) else {
            return;
        };
        self.total = total.or(self.total);
        self.rate.sample(now, done);
        let (frac, tail) = download_tail(done, self.total, self.rate.bytes_per_sec);
        ui::meter(frac, &tail);
    }

    /// Follow the in-process pipeline's live progress.
    fn observe(&mut self, progress: &update::ApplyProgress, now: Instant) {
        if let Some(stage) = progress.stage() {
            self.reach(Step::of(stage), now);
        }
        self.bytes(progress.bytes_done(), progress.bytes_total(), now);
    }

    /// The daemon is draining in-flight events before it restarts.
    fn draining(&mut self, now: Instant) {
        self.restarting(now);
        let at = *self.drain_at.get_or_insert(now);
        if self.step == Some(Step::Restart) {
            let left = DRAIN.saturating_sub(now.saturating_duration_since(at));
            let left = left.as_secs_f64().ceil().max(1.0) as u64;
            ui::meter(None, &format!("draining in-flight events · {left}s"));
        }
    }

    /// The daemon is down; the new one has yet to answer.
    fn waiting(&self) {
        if self.step == Some(Step::Restart) {
            ui::meter(None, &format!("waiting for {} to answer", self.release.to));
        }
    }

    /// Close the last stage: the apply is done.
    fn finish(&mut self, now: Instant) {
        self.close(now);
    }

    /// Fail the stage `at` names (or the running one, if that is later).
    fn fail(&mut self, at: FailedAt, now: Instant) -> Outcome {
        let why = at.why(&self.release, self.step);
        self.reach(why.step, now);
        ui::fail(&OlError::new(why.code, why.line));
        self.step = None;
        Outcome::Failed {
            release: self.release.clone(),
            at,
            step: why.step,
        }
    }

    /// The new version never settled and the old one came back: the running
    /// stage fails, then `◇  Rolled back · 0.5.7 restored and running`.
    fn rolled_back(&mut self) -> Outcome {
        let Release { from, to, .. } = &self.release;
        ui::fail(&OlError::new(
            crate::error::ERR_DAEMON_START_FAILED,
            format!("{to} didn't come back"),
        ));
        self.step = None;
        ui::stage_named(
            "Roll back",
            &format!("Rolling back to {from}"),
            "Rolled back",
        );
        ui::done(&format!("{from} restored and running"));
        Outcome::RolledBack {
            release: self.release.clone(),
        }
    }
}

/// Where an apply failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FailedAt {
    /// The pipeline reported a failed stage.
    Stage(ApplyStage),
    /// The daemon went down and nothing answered within [`BACK_WITHIN`].
    NotBack,
    /// The daemon stopped reporting progress for [`STALL`].
    Stalled,
}

/// What a failure tells the user, in each place it shows.
struct Why {
    step: Step,
    code: &'static str,
    /// The failed stage's line (`Verify failed · the signature …`) and the
    /// plain error line.
    line: String,
    /// The card's headline after `Update stopped: `.
    headline: String,
    /// The card's `What happened`.
    what: String,
    /// The plain summary's clause (`The signature doesn't match`).
    short: String,
    /// Nothing on disk was touched: the old version is still what runs.
    unchanged: bool,
}

impl FailedAt {
    fn why(self, release: &Release, running: Option<Step>) -> Why {
        use crate::error::{
            ERR_DAEMON_START_FAILED as START, ERR_READER_RETIREMENT_BLOCKED as READER,
            ERR_UPDATE_DAEMON_UNREACHABLE as GONE, ERR_UPDATE_VERIFY_FAILED as VERIFY,
        };
        let to = &release.to;
        let (step, code, line, headline, what, unchanged) = match self {
            Self::Stage(ApplyStage::Check) => (
                Step::Download,
                VERIFY,
                "Couldn't reach the update server".to_string(),
                "the download didn't start".to_string(),
                "The update server stopped answering.".to_string(),
                true,
            ),
            Self::Stage(ApplyStage::Download) => (
                Step::Download,
                VERIFY,
                "The download didn't finish".to_string(),
                "the download didn't finish".to_string(),
                "The download from the update server didn't finish.".to_string(),
                true,
            ),
            Self::Stage(ApplyStage::Extract) => (
                Step::Verify,
                VERIFY,
                "The download is damaged".to_string(),
                "the download didn't verify".to_string(),
                "The downloaded package is damaged.".to_string(),
                true,
            ),
            Self::Stage(ApplyStage::Verify) => (
                Step::Verify,
                VERIFY,
                "The signature doesn't match OpenLatch's release key".to_string(),
                "the download didn't verify".to_string(),
                "The signature doesn't match OpenLatch's key.".to_string(),
                true,
            ),
            Self::Stage(ApplyStage::Sanity) => (
                Step::Verify,
                VERIFY,
                format!("{to} failed its self-test"),
                "the download didn't verify".to_string(),
                format!("The downloaded {to} failed its self-test."),
                true,
            ),
            Self::Stage(ApplyStage::Reader) => (
                Step::Verify,
                READER,
                format!("{to} can't read this machine's policies"),
                format!("{to} can't read this machine's policies"),
                format!("{to} can't read the policies this machine enforces now."),
                true,
            ),
            Self::Stage(ApplyStage::Swap) => (
                Step::Install,
                VERIFY,
                "The installed files couldn't be replaced".to_string(),
                format!("{to} couldn't be installed"),
                "The installed files couldn't be replaced.".to_string(),
                false,
            ),
            Self::Stage(ApplyStage::Drain | ApplyStage::Restart) => (
                Step::Restart,
                START,
                "The background service couldn't restart".to_string(),
                "the background service didn't restart".to_string(),
                format!("{to} is installed, but the background service couldn't restart into it."),
                false,
            ),
            Self::Stage(ApplyStage::Healthz) => (
                Step::Confirm,
                START,
                format!("{to} didn't pass its health check"),
                format!("{to} didn't pass its health check"),
                format!("{to} started but didn't pass its own health check."),
                false,
            ),
            Self::NotBack => (
                running.unwrap_or(Step::Restart),
                START,
                format!("{to} didn't come back"),
                format!("{to} didn't come back"),
                format!(
                    "{to} was installed, but the background service didn't answer within 60 s."
                ),
                false,
            ),
            Self::Stalled => (
                running.unwrap_or(Step::Download),
                GONE,
                "The background service stopped reporting progress".to_string(),
                "the update stalled".to_string(),
                "The background service stopped reporting progress. The update may still finish."
                    .to_string(),
                false,
            ),
        };
        let short = match self {
            Self::Stage(ApplyStage::Verify) => "The signature doesn't match".to_string(),
            _ => what.trim_end_matches('.').to_string(),
        };
        // A failure reported for a stage the rail has already passed lands on
        // the running one. A daemon that never came back fails where the rail
        // stands: it may have gone down before it ever reached the swap.
        let step = match self {
            Self::NotBack | Self::Stalled => step,
            _ => running.map_or(step, |r| r.max(step)),
        };
        Why {
            step,
            code,
            line,
            headline,
            what,
            short,
            unchanged,
        }
    }
}

/// Is the service running the version this run installed?
#[derive(Debug, Clone, PartialEq, Eq)]
enum Service {
    /// Serving the new version.
    Running,
    /// No background service answered.
    NotRunning,
    /// Still serving this version.
    Stale(String),
}

/// How a run ended.
#[derive(Debug, Clone)]
enum Outcome {
    UpToDate {
        version: String,
        /// The background service still runs this older version.
        stale: Option<String>,
    },
    /// A release is out and nothing asked to install it: `--check`, or no
    /// terminal to ask on.
    Available {
        release: Release,
        check_only: bool,
    },
    Declined {
        release: Release,
    },
    CheckFailed {
        from: String,
        host: String,
        unreachable: bool,
    },
    Updated {
        release: Release,
        service: Service,
    },
    Failed {
        release: Release,
        at: FailedAt,
        /// The rail stage it failed on.
        step: Step,
    },
    RolledBack {
        release: Release,
    },
}

impl Outcome {
    fn kind(&self) -> ui::Update {
        match self {
            Self::UpToDate { .. } => ui::Update::UpToDate,
            Self::Available { .. } => ui::Update::Available,
            Self::Declined { .. } => ui::Update::Declined,
            Self::CheckFailed { .. } => ui::Update::CheckFailed,
            Self::Updated { .. } => ui::Update::Updated,
            Self::Failed { .. } => ui::Update::Failed,
            Self::RolledBack { .. } => ui::Update::RolledBack,
        }
    }

    /// The card's tone: an update with no service serving it needs the user.
    fn verdict(&self) -> ui::Verdict {
        match self {
            Self::Updated { service, .. } if *service != Service::Running => {
                ui::Verdict::NeedsAttention
            }
            Self::UpToDate { stale: Some(_), .. } => ui::Verdict::NeedsAttention,
            _ => self.kind().verdict(),
        }
    }

    /// 0 ok, 7 needs attention, 1 failed.
    fn exit_code(&self) -> i32 {
        match self.verdict() {
            ui::Verdict::Live => 0,
            ui::Verdict::NeedsAttention | ui::Verdict::NoAgent => crate::cli::report::EXIT_DEGRADED,
            ui::Verdict::NotLive => 1,
        }
    }

    fn outro(&self) -> &'static str {
        match self {
            Self::UpToDate { .. } | Self::Updated { .. } => "Done.",
            Self::Available { .. } | Self::Declined { .. } => "Nothing changed.",
            _ => "Stopped.",
        }
    }

    /// The card, and the amber warnings heading its footer.
    fn card(
        &self,
        auto: &AutoUpdate,
        now: chrono::DateTime<chrono::Utc>,
        log: Option<&str>,
    ) -> (ui::Card, Vec<String>) {
        use ui::Row;
        let (title, rows, mut warnings) =
            match self {
                Self::UpToDate { version, stale } => {
                    let latest =
                        Row::new("Version", version.as_str()).with_tail("· the latest release");
                    match stale {
                        None => (
                            ui::Update::UpToDate.title(version, version),
                            vec![latest],
                            vec![],
                        ),
                        Some(running) => (
                            format!("OpenLatch {version} is installed"),
                            vec![
                                latest,
                                Row::new("Service", format!("still running {running}")),
                            ],
                            vec![stale_warning(running)],
                        ),
                    }
                }
                Self::Available {
                    release,
                    check_only,
                } => (
                    ui::Update::Available.title(&release.from, &release.to),
                    vec![
                        Row::new("Running", release.from.as_str()),
                        Row::new(
                            "When ready",
                            if *check_only {
                                "Run `openlatch update`."
                            } else {
                                "Run `openlatch update --yes`."
                            },
                        ),
                    ],
                    vec![],
                ),
                Self::Declined { release } => (
                    ui::Update::Declined.title(&release.from, &release.to),
                    vec![
                        Row::new("Available", release.to.as_str())
                            .with_tail(severity_tail(release, "")),
                        Row::new("When ready", "Run `openlatch update` again."),
                    ],
                    vec![],
                ),
                Self::CheckFailed { from, .. } => (
                    ui::Update::CheckFailed.title(from, from),
                    vec![
                        Row::new("Still running", from.as_str())
                            .with_tail("· nothing changed, your agents stay protected"),
                        Row::new("Why", self.check_why()),
                        Row::new(
                            "Try",
                            "Check the connection or proxy, then run `openlatch update`",
                        ),
                    ],
                    vec![],
                ),
                Self::Updated { release, service } => {
                    let updated = Row::new("Updated", format!("{} → {}", release.from, release.to))
                        .with_tail(severity_tail(release, " applied"));
                    match service {
                    Service::Running => (
                        ui::Update::Updated.title(&release.from, &release.to),
                        vec![
                            updated,
                            Row::new("Your agents", "stay protected · nothing to restart"),
                        ],
                        vec![],
                    ),
                    Service::NotRunning => (
                        format!("OpenLatch {} is installed", release.to),
                        vec![updated],
                        vec!["The background service isn't running · start it: `openlatch start`"
                            .to_string()],
                    ),
                    Service::Stale(running) => (
                        format!("OpenLatch {} is installed", release.to),
                        vec![updated, Row::new("Service", format!("still running {running}"))],
                        vec![stale_warning(running)],
                    ),
                }
                }
                Self::Failed { release, at, step } => {
                    let why = at.why(release, Some(*step));
                    let mut rows = Vec::new();
                    if why.unchanged {
                        rows.push(
                            Row::new("Still running", release.from.as_str())
                                .with_tail("· nothing was changed"),
                        );
                    }
                    rows.push(Row::new("What happened", why.what));
                    rows.push(Row::more(why.code));
                    rows.push(Row::new("Try", try_this(why.unchanged)));
                    (
                        format!(
                            "{}: {}",
                            ui::Update::Failed.title(&release.from, &release.to),
                            why.headline
                        ),
                        rows,
                        vec![],
                    )
                }
                Self::RolledBack { release } => (
                    ui::Update::RolledBack.title(&release.from, &release.to),
                    vec![
                        Row::new("Running", release.from.as_str())
                            .with_tail("· restored automatically, agents protected"),
                        Row::new(
                            "What happened",
                            format!("The {} service stopped right after starting.", release.to),
                        ),
                        Row::more(crate::error::ERR_DAEMON_START_FAILED),
                        Row::new("Try", try_this(false)),
                    ],
                    vec![],
                ),
            };
        let mut footer = Vec::new();
        match auto.line(now) {
            (true, line) => warnings.push(line),
            (false, line) => footer.push(line),
        }
        if let Some(log) = log {
            footer.push(format!("Log  {log}"));
        }
        let card = ui::Card {
            verdict: self.verdict(),
            title,
            rows,
            sections: vec![],
            footer,
        };
        (card, warnings)
    }

    fn check_why(&self) -> String {
        match self {
            Self::CheckFailed {
                host,
                unreachable: true,
                ..
            } => format!("{host} didn't answer"),
            Self::CheckFailed { host, .. } => format!("{host} didn't return a usable release"),
            _ => String::new(),
        }
    }

    /// Plain mode: the line under the check when a release is left for later.
    fn plain_note(&self) -> Option<String> {
        match self {
            Self::Available {
                check_only: true, ..
            } => Some("To install it, run: openlatch update --yes".to_string()),
            Self::Available { .. } => Some(
                "Not applied: no terminal to ask. To update unattended, run: openlatch update --yes"
                    .to_string(),
            ),
            _ => None,
        }
    }

    /// Plain mode: one sentence of what the machine runs now, for an outcome
    /// that is not green.
    fn sentence(&self) -> Option<String> {
        match self {
            Self::CheckFailed { from, .. } => Some(format!(
                "Still running {from} · nothing changed. {}.",
                self.check_why()
            )),
            Self::Updated {
                release,
                service: Service::NotRunning,
            } => Some(format!(
                "Installed {} · the background service isn't running. Start it: openlatch start",
                release.to
            )),
            Self::Updated {
                release: Release { to: version, .. },
                service: Service::Stale(running),
            }
            | Self::UpToDate {
                version,
                stale: Some(running),
            } => Some(format!(
                "Installed {version} · the background service is still on {running}. Run: openlatch restart"
            )),
            Self::Failed { release, at, step } => {
                let why = at.why(release, Some(*step));
                Some(if why.unchanged {
                    format!(
                        "Still running {} · nothing was changed. {} ({}).",
                        release.from, why.short, why.code
                    )
                } else {
                    format!("{} ({}).", why.short, why.code)
                })
            }
            Self::RolledBack { release } => Some(format!(
                "Running {} again · {} stopped right after starting and was rolled back ({}).",
                release.from,
                release.to,
                crate::error::ERR_DAEMON_START_FAILED
            )),
            _ => None,
        }
    }

    /// The `result=` line's fields after the token.
    fn fields(&self, log: Option<&str>) -> Vec<(&'static str, String)> {
        let mut f: Vec<(&'static str, String)> = match self {
            Self::UpToDate { version, stale } => {
                let mut f = vec![("version", version.clone())];
                if stale.is_some() {
                    f.push(("hint", "openlatch restart".to_string()));
                }
                f
            }
            Self::Available { release, .. } => vec![
                ("from", release.from.clone()),
                ("to", release.to.clone()),
                ("severity", release.severity.as_str().to_string()),
                ("hint", "openlatch update --yes".to_string()),
            ],
            Self::Declined { release } => {
                vec![("from", release.from.clone()), ("to", release.to.clone())]
            }
            Self::CheckFailed {
                from, unreachable, ..
            } => vec![
                ("version", from.clone()),
                (
                    "reason",
                    if *unreachable {
                        "registry-unreachable"
                    } else {
                        "registry-error"
                    }
                    .to_string(),
                ),
            ],
            Self::Updated { release, service } => {
                let mut f = vec![("from", release.from.clone()), ("to", release.to.clone())];
                match service {
                    Service::Running => {}
                    Service::NotRunning => f.push(("hint", "openlatch start".to_string())),
                    Service::Stale(_) => f.push(("hint", "openlatch restart".to_string())),
                }
                f
            }
            Self::Failed { release, at, step } => {
                let why = at.why(release, Some(*step));
                let mut f = vec![
                    ("step", why.step.key().to_string()),
                    ("code", why.code.to_string()),
                ];
                if why.unchanged {
                    f.push(("version", release.from.clone()));
                }
                f
            }
            Self::RolledBack { release } => vec![
                ("from", release.to.clone()),
                ("to", release.from.clone()),
                ("code", crate::error::ERR_DAEMON_START_FAILED.to_string()),
            ],
        };
        if let Some(log) = log {
            f.push(("log", log.to_string()));
        }
        f
    }
}

/// The warning a service still on an older version gets.
fn stale_warning(running: &str) -> String {
    format!("The background service is still on {running} · restart it: `openlatch restart`")
}

/// ` · security fix` after a critical release's version (`suffix` finishes it).
fn severity_tail(release: &Release, suffix: &str) -> String {
    match release.severity {
        Severity::Critical => format!("· security fix{suffix}"),
        Severity::Normal => String::new(),
    }
}

fn try_this(unchanged: bool) -> &'static str {
    if unchanged {
        "Run `openlatch update` again. If it fails twice, share the log below with IT or OpenLatch."
    } else {
        "Run `openlatch doctor`, then share the log below."
    }
}

/// Whether the background worker keeps this machine up to date.
#[derive(Debug, Clone, Default)]
struct AutoUpdate {
    on: bool,
    /// `OPENLATCH_AUTO_UPDATE` is set, and so decides.
    by_env: bool,
    /// When the worker last checked (RFC 3339), if it has.
    last_check: Option<String>,
}

impl AutoUpdate {
    /// The one quiet line: `(is a warning, text)`. Off is never a pass: it is
    /// a warning with the setting that turns it back on.
    fn line(&self, now: chrono::DateTime<chrono::Utc>) -> (bool, String) {
        if !self.on {
            let remedy = if self.by_env {
                "`OPENLATCH_AUTO_UPDATE=true`"
            } else {
                "`[update] auto_update = true`"
            };
            return (true, format!("Automatic updates: off · turn on: {remedy}"));
        }
        let checked = self
            .last_check
            .as_deref()
            .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())
            .map(|t| ago(now.signed_duration_since(t)));
        match checked {
            Some(ago) => (false, format!("Automatic updates: on · last checked {ago}")),
            None => (false, "Automatic updates: on".to_string()),
        }
    }

    /// The line as plain mode writes it: `! ` ahead of a warning, no marks.
    fn plain_line(&self, now: chrono::DateTime<chrono::Utc>) -> String {
        let (warn, line) = self.line(now);
        let line = ui::style(&line, false);
        if warn {
            format!("! {line}")
        } else {
            line
        }
    }
}

/// `just now`, `12m ago`, `4h ago`, `3d ago`.
fn ago(elapsed: chrono::Duration) -> String {
    let s = elapsed.num_seconds().max(0);
    match s {
        0..60 => "just now".to_string(),
        60..3600 => format!("{}m ago", s / 60),
        3600..86_400 => format!("{}h ago", s / 3600),
        _ => format!("{}d ago", s / 86_400),
    }
}

/// Close the rail on `outcome`: the outro and card (or plain mode's lines),
/// then the `result=` line. Returns the exit code.
fn finish(outcome: &Outcome, auto: &AutoUpdate, now: chrono::DateTime<chrono::Utc>) -> i32 {
    let exit = outcome.exit_code();
    let log = ui::log_path()
        .map(|p| p.display().to_string())
        .filter(|_| outcome.verdict() == ui::Verdict::NotLive);
    if plain() {
        // Under the check, as its stage's own line: one line, so a log greps it.
        if let Some(note) = outcome.plain_note() {
            margin(&format!("      {note}"));
        }
        if let Some(sentence) = outcome.sentence() {
            margin(&sentence);
        }
        margin(&auto.plain_line(now));
    } else {
        ui::outro(outcome.outro());
        let (card, warnings) = outcome.card(auto, now, log.as_deref());
        ui::card_with_warnings(&card, &warnings);
    }
    let fields = outcome.fields(log.as_deref());
    let fields: Vec<(&str, &str)> = fields.iter().map(|(k, v)| (*k, v.as_str())).collect();
    ui::result_token(outcome.kind().token(), exit, &fields);
    exit
}

/// A run that stops on an error before it can reach a verdict: a refused
/// binary, a daemon that cannot be driven.
struct Stop {
    error: OlError,
    exit: i32,
}

impl Stop {
    fn new(error: OlError, exit: i32) -> Self {
        Self { error, exit }
    }
}

fn stop(s: &Stop) -> i32 {
    ui::fail(&s.error);
    ui::outro("Stopped.");
    ui::result_token("failed", s.exit, &[("code", s.error.code)]);
    s.exit
}

/// The daemon path's clock: how often it polls, how long it waits. The
/// command runs on [`Timing::REAL`]; tests shrink it.
#[derive(Debug, Clone, Copy)]
struct Timing {
    /// Between status polls, and between `/health` polls after the restart.
    poll: Duration,
    /// Per request to the daemon.
    request: Duration,
    /// How long the new daemon has to answer after the restart.
    back_within: Duration,
    /// How long the daemon may report the same stage and bytes.
    stall: Duration,
    /// Consecutive polls with the daemon wholly silent (status and `/health`)
    /// before it counts as down, when it never reported reaching the swap.
    misses: u32,
}

impl Timing {
    const REAL: Self = Self {
        poll: POLL,
        request: Duration::from_secs(2),
        back_within: BACK_WITHIN,
        stall: STALL,
        misses: 8,
    };
}

/// What following the daemon's status came to.
enum Follow {
    Done(Outcome),
    /// The daemon went down for its restart (`dropped`), or reported the
    /// apply complete while still answering.
    Restarting {
        dropped: bool,
    },
}

/// What waiting for the daemon after the restart came to.
enum Back {
    Done(Outcome),
    /// The daemon answering on the old version is the same process, still
    /// applying: follow its status again.
    Resume,
}

/// How far the daemon has been seen to get.
#[derive(Default)]
struct Watch {
    /// The last stage and byte count, and when they last changed.
    seen: (Option<String>, Option<u64>),
    changed: Option<Instant>,
    /// It reported the swap, the drain or the restart: going down is expected.
    swapped: bool,
    /// Consecutive polls it did not answer at all.
    misses: u32,
}

/// Let the daemon apply the update, following its progress through the
/// restart until the new version answers.
async fn via_daemon(
    release: Release,
    port: u16,
    token: &str,
    force_cargo: bool,
    timing: Timing,
) -> Result<Outcome, Stop> {
    let client = local_client(Duration::from_secs(15)).map_err(|e| {
        Stop::new(
            OlError::new(
                crate::error::ERR_UPDATE_DAEMON_UNREACHABLE,
                format!("failed to build HTTP client: {e}"),
            ),
            1,
        )
    })?;
    let resp = client
        .post(format!("http://127.0.0.1:{port}/admin/update"))
        .bearer_auth(token)
        .json(&json!({"force_cargo_install": force_cargo}))
        .send()
        .await
        .map_err(|e| Stop::new(rpc_failed(&e), 6))?;
    let status = resp.status();
    let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
    if status != reqwest::StatusCode::ACCEPTED {
        return match rejection(status, &body, &release.from) {
            Rejection::UpToDate(version) => Ok(Outcome::UpToDate {
                version,
                stale: None,
            }),
            Rejection::Refused(error, exit) => Err(Stop::new(error, exit)),
        };
    }
    // The daemon says what it runs and what it installs; it is the one
    // restarting, so its word beats this CLI's.
    let said = |key: &str, or: &str| {
        body.get(key)
            .and_then(|v| v.as_str())
            .unwrap_or(or)
            .to_string()
    };
    let release = Release {
        from: said("from", &release.from),
        to: said("to", &release.to),
        ..release
    };
    let mut apply = Apply::new(release, Instant::now());
    apply.reach(Step::Download, Instant::now());
    let mut watch = Watch::default();
    loop {
        let dropped = match follow(&client, port, token, &mut apply, &mut watch, timing).await {
            Follow::Done(outcome) => return Ok(outcome),
            Follow::Restarting { dropped } => dropped,
        };
        match come_back(&client, port, token, &mut apply, &watch, dropped, timing).await {
            Back::Done(outcome) => return Ok(outcome),
            Back::Resume => {
                watch.misses = 0;
                // The same process was only slow: that drop began no restart.
                if !watch.swapped {
                    apply.restart_at = None;
                }
            }
        }
    }
}

/// Follow `/admin/update/status` until the daemon goes down for its restart,
/// reports the apply complete, or fails.
async fn follow(
    client: &reqwest::Client,
    port: u16,
    token: &str,
    apply: &mut Apply,
    watch: &mut Watch,
    timing: Timing,
) -> Follow {
    loop {
        let now = Instant::now();
        let changed = *watch.changed.get_or_insert(now);
        if now.saturating_duration_since(changed) > timing.stall {
            return Follow::Done(apply.fail(FailedAt::Stalled, now));
        }
        let Some(poll) = poll_status(client, port, token, timing.request).await else {
            // One silent poll is not a restart: a daemon that answers
            // `/health` was only slow, and one that answers nothing counts
            // as down once it has reached the swap, or after
            // `timing.misses` silent polls in a row.
            if health_version(client, port, timing.request).await.is_some() {
                watch.misses = 0;
            } else {
                watch.misses += 1;
                if watch.swapped || watch.misses >= timing.misses {
                    apply.restarting(Instant::now());
                    return Follow::Restarting { dropped: true };
                }
            }
            tokio::time::sleep(timing.poll).await;
            continue;
        };
        watch.misses = 0;
        let now = Instant::now();
        let key = (poll.stage.clone(), poll.bytes_done);
        if key != watch.seen {
            watch.seen = key;
            watch.changed = Some(now);
        }
        let stage = poll.stage.as_deref().and_then(apply_stage);
        if matches!(
            stage,
            Some(ApplyStage::Swap | ApplyStage::Drain | ApplyStage::Restart)
        ) {
            apply.restarting(now);
        }
        if let Some(stage) = stage {
            apply.reach(Step::of(stage), now);
        }
        watch.swapped |= matches!(
            stage,
            Some(ApplyStage::Swap | ApplyStage::Drain | ApplyStage::Restart | ApplyStage::Healthz)
        );
        apply.bytes(poll.bytes_done, poll.bytes_total, now);
        if matches!(stage, Some(ApplyStage::Drain | ApplyStage::Restart)) {
            apply.draining(now);
        }
        match poll.status.as_deref() {
            Some("completed") => {
                // Complete with nothing swapped and the old version still
                // serving: the daemon found itself up to date after all.
                if !watch.swapped {
                    let serving = health_version(client, port, timing.request).await;
                    if serving.is_some_and(|v| serves_from(&v, &apply.release, IDENTITY)) {
                        ui::done("already on the latest");
                        return Follow::Done(Outcome::UpToDate {
                            version: apply.release.from.clone(),
                            stale: None,
                        });
                    }
                }
                return Follow::Restarting { dropped: false };
            }
            // The daemon stamps `in_progress` before it answers the POST, so
            // `idle` is a daemon that restarted since, and a rollback leaves
            // one idle: which version answers decides.
            Some("idle") => {
                apply.restarting(now);
                return Follow::Restarting { dropped: true };
            }
            Some("failed") => {
                if let Some(error) = &poll.error {
                    ui::detail(error);
                }
                let at = FailedAt::Stage(stage.unwrap_or(ApplyStage::Download));
                return Follow::Done(apply.fail(at, now));
            }
            _ => {}
        }
        tokio::time::sleep(timing.poll).await;
    }
}

/// After the restart: wait for a version to answer `/health`. The new one,
/// settled by its own post-restart probe, is the update confirmed. The old
/// one, once the daemon has been seen down, is either the same process still
/// applying (its status says so) or a rollback (a restored daemon is idle).
async fn come_back(
    client: &reqwest::Client,
    port: u16,
    token: &str,
    apply: &mut Apply,
    watch: &Watch,
    mut dropped: bool,
    timing: Timing,
) -> Back {
    if watch.swapped {
        apply.reach(Step::Restart, Instant::now());
    }
    let deadline = Instant::now() + timing.back_within;
    let mut answered = false;
    while Instant::now() < deadline {
        let now = Instant::now();
        match health_version(client, port, timing.request).await {
            None => {
                dropped = true;
                apply.restarting(now);
                apply.waiting();
            }
            Some(v) if is_version(&v, &apply.release.to) => {
                apply.reach(Step::Confirm, now);
                answered = true;
                let settled = poll_status(client, port, token, timing.request).await;
                // Still settling (or failed, and about to roll back): wait.
                if !matches!(
                    settled.and_then(|p| p.status).as_deref(),
                    Some("in_progress" | "failed")
                ) {
                    apply.finish(Instant::now());
                    return Back::Done(Outcome::Updated {
                        release: apply.release.clone(),
                        service: Service::Running,
                    });
                }
            }
            Some(v)
                if dropped
                    && serves_from(&v, &apply.release, IDENTITY)
                    && !is_version(&v, &apply.release.to) =>
            {
                let poll = poll_status(client, port, token, timing.request).await;
                let applying = poll.as_ref().is_some_and(|p| {
                    p.status.as_deref() == Some("in_progress")
                        && !matches!(
                            p.stage.as_deref().and_then(apply_stage),
                            Some(ApplyStage::Drain | ApplyStage::Restart | ApplyStage::Healthz)
                        )
                });
                if applying {
                    return Back::Resume;
                }
                return Back::Done(apply.rolled_back());
            }
            // The old daemon, still draining.
            Some(_) => apply.draining(now),
        }
        tokio::time::sleep(timing.poll).await;
    }
    let at = if answered {
        FailedAt::Stage(ApplyStage::Healthz)
    } else {
        FailedAt::NotBack
    };
    Back::Done(apply.fail(at, Instant::now()))
}

/// Apply in this process (no daemon running), reading the pipeline's live
/// progress every [`TICK`].
async fn in_process(release: Release, ctx: &Ctx, force_cargo: bool) -> Result<Outcome, Stop> {
    let progress = Arc::new(update::ApplyProgress::default());
    let opts = update::ApplyOptions {
        current_version: ctx.current.clone(),
        registry_origin: ctx.registry.clone(),
        download_timeout: Duration::from_secs(60),
        force_cargo_install: force_cargo,
        mode: update::ApplyMode::InProcess,
        egress: ctx.egress.clone(),
        progress: progress.clone(),
    };
    let mut apply = Apply::new(release, Instant::now());
    apply.reach(Step::Download, Instant::now());
    let run = update::apply_local(opts);
    tokio::pin!(run);
    let mut tick = tokio::time::interval(TICK);
    let result = loop {
        tokio::select! {
            result = &mut run => break result,
            _ = tick.tick() => apply.observe(&progress, Instant::now()),
        }
    };
    let now = Instant::now();
    match result {
        update::ApplyResult::Applied { from, to, .. } => {
            apply.reach(Step::Install, now);
            apply.finish(now);
            // "No daemon was running" was true when the swap started. A
            // supervisor may have brought one up since, on either binary.
            let service = match daemon_version(ctx.port).await {
                None => Service::NotRunning,
                Some(v) if is_version(&v, &to) => Service::Running,
                Some(v) => Service::Stale(v),
            };
            let release = Release {
                from,
                to,
                ..apply.release
            };
            Ok(Outcome::Updated { release, service })
        }
        update::ApplyResult::UpToDate { current } => {
            ui::done("already on the latest");
            Ok(Outcome::UpToDate {
                version: current,
                stale: None,
            })
        }
        update::ApplyResult::RefusedCargoInstall { suggestion } => {
            Err(Stop::new(cargo_refusal(&suggestion), 5))
        }
        update::ApplyResult::Failed { stage, reason } => {
            ui::detail(&format!("{}: {reason}", stage.as_str()));
            Ok(apply.fail(FailedAt::Stage(stage), now))
        }
    }
}

// ---------------------------------------------------------------------------
// `--json` / `--quiet`: the documents this command always printed (`--json`
// only), with their exit codes
// ---------------------------------------------------------------------------

/// A JSON document on stdout, under `--json` only: `--quiet` prints nothing
/// there and keeps the same exit code.
fn print_json(output: &OutputConfig, value: &serde_json::Value) {
    if output.format == crate::cli::output::OutputFormat::Json {
        output.print_json(value);
    }
}

async fn run_json(args: &UpdateArgs, output: &OutputConfig, ctx: &Ctx) -> i32 {
    if !args.applies() {
        return run_check(output, &ctx.current, &ctx.registry, &ctx.egress).await;
    }

    // Cargo-install gate runs first so we never POST or hit the network
    // for a binary we can't update.
    if refuses_cargo(args) {
        output.print_error(&cargo_refusal(CARGO_SUGGESTION));
        return 5;
    }

    match probe_daemon(ctx.port).await {
        DaemonState::RunningAndReachable { port, token } => {
            apply_via_daemon_rpc(output, &ctx.current, port, &token, args.force_cargo).await
        }
        DaemonState::NotRunning => apply_in_process(output, ctx, args).await,
        DaemonState::RunningButUnauthenticated => {
            output.print_error(&unauthenticated());
            6
        }
    }
}

async fn run_check(
    output: &OutputConfig,
    current: &str,
    registry: &str,
    egress: &crate::egress::EgressConfig,
) -> i32 {
    // `--check` is read-only and idempotent; install-state.json is
    // updated by the apply paths only (the daemon's auto-update worker
    // bumps `last_check_at` on its periodic poll in P3).
    let result = update::check(current, registry, egress).await;
    match result {
        update::CheckResult::UpToDate { current } => {
            print_json(output, &json!({"current": current, "latest": null}));
            0
        }
        update::CheckResult::Available {
            current,
            latest,
            severity,
            ..
        } => {
            print_json(
                output,
                &json!({
                    "current": current,
                    "latest": latest,
                    "severity": severity.as_str(),
                }),
            );
            0
        }
        update::CheckResult::Failed { reason } => {
            output.print_info(&format!("update check failed: {reason}"));
            // Per the doc's idempotency table, `--check` always exits 0
            // — failure surfaces in the message, not the exit code.
            0
        }
    }
}

async fn apply_in_process(output: &OutputConfig, ctx: &Ctx, args: &UpdateArgs) -> i32 {
    let opts = update::ApplyOptions {
        current_version: ctx.current.clone(),
        registry_origin: ctx.registry.clone(),
        download_timeout: Duration::from_secs(60),
        force_cargo_install: args.force_cargo,
        mode: update::ApplyMode::InProcess,
        egress: ctx.egress.clone(),
        progress: Default::default(),
    };
    match update::apply_local(opts).await {
        update::ApplyResult::Applied { from, to, .. } => {
            output.print_info(&format!("Updated {from} → {to} (no daemon was running)"));
            // "No daemon was running" was true when the swap started. A
            // supervisor may have brought one up on the old binary since.
            let stale = warn_if_daemon_still_stale(output, ctx.port, &to).await;
            print_json(
                output,
                &json!({
                    "from": from, "to": to, "applied": true, "restart_required": stale,
                }),
            );
            0
        }
        update::ApplyResult::UpToDate { current } => {
            output.print_info(&format!("Already on the latest version ({current})"));
            print_json(output, &json!({"current": current, "idempotent": true}));
            0
        }
        update::ApplyResult::RefusedCargoInstall { suggestion } => {
            output.print_error(&cargo_refusal(&suggestion));
            5
        }
        update::ApplyResult::Failed { stage, reason } => {
            let err = OlError::new(
                crate::error::ERR_UPDATE_VERIFY_FAILED,
                format!("auto-update failed at stage `{}`: {reason}", stage.as_str()),
            );
            output.print_error(&err);
            1
        }
    }
}

async fn apply_via_daemon_rpc(
    output: &OutputConfig,
    current: &str,
    port: u16,
    token: &str,
    force_cargo: bool,
) -> i32 {
    let client = match local_client(Duration::from_secs(15)) {
        Ok(c) => c,
        Err(e) => {
            output.print_info(&format!("failed to build HTTP client: {e}"));
            return 1;
        }
    };
    let admin_url = format!("http://127.0.0.1:{port}/admin/update");
    let status_url = format!("{admin_url}/status");

    // 1. POST /admin/update.
    let post_resp = match client
        .post(&admin_url)
        .bearer_auth(token)
        .json(&json!({"force_cargo_install": force_cargo}))
        .send()
        .await
    {
        Ok(r) => r,
        Err(e) => {
            output.print_error(&rpc_failed(&e));
            return 6;
        }
    };
    let status = post_resp.status();
    if status != reqwest::StatusCode::ACCEPTED {
        // Map daemon error responses to CLI exit codes.
        let body: serde_json::Value = post_resp.json().await.unwrap_or(serde_json::Value::Null);
        return match rejection(status, &body, current) {
            Rejection::UpToDate(cur) => {
                output.print_info(&format!("Already on the latest version ({cur})"));
                print_json(output, &json!({"current": cur, "idempotent": true}));
                0
            }
            Rejection::Refused(err, exit) => {
                output.print_error(&err);
                exit
            }
        };
    }

    let post_body: serde_json::Value = post_resp.json().await.unwrap_or(serde_json::Value::Null);
    let from = post_body
        .get("from")
        .and_then(|v| v.as_str())
        .unwrap_or(current)
        .to_string();
    let to = post_body
        .get("to")
        .and_then(|v| v.as_str())
        .unwrap_or("?")
        .to_string();
    output.print_info(&format!("Updating {from} → {to}…"));

    // 2. Long-poll status until completed/failed OR daemon stops responding.
    let started = std::time::Instant::now();
    let max_wait = Duration::from_secs(120);
    let poll_interval = Duration::from_secs(1);
    loop {
        if started.elapsed() > max_wait {
            output.print_info("daemon long-poll timed out — the update may still be in progress");
            return 1;
        }
        let resp = client.get(&status_url).bearer_auth(token).send().await;
        match resp {
            Ok(r) if r.status().is_success() => {
                let body: StatusPoll = r.json().await.unwrap_or_default();
                match body.status.as_deref().unwrap_or("in_progress") {
                    "completed" => {
                        output.print_info(&format!("Updated {from} → {to}"));
                        let stale = warn_if_daemon_still_stale(output, port, &to).await;
                        print_json(
                            output,
                            &json!({
                                "from": from, "to": to, "applied": true, "restart_required": stale,
                            }),
                        );
                        return 0;
                    }
                    "failed" => {
                        let stage = body.stage.as_deref().unwrap_or("unknown");
                        let reason = body.error.as_deref().unwrap_or("");
                        // The restart not coming good is the daemon's start
                        // failing; anything earlier is the apply's.
                        let code = if matches!(stage, "drain" | "restart" | "healthz") {
                            crate::error::ERR_DAEMON_START_FAILED
                        } else {
                            crate::error::ERR_UPDATE_VERIFY_FAILED
                        };
                        let err = OlError::new(
                            code,
                            format!("update failed at stage `{stage}`: {reason}"),
                        );
                        output.print_error(&err);
                        return 1;
                    }
                    _ => {
                        // in_progress or idle — keep polling.
                        tokio::time::sleep(poll_interval).await;
                    }
                }
            }
            Ok(_) | Err(_) => {
                // Daemon stopped responding mid-poll — this is the
                // expected outcome on Unix where `execv` keeps the PID
                // but momentarily drops the listener, and on Windows
                // where the daemon spawn-detached + exited. Wait for
                // the new daemon to come back up and verify the
                // version bump.
                if let Some(new_version) = wait_for_daemon_version(port, &to).await {
                    output.print_info(&format!("Updated {from} → {new_version}"));
                    print_json(
                        output,
                        &json!({
                            "from": from,
                            "to": new_version,
                            "applied": true,
                        }),
                    );
                    return 0;
                }
                let err = OlError::new(
                    crate::error::ERR_DAEMON_START_FAILED,
                    "daemon did not return after the update — check `openlatch status`",
                );
                output.print_error(&err);
                return 1;
            }
        }
    }
}

/// Warn when the binary moved but the process did not.
///
/// A package manager — and `update --apply`'s own in-process swap when no
/// daemon was running — replaces the file on disk. The daemon already running
/// keeps serving the build it loaded at start, and every other signal on the
/// machine looks healthy: the file really is new, the daemon really answers
/// 200. On a security client that means the fix the user just installed is not
/// the code enforcing anything.
///
/// Returns `true` when a stale daemon was found and reported.
async fn warn_if_daemon_still_stale(output: &OutputConfig, port: u16, expected: &str) -> bool {
    match daemon_version(port).await {
        Some(running) if running != expected => {
            output.print_info(&format!(
                "The running daemon is still serving {running} — run `openlatch restart` to \
                 put {expected} in effect."
            ));
            crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
            true
        }
        _ => false,
    }
}

/// Poll `/health` until the daemon responds AND reports the expected
/// new version, or until a 60-second budget elapses. Returns the
/// reported version on success.
async fn wait_for_daemon_version(port: u16, expected: &str) -> Option<String> {
    let client = local_client(Duration::from_secs(2)).ok()?;
    let deadline = std::time::Instant::now() + Duration::from_secs(60);
    while std::time::Instant::now() < deadline {
        if let Some(v) = health_version(&client, port, Duration::from_secs(2)).await {
            if is_version(&v, expected) {
                return Some(v);
            }
        }
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
    None
}

// ---------------------------------------------------------------------------
// Shared: the daemon, errors
// ---------------------------------------------------------------------------

/// One `GET /admin/update/status` answer. Every field is optional and
/// strings stay strings, so a daemon older or newer than this CLI still
/// parses: one that predates the byte counts simply reports none.
#[derive(Debug, Default, serde::Deserialize)]
#[serde(default)]
struct StatusPoll {
    status: Option<String>,
    stage: Option<String>,
    error: Option<String>,
    bytes_done: Option<u64>,
    bytes_total: Option<u64>,
}

/// How long a loopback connect may take. Nothing listening is refused at
/// once on Unix, but Windows retries the SYN for about 2 s first.
const CONNECT: Duration = Duration::from_millis(300);

/// A loopback client with a whole-request `timeout`, failing fast when
/// nothing listens.
fn local_client(timeout: Duration) -> reqwest::Result<reqwest::Client> {
    crate::egress::client_builder()
        .connect_timeout(CONNECT)
        .timeout(timeout)
        .use_rustls_tls()
        .build()
}

/// The daemon's status; `None` once it stops answering (or answers an error).
async fn poll_status(
    client: &reqwest::Client,
    port: u16,
    token: &str,
    timeout: Duration,
) -> Option<StatusPoll> {
    let resp = client
        .get(format!("http://127.0.0.1:{port}/admin/update/status"))
        .bearer_auth(token)
        .timeout(timeout)
        .send()
        .await
        .ok()
        .filter(|r| r.status().is_success())?;
    Some(resp.json().await.unwrap_or_default())
}

/// The version the daemon's unauthenticated `/health` reports.
async fn health_version(client: &reqwest::Client, port: u16, timeout: Duration) -> Option<String> {
    let body: serde_json::Value = client
        .get(format!("http://127.0.0.1:{port}/health"))
        .timeout(timeout)
        .send()
        .await
        .ok()
        .filter(|r| r.status().is_success())?
        .json()
        .await
        .ok()?;
    body.get("version")?.as_str().map(str::to_string)
}

/// The version a daemon on `port` serves, if one answers.
async fn daemon_version(port: u16) -> Option<String> {
    let timeout = Duration::from_secs(2);
    health_version(&local_client(timeout).ok()?, port, timeout).await
}

/// This binary's identity, as `/health` reports it: the manifest version on
/// a release, `x.y.z-dev.N+gHASH` on a build between releases. Anything
/// compared against a daemon's `/health` answer is compared against this,
/// never against `CARGO_PKG_VERSION`, which only the registry check uses.
const IDENTITY: &str = env!("OPENLATCH_VERSION");

/// A `/health` answer is the version the update started from. The daemon
/// reports `release.from` as its manifest version but answers `/health`
/// with its identity, which a build between releases does not share, so
/// the identity of the binary it was installed with counts too.
fn serves_from(reported: &str, release: &Release, identity: &str) -> bool {
    is_version(reported, &release.from) || is_version(reported, identity)
}

/// A `/health` version is `expected`, allowing only a `+build` suffix:
/// `0.5.10` is not `0.5.1`, and `0.5.8-rc.1` is a different, lower version
/// than `0.5.8`.
fn is_version(reported: &str, expected: &str) -> bool {
    reported
        .strip_prefix(expected)
        .is_some_and(|rest| rest.is_empty() || rest.starts_with('+'))
}

fn read_token() -> Option<String> {
    let token = std::fs::read_to_string(config::openlatch_dir().join("daemon.token")).ok()?;
    Some(token.trim().to_string()).filter(|t| !t.is_empty())
}

const CARGO_SUGGESTION: &str = "Run: cargo install --force --locked openlatch-client";

fn refuses_cargo(args: &UpdateArgs) -> bool {
    !args.force_cargo
        && matches!(
            install_state::detect_install_method(),
            install_state::InstallMethod::CargoInstall
        )
}

fn cargo_refusal(suggestion: &str) -> OlError {
    OlError::new(
        crate::error::ERR_UPDATE_REFUSED_CARGO_INSTALL,
        "this binary was installed via `cargo install` — auto-update would not take effect",
    )
    .with_suggestion(suggestion)
}

fn unauthenticated() -> OlError {
    OlError::new(
        crate::error::ERR_UPDATE_DAEMON_UNREACHABLE,
        "daemon is running but the bearer token in ~/.openlatch/daemon.token is missing or wrong",
    )
    .with_suggestion(
        "Run `openlatch init --reconfig` to regenerate, or stop the daemon and re-run.",
    )
}

fn rpc_failed(e: &reqwest::Error) -> OlError {
    OlError::new(
        crate::error::ERR_UPDATE_DAEMON_UNREACHABLE,
        format!("daemon RPC failed: {e}"),
    )
    .with_suggestion("Is the daemon still running? Try `openlatch status`.")
}

/// How the daemon turned `POST /admin/update` down.
enum Rejection {
    /// Already on the latest version: an idempotent success.
    UpToDate(String),
    /// Refused, with the error and exit code to report.
    Refused(OlError, i32),
}

fn rejection(status: reqwest::StatusCode, body: &serde_json::Value, current: &str) -> Rejection {
    let message = body
        .pointer("/error/message")
        .and_then(|v| v.as_str())
        .unwrap_or("daemon rejected update");
    let suggestion = body
        .pointer("/error/suggestion")
        .and_then(|v| v.as_str())
        .map(String::from);

    match status.as_u16() {
        409 => {
            // Either cargo-install refusal or already-up-to-date.
            if body.get("idempotent").and_then(|v| v.as_bool()) == Some(true) {
                let cur = body
                    .get("current")
                    .and_then(|v| v.as_str())
                    .unwrap_or(current);
                return Rejection::UpToDate(cur.to_string());
            }
            let mut err = OlError::new(
                crate::error::ERR_UPDATE_REFUSED_CARGO_INSTALL,
                message.to_string(),
            );
            if let Some(s) = suggestion {
                err = err.with_suggestion(s);
            }
            Rejection::Refused(err, 5)
        }
        503 => Rejection::Refused(
            OlError::new(crate::error::ERR_DAEMON_START_FAILED, message.to_string()),
            1,
        ),
        _ => Rejection::Refused(
            OlError::new(
                crate::error::ERR_UPDATE_VERIFY_FAILED,
                format!("daemon rejected update (HTTP {status}): {message}"),
            ),
            1,
        ),
    }
}

enum DaemonState {
    RunningAndReachable { port: u16, token: String },
    NotRunning,
    RunningButUnauthenticated,
}

/// `/health` is unauthenticated — use it to detect "is something
/// listening" before trying the bearer-protected `/admin` endpoint.
async fn probe_daemon(port: u16) -> DaemonState {
    let Ok(client) = local_client(Duration::from_secs(2)) else {
        return DaemonState::NotRunning;
    };
    let health_url = format!("http://127.0.0.1:{port}/health");
    if client.get(&health_url).send().await.is_err() {
        return DaemonState::NotRunning;
    }
    match read_token() {
        Some(token) => DaemonState::RunningAndReachable { port, token },
        None => DaemonState::RunningButUnauthenticated,
    }
}

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

    #[test]
    fn status_poll_tolerates_a_daemon_without_byte_counts() {
        let older: StatusPoll = serde_json::from_value(json!({
            "status": "in_progress", "stage": "download", "from": "0.1.0", "to": "0.2.0",
            "started_at": null, "ended_at": null, "error": null,
        }))
        .expect("an older daemon's body parses");
        assert_eq!(older.status.as_deref(), Some("in_progress"));
        assert_eq!(older.bytes_done, None);
        assert_eq!(older.bytes_total, None);

        let newer: StatusPoll = serde_json::from_value(json!({
            "status": "in_progress", "stage": "some_future_stage",
            "bytes_done": 10, "bytes_total": 20,
        }))
        .expect("a newer daemon's body parses");
        assert_eq!(newer.stage.as_deref(), Some("some_future_stage"));
        assert_eq!((newer.bytes_done, newer.bytes_total), (Some(10), Some(20)));
    }
}

/// Every outcome of a run, driven on an in-memory rail in each mode with the
/// same calls the command makes, the network replaced by what it answered.
#[cfg(test)]
mod rail_tests {
    use super::*;
    use crate::cli::ui::{Rail, INSTALL_LOCK};

    /// 8,806,432 bytes: the playground's 8.4 MB.
    const SIZE: u64 = 8_806_432;

    fn release(severity: Severity) -> Release {
        Release {
            from: "0.5.7".into(),
            to: "0.5.8".into(),
            severity,
            size: Some(SIZE),
        }
    }

    fn available(severity: Severity) -> CheckResult {
        CheckResult::Available {
            current: "0.5.7".into(),
            latest: "0.5.8".into(),
            severity,
            tarball_url: String::new(),
            tarball_integrity: String::new(),
            size: Some(SIZE),
        }
    }

    fn now() -> chrono::DateTime<chrono::Utc> {
        "2026-09-23T12:00:00Z".parse().expect("a timestamp")
    }

    fn auto_on() -> AutoUpdate {
        AutoUpdate {
            on: true,
            by_env: false,
            last_check: Some("2026-09-23T08:00:00Z".into()),
        }
    }

    /// Run `script` on a rail of `total` stages in `mode`, opened as the
    /// command opens it. Returns the screen and the exit code.
    fn drive(mode: Mode, total: usize, script: impl FnOnce(Instant) -> i32) -> (Vec<String>, i32) {
        let _l = INSTALL_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (rail, screen) = Rail::buffer(Caps::new(mode, false, false, 80), total);
        let exit = {
            let _guard = ui::install_rail(rail).expect("installs");
            begin();
            script(Instant::now())
        };
        let lines = screen.lock().unwrap().clone();
        if mode != Mode::Live {
            assert!(lines.iter().all(|l| l.is_ascii()), "{mode:?}: {lines:#?}");
        }
        (lines, exit)
    }

    fn ms(t0: Instant, ms: u64) -> Instant {
        t0 + Duration::from_millis(ms)
    }

    /// Check, (ask,) then download and reach verify, as the daemon reports them.
    fn check_and_download(t0: Instant, severity: Severity, ask: bool) -> Apply {
        let release = close_check(available(severity), "0.5.7", "https://registry.npmjs.org")
            .expect("a release");
        if ask {
            let (title, _, _) = question(&release, true);
            ui::stage_named("Update", &title, &title);
            answered(true);
        }
        let mut apply = Apply::new(release, t0);
        apply.reach(Step::Download, t0);
        apply.bytes(Some(0), Some(SIZE), t0);
        apply.bytes(Some(SIZE / 2), Some(SIZE), ms(t0, 1000));
        apply.bytes(Some(SIZE), Some(SIZE), ms(t0, 2900));
        apply.reach(Step::of(ApplyStage::Extract), ms(t0, 2900));
        apply
    }

    /// Install, then the restart: drain, down, and back.
    fn install_and_restart(apply: &mut Apply, t0: Instant) {
        apply.reach(Step::of(ApplyStage::Swap), ms(t0, 4000));
        apply.reach(Step::of(ApplyStage::Drain), ms(t0, 5100));
        apply.draining(ms(t0, 5100));
        apply.waiting();
    }

    fn updated(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 6, |t0| {
            let mut apply = check_and_download(t0, Severity::Normal, mode != Mode::Plain);
            install_and_restart(&mut apply, t0);
            apply.reach(Step::of(ApplyStage::Healthz), ms(t0, 10_500));
            apply.finish(ms(t0, 11_300));
            let outcome = Outcome::Updated {
                release: apply.release.clone(),
                service: Service::Running,
            };
            finish(&outcome, &auto_on(), now())
        })
    }

    #[test]
    fn updated_in_every_mode() {
        let (live, exit) = updated(Mode::Live);
        assert_eq!(exit, 0);
        assert_eq!(
            live[..18],
            [
                "┌  Updating OpenLatch",
                "│",
                "◇  Checked for updates · 0.5.7 → 0.5.8",
                "│",
                "◇  Update to 0.5.8 · yes",
                "│",
                "◇  Downloaded · 8.4 MB in 2.9s",
                "│",
                "◇  Verified · signed by OpenLatch",
                "│",
                "◇  Installed · 0.5.7 kept as a backup",
                "│",
                "◇  Restarted the background service · back in 5.4s",
                "│",
                "◇  Confirmed · running 0.5.8",
                "│",
                "└  Done.",
                "",
            ]
        );
        assert!(live[18].starts_with("  ╭─"), "{live:#?}");
        assert!(live[20].starts_with("  │ ✓  OpenLatch 0.5.8 is running"));
        let card = live.join("\n");
        assert!(card.contains("    Updated        0.5.7 → 0.5.8"));
        assert!(card.contains("    Your agents    stay protected · nothing to restart"));
        assert_eq!(
            live.last().map(String::as_str),
            Some("  Automatic updates: on · last checked 4h ago")
        );

        let (append, _) = updated(Mode::Append);
        assert_eq!(
            append[..9],
            [
                "+  Updating OpenLatch",
                "|",
                ">  Checking for updates...",
                "+  Checked for updates - 0.5.7 -> 0.5.8",
                "|",
                ">  Update to 0.5.8...",
                "+  Update to 0.5.8 - yes",
                "|",
                ">  Downloading 0.5.8...",
            ]
        );
        assert_eq!(append[9], "|   25%");
        assert_eq!(append[10], "|   50% 4.2 / 8.4 MB - 4.2 MB/s - 1s left");
        assert_eq!(append[11], "|   75%");
        assert!(
            append[12].starts_with("|  100% 8.4 / 8.4 MB - "),
            "{append:#?}"
        );
        assert_eq!(append[13], "+  Downloaded - 8.4 MB in 2.9s");
        assert!(append.contains(&">  Restarting the background service...".to_string()));
        assert!(append.contains(&"+  Confirmed - running 0.5.8".to_string()));
        assert!(append.contains(&"+  Done.".to_string()));
        assert!(append
            .iter()
            .any(|l| l.starts_with("  | +  OpenLatch 0.5.8 is running")));

        let (plain, exit) = updated(Mode::Plain);
        assert_eq!(exit, 0);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/6] Checked for updates - 0.5.7 -> 0.5.8",
                "[2/6] Downloading 8.4 MB...",
                "[2/6] Downloaded - 8.4 MB in 2.9s",
                "[3/6] Verified - signed by OpenLatch",
                "[4/6] Installed - 0.5.7 kept as a backup",
                "[5/6] Restarting the background service...",
                "[5/6] Restarted the background service - back in 5.4s",
                "[6/6] Confirmed - running 0.5.8",
                "Automatic updates: on - last checked 4h ago",
                "result=updated from=0.5.7 to=0.5.8 exit=0",
            ]
        );
    }

    fn up_to_date(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 1, |_| {
            let check = CheckResult::UpToDate {
                current: "0.5.8".into(),
            };
            let outcome = close_check(check, "0.5.8", "https://registry.npmjs.org")
                .expect_err("nothing to install");
            finish(&outcome, &auto_on(), now())
        })
    }

    #[test]
    fn up_to_date_in_every_mode() {
        let (live, exit) = up_to_date(Mode::Live);
        assert_eq!(exit, 0);
        assert_eq!(
            live[..6],
            [
                "┌  Updating OpenLatch",
                "│",
                "◇  Checked for updates · already on the latest (0.5.8)",
                "│",
                "└  Done.",
                "",
            ]
        );
        assert!(live[8].starts_with("  │ ✓  OpenLatch 0.5.8 is up to date"));
        assert!(live
            .iter()
            .any(|l| l.contains("    Version        0.5.8 · the latest release")));

        let (append, _) = up_to_date(Mode::Append);
        assert!(append.contains(&"+  Checked for updates - already on the latest (0.5.8)".into()));
        assert!(append
            .iter()
            .any(|l| l.starts_with("  | +  OpenLatch 0.5.8 is up to date")));

        let (plain, _) = up_to_date(Mode::Plain);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/1] Checked for updates - already on the latest (0.5.8)",
                "Automatic updates: on - last checked 4h ago",
                "result=up_to_date version=0.5.8 exit=0",
            ]
        );
    }

    /// No terminal to ask (or `--check`): the release is reported, not applied.
    fn available_not_applied(mode: Mode, check_only: bool) -> (Vec<String>, i32) {
        drive(mode, 1, |_| {
            let check = available(Severity::Normal);
            let release =
                close_check(check, "0.5.7", "https://registry.npmjs.org").expect("a release");
            let outcome = Outcome::Available {
                release,
                check_only,
            };
            finish(&outcome, &auto_on(), now())
        })
    }

    #[test]
    fn available_without_a_terminal_in_every_mode() {
        let (live, exit) = available_not_applied(Mode::Live, false);
        assert_eq!(exit, 7);
        assert!(live.contains(&"└  Nothing changed.".to_string()));
        assert!(live
            .iter()
            .any(|l| l.starts_with("  │ !  0.5.8 is available")));
        assert!(live
            .iter()
            .any(|l| l.contains("When ready     Run openlatch update --yes.")));

        let (append, _) = available_not_applied(Mode::Append, false);
        assert!(append
            .iter()
            .any(|l| l.starts_with("  | !  0.5.8 is available")));

        let (plain, exit) = available_not_applied(Mode::Plain, false);
        assert_eq!(exit, 7);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/1] Checked for updates - 0.5.7 -> 0.5.8",
                "      Not applied: no terminal to ask. To update unattended, run: openlatch update --yes",
                "Automatic updates: on - last checked 4h ago",
                r#"result=available from=0.5.7 to=0.5.8 severity=normal hint="openlatch update --yes" exit=7"#,
            ]
        );

        let (plain, _) = available_not_applied(Mode::Plain, true);
        assert_eq!(plain[2], "      To install it, run: openlatch update --yes");
        let (live, _) = available_not_applied(Mode::Live, true);
        assert!(live
            .iter()
            .any(|l| l.contains("When ready     Run openlatch update.")));
    }

    /// "Not now" to a critical release. Only a terminal is ever asked; plain
    /// mode shows what the same answer would write.
    fn declined(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 2, |_| {
            let check = available(Severity::Critical);
            let release =
                close_check(check, "0.5.7", "https://registry.npmjs.org").expect("a release");
            let (title, _, _) = question(&release, true);
            ui::stage_named("Update", &title, &title);
            answered(false);
            finish(&Outcome::Declined { release }, &auto_on(), now())
        })
    }

    #[test]
    fn declined_in_every_mode() {
        let (live, exit) = declined(Mode::Live);
        assert_eq!(exit, 7);
        assert_eq!(
            live[..8],
            [
                "┌  Updating OpenLatch",
                "│",
                "◇  Checked for updates · 0.5.7 → 0.5.8 · security fix",
                "│",
                "◇  Update to 0.5.8 · not now",
                "│",
                "└  Nothing changed.",
                "",
            ]
        );
        assert!(live[10].starts_with("  │ !  Not updated · still on 0.5.7"));
        let card = live.join("\n");
        assert!(card.contains("    Available      0.5.8 · security fix"));
        assert!(card.contains("    When ready     Run openlatch update again."));

        let (append, _) = declined(Mode::Append);
        assert!(append.contains(&"+  Update to 0.5.8 - not now".to_string()));
        assert!(append
            .iter()
            .any(|l| l.starts_with("  | !  Not updated - still on 0.5.7")));

        let (plain, _) = declined(Mode::Plain);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/2] Checked for updates - 0.5.7 -> 0.5.8 - security fix",
                "[2/2] Update to 0.5.8 - not now",
                "Automatic updates: on - last checked 4h ago",
                "result=declined from=0.5.7 to=0.5.8 exit=7",
            ]
        );
    }

    /// The registry did not answer: nothing changed, the agents stay protected.
    fn check_failed(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 1, |_| {
            let check = CheckResult::Failed {
                reason: "manifest fetch: send: operation timed out".into(),
            };
            let outcome = close_check(check, "0.5.7", "https://registry.npmjs.org")
                .expect_err("nothing to install");
            finish(&outcome, &auto_on(), now())
        })
    }

    #[test]
    fn check_failed_in_every_mode() {
        let (live, exit) = check_failed(Mode::Live);
        assert_eq!(exit, 7);
        assert_eq!(
            live[..6],
            [
                "┌  Updating OpenLatch",
                "│",
                "✗  Check failed · couldn't reach the update server",
                "│",
                "└  Stopped.",
                "",
            ]
        );
        assert!(live[8].starts_with("  │ !  Couldn't check for updates"));
        let card = live.join("\n");
        // One column too wide for the value column: the tail takes its own line.
        assert!(card.contains("    Still running  0.5.7 "), "{card}");
        assert!(card.contains("                    · nothing changed, your agents stay protected"));
        assert!(card.contains("    Why            registry.npmjs.org didn't answer"));
        assert!(card.contains("    Try            Check the connection or proxy, then run"));

        let (append, _) = check_failed(Mode::Append);
        assert!(append.contains(&"x  Check failed - couldn't reach the update server".into()));

        let (plain, _) = check_failed(Mode::Plain);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/1] Check failed - couldn't reach the update server",
                "Still running 0.5.7 - nothing changed. registry.npmjs.org didn't answer.",
                "Automatic updates: on - last checked 4h ago",
                "result=check_failed version=0.5.7 reason=registry-unreachable exit=7",
            ]
        );
    }

    /// OL-1504: the signature does not verify; the staging is discarded.
    fn failed_verify(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 6, |t0| {
            let mut apply = check_and_download(t0, Severity::Normal, false);
            let outcome = apply.fail(FailedAt::Stage(ApplyStage::Verify), ms(t0, 3500));
            finish(&outcome, &auto_on(), now())
        })
    }

    #[test]
    fn failed_verify_in_every_mode() {
        let (live, exit) = failed_verify(Mode::Live);
        assert_eq!(exit, 1);
        assert_eq!(
            live[..10],
            [
                "┌  Updating OpenLatch",
                "│",
                "◇  Checked for updates · 0.5.7 → 0.5.8",
                "│",
                "◇  Downloaded · 8.4 MB in 2.9s",
                "│",
                "✗  Verify failed · the signature doesn't match OpenLatch's release key",
                "│",
                "└  Stopped.",
                "",
            ]
        );
        assert!(live[12].starts_with("  │ ✗  Update stopped: the download didn't verify"));
        let card = live.join("\n");
        assert!(card.contains("    Still running  0.5.7 · nothing was changed"));
        assert!(card.contains("    What happened  The signature doesn't match OpenLatch's key."));
        assert!(card.contains("                   OL-1504"));
        assert!(card.contains("    Try            Run openlatch update again. If it fails twice,"));

        let (append, _) = failed_verify(Mode::Append);
        assert!(append.contains(
            &"x  Verify failed - the signature doesn't match OpenLatch's release key".into()
        ));

        let (plain, _) = failed_verify(Mode::Plain);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/6] Checked for updates - 0.5.7 -> 0.5.8",
                "[2/6] Downloading 8.4 MB...",
                "[2/6] Downloaded - 8.4 MB in 2.9s",
                "[3/6] Verifying the signature - failed",
                "      The signature doesn't match OpenLatch's release key (OL-1504)",
                "Still running 0.5.7 - nothing was changed. The signature doesn't match (OL-1504).",
                "Automatic updates: on - last checked 4h ago",
                "result=failed step=verify code=OL-1504 version=0.5.7 exit=1",
            ]
        );
    }

    /// The new daemon never settles and the old version comes back.
    fn rolled_back(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 6, |t0| {
            let mut apply = check_and_download(t0, Severity::Normal, false);
            install_and_restart(&mut apply, t0);
            let outcome = apply.rolled_back();
            finish(&outcome, &auto_on(), now())
        })
    }

    #[test]
    fn rolled_back_in_every_mode() {
        let (live, exit) = rolled_back(Mode::Live);
        assert_eq!(exit, 1);
        let at = live
            .iter()
            .position(|l| l == "✗  Restart failed · 0.5.8 didn't come back")
            .unwrap_or_else(|| panic!("{live:#?}"));
        assert_eq!(
            live[at + 1..at + 6],
            [
                "│",
                "◇  Rolled back · 0.5.7 restored and running",
                "│",
                "└  Stopped.",
                "",
            ]
        );
        assert!(live[at + 8].starts_with("  │ ✗  0.5.8 didn't start, so 0.5.7 is back"));
        let card = live.join("\n");
        assert!(
            card.contains("    Running        0.5.7 · restored automatically, agents protected")
        );
        assert!(card.contains("    What happened  The 0.5.8 service stopped right after starting."));
        assert!(card.contains("                   OL-1502"));
        assert!(card.contains("    Try            Run openlatch doctor, then share the log below."));

        let (append, _) = rolled_back(Mode::Append);
        assert!(append.contains(&"x  Restart failed - 0.5.8 didn't come back".into()));
        assert!(append.contains(&"+  Rolled back - 0.5.7 restored and running".into()));

        let (plain, _) = rolled_back(Mode::Plain);
        assert_eq!(
            plain[4..],
            [
                "[3/6] Verified - signed by OpenLatch",
                "[4/6] Installed - 0.5.7 kept as a backup",
                "[5/6] Restarting the background service...",
                "[5/6] Restarting the background service - failed",
                "      0.5.8 didn't come back (OL-1502)",
                "[6/6] Rolled back - 0.5.7 restored and running",
                "Running 0.5.7 again - 0.5.8 stopped right after starting and was rolled back (OL-1502).",
                "Automatic updates: on - last checked 4h ago",
                "result=rolled_back from=0.5.8 to=0.5.7 code=OL-1502 exit=1",
            ]
        );
    }

    /// No daemon: four stages, no restart, and no service running to put the
    /// new version in effect. Automatic updates are off here too.
    fn no_daemon_updated(mode: Mode) -> (Vec<String>, i32) {
        drive(mode, 4, |t0| {
            let mut apply = check_and_download(t0, Severity::Normal, false);
            apply.reach(Step::of(ApplyStage::Swap), ms(t0, 4000));
            apply.finish(ms(t0, 4200));
            let outcome = Outcome::Updated {
                release: apply.release.clone(),
                service: Service::NotRunning,
            };
            let auto = AutoUpdate {
                on: false,
                ..auto_on()
            };
            finish(&outcome, &auto, now())
        })
    }

    #[test]
    fn no_daemon_updated_in_every_mode() {
        let (live, exit) = no_daemon_updated(Mode::Live);
        assert_eq!(exit, 7);
        assert!(live.contains(&"◇  Installed · 0.5.7 kept as a backup".to_string()));
        assert!(!live.iter().any(|l| l.contains("Restart")), "{live:#?}");
        assert!(live.contains(&"└  Done.".to_string()));
        assert!(live
            .iter()
            .any(|l| l.starts_with("  │ !  OpenLatch 0.5.8 is installed")));
        let n = live.len();
        assert_eq!(
            live[n - 2..],
            [
                "  ! The background service isn't running · start it: openlatch start",
                "  ! Automatic updates: off · turn on: [update] auto_update = true",
            ]
        );

        let (append, _) = no_daemon_updated(Mode::Append);
        assert!(append.contains(&"+  Installed - 0.5.7 kept as a backup".into()));
        assert!(append
            .iter()
            .any(|l| l == "  ! The background service isn't running - start it: openlatch start"));

        let (plain, exit) = no_daemon_updated(Mode::Plain);
        assert_eq!(exit, 7);
        assert_eq!(
            plain,
            [
                "Updating OpenLatch",
                "[1/4] Checked for updates - 0.5.7 -> 0.5.8",
                "[2/4] Downloading 8.4 MB...",
                "[2/4] Downloaded - 8.4 MB in 2.9s",
                "[3/4] Verified - signed by OpenLatch",
                "[4/4] Installed - 0.5.7 kept as a backup",
                "Installed 0.5.8 - the background service isn't running. Start it: openlatch start",
                "! Automatic updates: off - turn on: [update] auto_update = true",
                r#"result=updated from=0.5.7 to=0.5.8 hint="openlatch start" exit=7"#,
            ]
        );
    }

    /// A daemon that reports no byte counts keeps the plain spinner: nothing
    /// is metered, and the stage still closes with how long it took.
    #[test]
    fn a_daemon_without_byte_counts_draws_no_meter() {
        let (append, _) = drive(Mode::Append, 6, |t0| {
            let mut release = release(Severity::Normal);
            release.size = None;
            let mut apply = Apply::new(release, t0);
            apply.reach(Step::Download, t0);
            apply.bytes(None, None, ms(t0, 500));
            apply.reach(Step::Verify, ms(t0, 2000));
            0
        });
        assert_eq!(
            append[4..],
            [
                "|",
                ">  Downloading 0.5.8...",
                "+  Downloaded - in 2.0s",
                "|",
                ">  Verifying the signature...",
            ]
        );
    }
}

/// The pieces of the flow that need no rail: stage mapping, the question,
/// the exit code, the meter's text.
#[cfg(test)]
mod flow_tests {
    use super::*;
    use clap::Parser;

    fn release(severity: Severity, size: Option<u64>) -> Release {
        Release {
            from: "0.5.7".into(),
            to: "0.5.8".into(),
            severity,
            size,
        }
    }

    #[test]
    fn pipeline_stages_map_onto_the_rail() {
        use ApplyStage::*;
        let cases = [
            (Check, Step::Download),
            (Download, Step::Download),
            (Extract, Step::Verify),
            (Verify, Step::Verify),
            (Sanity, Step::Verify),
            (Reader, Step::Verify),
            (Swap, Step::Install),
            (Drain, Step::Restart),
            (Restart, Step::Restart),
            (Healthz, Step::Confirm),
        ];
        for (stage, step) in cases {
            assert_eq!(Step::of(stage), step, "{stage:?}");
            assert_eq!(apply_stage(stage.as_str()), Some(stage));
        }
        assert_eq!(apply_stage("some_future_stage"), None);
    }

    #[test]
    fn the_question_follows_severity_size_and_daemon() {
        let (title, q, line) = question(&release(Severity::Normal, Some(8_806_432)), true);
        assert_eq!(title, "Update to 0.5.8");
        assert_eq!(q, "Update to 0.5.8 now?");
        assert_eq!(
            line.as_deref(),
            Some("About 8.4 MB · the background service restarts for a few seconds.")
        );
        let (_, q, line) = question(&release(Severity::Critical, Some(8_806_432)), false);
        assert_eq!(q, "0.5.8 fixes a security issue. Update now?");
        assert_eq!(line.as_deref(), Some("About 8.4 MB."));
        let (_, _, line) = question(&release(Severity::Normal, None), false);
        assert_eq!(line, None);
    }

    #[test]
    fn exit_codes_follow_the_health_convention() {
        let r = || release(Severity::Normal, None);
        let failed = |at| Outcome::Failed {
            release: r(),
            at,
            step: Step::Verify,
        };
        let updated = |service| Outcome::Updated {
            release: r(),
            service,
        };
        let cases = [
            (
                Outcome::UpToDate {
                    version: "0.5.8".into(),
                    stale: None,
                },
                0,
            ),
            (
                Outcome::UpToDate {
                    version: "0.5.8".into(),
                    stale: Some("0.5.7".into()),
                },
                7,
            ),
            (updated(Service::Running), 0),
            (updated(Service::NotRunning), 7),
            (updated(Service::Stale("0.5.7".into())), 7),
            (
                Outcome::Available {
                    release: r(),
                    check_only: true,
                },
                7,
            ),
            (Outcome::Declined { release: r() }, 7),
            (
                Outcome::CheckFailed {
                    from: "0.5.7".into(),
                    host: "registry.npmjs.org".into(),
                    unreachable: true,
                },
                7,
            ),
            (failed(FailedAt::Stage(ApplyStage::Verify)), 1),
            (failed(FailedAt::NotBack), 1),
            (Outcome::RolledBack { release: r() }, 1),
        ];
        for (outcome, exit) in cases {
            assert_eq!(outcome.exit_code(), exit, "{outcome:?}");
        }
    }

    /// Every failure names its stage and a code the registry defines; only
    /// the ones before the swap claim nothing was changed.
    #[test]
    fn failures_name_their_stage_and_code() {
        let r = release(Severity::Normal, None);
        let why = |at: FailedAt| at.why(&r, None);
        let verify = why(FailedAt::Stage(ApplyStage::Verify));
        assert_eq!(
            (verify.step, verify.code, verify.unchanged),
            (Step::Verify, "OL-1504", true)
        );
        let reader = why(FailedAt::Stage(ApplyStage::Reader));
        assert_eq!((reader.step, reader.code), (Step::Verify, "OL-1216"));
        let swap = why(FailedAt::Stage(ApplyStage::Swap));
        assert_eq!((swap.step, swap.unchanged), (Step::Install, false));
        let gone = why(FailedAt::NotBack);
        assert_eq!((gone.step, gone.code), (Step::Restart, "OL-1502"));
        assert_eq!(gone.line, "0.5.8 didn't come back");
        // A failure for a stage already passed lands on the running one.
        let late = FailedAt::Stage(ApplyStage::Download).why(&r, Some(Step::Install));
        assert_eq!(late.step, Step::Install);
        assert_eq!(
            FailedAt::Stalled.why(&r, Some(Step::Verify)).step,
            Step::Verify
        );
    }

    #[test]
    fn the_meter_reads_bytes_speed_and_time_left() {
        let mib = 1_048_576;
        assert_eq!(
            download_tail(5 * mib, Some(8 * mib), Some(3.0 * mib as f64)),
            (Some(0.625), "5.0 / 8.0 MB · 3.0 MB/s · 1s left".to_string())
        );
        assert_eq!(
            download_tail(mib, Some(300 * mib), Some(mib as f64)),
            (
                Some(1.0 / 300.0),
                "1.0 / 300.0 MB · 1.0 MB/s · 5m left".to_string()
            )
        );
        assert_eq!(download_tail(mib, None, None), (None, "1.0 MB".to_string()));
        assert_eq!(
            download_tail(0, Some(0), None),
            (None, "0.0 MB".to_string())
        );

        let t0 = Instant::now();
        let mut rate = Rate::default();
        rate.sample(t0, 0);
        rate.sample(t0 + Duration::from_millis(100), 10);
        assert_eq!(rate.bytes_per_sec, None, "too soon to tell");
        rate.sample(t0 + Duration::from_secs(1), 1000);
        assert_eq!(rate.bytes_per_sec, Some(1000.0));
        rate.sample(t0 + Duration::from_secs(2), 1500);
        assert_eq!(rate.bytes_per_sec, Some(0.7 * 1000.0 + 0.3 * 500.0));
    }

    #[test]
    fn automatic_updates_line() {
        let now: chrono::DateTime<chrono::Utc> = "2026-09-23T12:00:00Z".parse().unwrap();
        let on = AutoUpdate {
            on: true,
            by_env: false,
            last_check: None,
        };
        assert_eq!(on.line(now), (false, "Automatic updates: on".to_string()));
        let checked = AutoUpdate {
            last_check: Some("2026-09-23T11:48:00Z".into()),
            ..on.clone()
        };
        assert_eq!(
            checked.line(now).1,
            "Automatic updates: on · last checked 12m ago"
        );
        let off = AutoUpdate {
            on: false,
            ..on.clone()
        };
        assert_eq!(
            off.line(now),
            (
                true,
                "Automatic updates: off · turn on: `[update] auto_update = true`".to_string()
            )
        );
        let off_by_env = AutoUpdate {
            by_env: true,
            ..off
        };
        assert_eq!(
            off_by_env.plain_line(now),
            "! Automatic updates: off · turn on: OPENLATCH_AUTO_UPDATE=true"
        );
        assert_eq!(ago(chrono::Duration::seconds(5)), "just now");
        assert_eq!(ago(chrono::Duration::hours(50)), "2d ago");
    }

    #[test]
    fn daemon_rejections_keep_their_exit_codes() {
        use reqwest::StatusCode;
        let up = rejection(
            StatusCode::CONFLICT,
            &json!({"idempotent": true, "current": "0.5.8"}),
            "0.5.7",
        );
        assert!(matches!(up, Rejection::UpToDate(v) if v == "0.5.8"));
        let exit = |status, body| match rejection(status, &body, "0.5.7") {
            Rejection::Refused(e, exit) => (e.code, exit),
            Rejection::UpToDate(_) => ("", 0),
        };
        assert_eq!(exit(StatusCode::CONFLICT, json!({})), ("OL-1505", 5));
        assert_eq!(
            exit(StatusCode::SERVICE_UNAVAILABLE, json!({})),
            ("OL-1502", 1)
        );
        assert_eq!(exit(StatusCode::BAD_GATEWAY, json!({})), ("OL-1504", 1));
    }

    #[test]
    fn apply_is_a_hidden_alias_of_yes() {
        let parse = |args: &[&str]| {
            let argv = ["openlatch", "update"].iter().chain(args).copied();
            let cli = crate::cli::Cli::try_parse_from(argv).expect("parses");
            match cli.command {
                Some(crate::cli::Commands::Update(a)) => a,
                _ => panic!("not update"),
            }
        };
        assert!(!parse(&[]).applies());
        assert!(parse(&["--yes"]).applies());
        assert!(parse(&["-y"]).applies());
        assert!(parse(&["--apply"]).applies());
        assert!(parse(&["--apply", "--yes"]).applies(), "existing scripts");
        assert!(!parse(&["--check"]).applies());
        assert!(!parse(&["--check", "--yes"]).applies());
        let mut cli = <crate::cli::Cli as clap::CommandFactory>::command();
        let help = cli
            .find_subcommand_mut("update")
            .expect("update")
            .render_long_help()
            .to_string();
        assert!(
            help.contains("--yes") && !help.contains("--apply"),
            "{help}"
        );
    }

    #[test]
    fn versions_match_exactly_up_to_a_build_suffix() {
        assert!(is_version("0.5.8", "0.5.8"));
        assert!(is_version("0.5.8+abc123", "0.5.8"));
        assert!(
            !is_version("0.5.8-rc.1", "0.5.8"),
            "a pre-release is not the release"
        );
        assert!(!is_version("0.5.9-dev.12+g73ec01c", "0.5.9"));
        assert!(!is_version("0.5.10", "0.5.1"), "0.5.1 → 0.5.10");
        assert!(!is_version("0.5.1", "0.5.10"));
        assert!(!is_version("0.5.7", "0.5.8"));
    }

    #[test]
    fn host_of_the_registry() {
        assert_eq!(host("https://registry.npmjs.org"), "registry.npmjs.org");
        assert_eq!(host("http://127.0.0.1:4873/npm/"), "127.0.0.1:4873");
        assert_eq!(host("registry.local"), "registry.local");
    }
}

/// The daemon path against a stand-in daemon: scripted `/admin/update`,
/// `/admin/update/status` and `/health` answers on an ephemeral loopback port,
/// on a shrunken clock.
#[cfg(test)]
mod daemon_tests {
    use super::*;
    use crate::cli::ui::{Rail, INSTALL_LOCK};
    use std::collections::{HashMap, VecDeque};
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::sync::Mutex;

    /// One scripted answer.
    #[derive(Clone)]
    enum Reply {
        Json(u16, serde_json::Value),
        /// Read the request, then close without answering: a daemon going down.
        Down,
    }

    use Reply::Down;

    fn ok(body: serde_json::Value) -> Reply {
        Reply::Json(200, body)
    }

    fn health(version: &str) -> Reply {
        ok(json!({"status": "ok", "version": version}))
    }

    fn applying(stage: &str) -> Reply {
        ok(json!({"status": "in_progress", "stage": stage, "bytes_done": 10, "bytes_total": 20}))
    }

    fn accepted(from: &str) -> Reply {
        Reply::Json(202, json!({"started": true, "from": from, "to": "0.5.8"}))
    }

    const FAST: Timing = Timing {
        poll: Duration::from_millis(5),
        request: Duration::from_secs(2),
        back_within: Duration::from_secs(3),
        stall: Duration::from_secs(5),
        misses: 3,
    };

    /// Serve `routes` (path → answers, taken in order, the last one repeating)
    /// until the test process ends. Returns the port.
    fn serve(routes: Vec<(&'static str, Vec<Reply>)>) -> u16 {
        let listener = TcpListener::bind("127.0.0.1:0").expect("binds");
        let port = listener.local_addr().expect("addr").port();
        let scripts: Mutex<HashMap<&str, VecDeque<Reply>>> = Mutex::new(
            routes
                .into_iter()
                .map(|(path, replies)| (path, replies.into()))
                .collect(),
        );
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { continue };
                let path = read_request(&mut stream);
                let reply = {
                    let mut scripts = scripts.lock().unwrap();
                    let script = scripts.get_mut(path.as_str());
                    match script {
                        Some(q) if q.len() > 1 => q.pop_front(),
                        Some(q) => q.front().cloned(),
                        None => None,
                    }
                };
                match reply {
                    Some(Reply::Json(code, body)) => {
                        let body = body.to_string();
                        let _ = write!(
                            stream,
                            "HTTP/1.1 {code} X\r\nContent-Type: application/json\r\n\
                             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
                            body.len()
                        );
                    }
                    Some(Down) | None => {}
                }
            }
        });
        port
    }

    /// Read the whole request (headers, then any body) before answering, and
    /// return its path.
    fn read_request(stream: &mut TcpStream) -> String {
        let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
        let mut buf = Vec::new();
        let mut chunk = [0u8; 1024];
        let end = loop {
            if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                break end + 4;
            }
            match stream.read(&mut chunk) {
                Ok(0) | Err(_) => return String::new(),
                Ok(n) => buf.extend_from_slice(&chunk[..n]),
            }
        };
        let head = String::from_utf8_lossy(&buf[..end]).to_string();
        let length = head
            .lines()
            .find_map(|l| {
                let (k, v) = l.split_once(':')?;
                k.eq_ignore_ascii_case("content-length")
                    .then(|| v.trim().parse::<usize>().ok())?
            })
            .unwrap_or(0);
        while buf.len() < end + length {
            match stream.read(&mut chunk) {
                Ok(0) | Err(_) => break,
                Ok(n) => buf.extend_from_slice(&chunk[..n]),
            }
        }
        head.split_whitespace().nth(1).unwrap_or("").to_string()
    }

    fn release() -> Release {
        Release {
            from: "0.5.7".into(),
            to: "0.5.8".into(),
            severity: Severity::Normal,
            size: Some(20),
        }
    }

    /// Run `f` on a plain rail; returns its outcome and the screen.
    fn on_rail<T>(f: impl std::future::Future<Output = T>) -> (T, Vec<String>) {
        let _l = INSTALL_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (rail, screen) = Rail::buffer(Caps::new(Mode::Plain, false, false, 80), 6);
        let out = {
            let _guard = ui::install_rail(rail).expect("installs");
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("runtime")
                .block_on(f)
        };
        let lines = screen.lock().unwrap().clone();
        (out, lines)
    }

    fn apply_through(routes: Vec<(&'static str, Vec<Reply>)>) -> (Outcome, Vec<String>) {
        let port = serve(routes);
        let (out, lines) = on_rail(via_daemon(release(), port, "token", false, FAST));
        match out {
            Ok(outcome) => (outcome, lines),
            Err(stop) => panic!("stopped: {} {lines:#?}", stop.error.message),
        }
    }

    /// One poll where the daemon answered nothing, mid-download, then it
    /// carries on: no rollback, the update lands. `from` is the daemon's.
    #[test]
    fn a_missed_poll_mid_download_is_not_a_restart() {
        let (outcome, lines) = apply_through(vec![
            ("/admin/update", vec![accepted("0.5.6")]),
            (
                "/admin/update/status",
                vec![
                    applying("download"),
                    Down,
                    applying("download"),
                    applying("verify"),
                    applying("swap"),
                    applying("drain"),
                    Down,
                    ok(json!({"status": "completed"})),
                ],
            ),
            ("/health", vec![Down, Down, Down, health("0.5.8")]),
        ]);
        let Outcome::Updated { release, service } = outcome else {
            panic!("{outcome:?} {lines:#?}");
        };
        assert_eq!(service, Service::Running);
        assert_eq!(release.from, "0.5.6", "the daemon's own version");
        assert!(
            lines.iter().any(|l| l == "[5/6] Confirmed - running 0.5.8"),
            "{lines:#?}"
        );
        assert!(
            !lines.iter().any(|l| l.contains("Rolled back")),
            "{lines:#?}"
        );
    }

    /// Silent long enough to count as down before any swap, then answering
    /// on the old version while its status still reads `download`: the same
    /// process, still applying. Follow it again.
    #[test]
    fn the_old_version_still_applying_is_resumed_not_rolled_back() {
        let (outcome, lines) = apply_through(vec![
            ("/admin/update", vec![accepted("0.5.7")]),
            (
                "/admin/update/status",
                vec![
                    applying("download"),
                    Down,
                    Down,
                    Down,
                    applying("download"),
                    applying("swap"),
                    applying("drain"),
                    Down,
                    ok(json!({"status": "completed"})),
                ],
            ),
            (
                "/health",
                vec![
                    Down,
                    Down,
                    Down,
                    health("0.5.7"),
                    Down,
                    Down,
                    health("0.5.8"),
                ],
            ),
        ]);
        assert!(
            matches!(outcome, Outcome::Updated { .. }),
            "{outcome:?} {lines:#?}"
        );
        assert!(
            !lines.iter().any(|l| l.contains("Rolled back")),
            "{lines:#?}"
        );
    }

    /// Down after the drain, back on the old version and idle: rolled back.
    #[test]
    fn idle_on_the_old_version_after_the_restart_is_a_rollback() {
        let (outcome, lines) = apply_through(vec![
            ("/admin/update", vec![accepted("0.5.7")]),
            (
                "/admin/update/status",
                vec![
                    applying("download"),
                    applying("swap"),
                    applying("drain"),
                    Down,
                    ok(json!({"status": "idle"})),
                ],
            ),
            ("/health", vec![Down, Down, health("0.5.7")]),
        ]);
        assert!(
            matches!(outcome, Outcome::RolledBack { .. }),
            "{outcome:?} {lines:#?}"
        );
        assert!(lines.contains(&"      0.5.8 didn't come back (OL-1502)".to_string()));
        assert!(lines
            .iter()
            .any(|l| l.ends_with("] Rolled back - 0.5.7 restored and running")));
    }

    /// A rollback the run never saw go down: the old daemon answers every
    /// poll, idle. Read as restarted, and the version decides: rolled back.
    #[test]
    fn idle_without_a_drop_is_a_restart_the_version_decides() {
        let started = Instant::now();
        let (outcome, lines) = apply_through(vec![
            ("/admin/update", vec![accepted("0.5.7")]),
            (
                "/admin/update/status",
                vec![applying("download"), ok(json!({"status": "idle"}))],
            ),
            ("/health", vec![health("0.5.7")]),
        ]);
        assert!(
            matches!(outcome, Outcome::RolledBack { .. }),
            "{outcome:?} {lines:#?}"
        );
        assert!(started.elapsed() < FAST.back_within, "not a timeout");
    }

    /// `completed` with nothing swapped and the old version serving: the
    /// daemon found itself up to date. Said at once, not after 60 s.
    #[test]
    fn completed_without_a_swap_is_up_to_date() {
        let started = Instant::now();
        let (outcome, lines) = apply_through(vec![
            ("/admin/update", vec![accepted("0.5.7")]),
            (
                "/admin/update/status",
                vec![ok(json!({"status": "completed", "stage": null}))],
            ),
            ("/health", vec![health("0.5.7")]),
        ]);
        assert!(
            matches!(&outcome, Outcome::UpToDate { version, stale: None } if version == "0.5.7"),
            "{outcome:?} {lines:#?}"
        );
        assert!(started.elapsed() < FAST.back_within);
    }

    /// A build between releases reports `0.5.9-dev.12+g73ec01c` on `/health`
    /// while its manifest says `0.5.8`: the daemon running that same build is
    /// not stale, and one on another build is.
    #[test]
    fn a_dev_build_compares_the_daemon_against_its_own_identity() {
        let dev = "0.5.9-dev.12+g73ec01c";
        let port = serve(vec![("/health", vec![health(dev)])]);
        let (outcome, _) = on_rail(up_to_date("0.5.8".into(), dev, port));
        assert!(
            matches!(&outcome, Outcome::UpToDate { stale: None, .. }),
            "{outcome:?}"
        );

        let port = serve(vec![("/health", vec![health("0.5.9-dev.11+g0a1b2c3")])]);
        let (outcome, _) = on_rail(up_to_date("0.5.8".into(), dev, port));
        assert!(
            matches!(&outcome, Outcome::UpToDate { stale: Some(v), .. } if v == "0.5.9-dev.11+g0a1b2c3"),
            "{outcome:?}"
        );

        // After the restart, the dev daemon is still the one the update
        // started from, whatever manifest version it said it was.
        let r = release();
        assert!(serves_from(dev, &r, dev));
        assert!(serves_from("0.5.7", &r, dev));
        assert!(!serves_from("0.5.9-dev.11+g0a1b2c3", &r, dev));
        assert!(!serves_from("0.5.8", &r, dev));
    }

    /// Up to date here, but the background service still runs an older build:
    /// not green. A service on this version, or none, is.
    #[test]
    fn up_to_date_with_a_stale_daemon_needs_a_restart() {
        let port = serve(vec![("/health", vec![health("0.5.7")])]);
        let (outcome, lines) = on_rail(async {
            let outcome = up_to_date("0.5.8".into(), "0.5.8", port).await;
            let exit = finish(&outcome, &AutoUpdate::default(), chrono::Utc::now());
            (outcome, exit)
        });
        let (outcome, exit) = outcome;
        assert!(
            matches!(&outcome, Outcome::UpToDate { stale: Some(v), .. } if v == "0.5.7"),
            "{outcome:?}"
        );
        assert_eq!(exit, 7);
        assert_eq!(
            lines[lines.len() - 3..],
            [
                "Installed 0.5.8 - the background service is still on 0.5.7. Run: openlatch restart",
                "! Automatic updates: off - turn on: [update] auto_update = true",
                r#"result=up_to_date version=0.5.8 hint="openlatch restart" exit=7"#,
            ]
        );
        let (card, warnings) = outcome.card(&AutoUpdate::default(), chrono::Utc::now(), None);
        assert_eq!(card.verdict, ui::Verdict::NeedsAttention);
        assert_eq!(card.title, "OpenLatch 0.5.8 is installed");
        assert_eq!(
            warnings[0],
            "The background service is still on 0.5.7 · restart it: `openlatch restart`"
        );

        let current = serve(vec![("/health", vec![health("0.5.8")])]);
        let ((same, none), _) = on_rail(async {
            let closed = TcpListener::bind("127.0.0.1:0")
                .and_then(|l| l.local_addr())
                .expect("a free port")
                .port();
            (
                up_to_date("0.5.8".into(), "0.5.8", current).await,
                up_to_date("0.5.8".into(), "0.5.8", closed).await,
            )
        });
        for outcome in [same, none] {
            assert!(
                matches!(outcome, Outcome::UpToDate { stale: None, .. }),
                "{outcome:?}"
            );
            assert_eq!(outcome.exit_code(), 0);
        }
    }

    /// A restart the status never showed: the daemon drops mid-poll and the
    /// rail only reaches Restart when the new version answers. The stage is
    /// still timed from the drop, not from that answer.
    #[test]
    fn the_restart_is_timed_from_the_drop() {
        let mut health_script = vec![Down; 3 + 40];
        health_script.push(health("0.5.8"));
        let (outcome, lines) = apply_through(vec![
            ("/admin/update", vec![accepted("0.5.7")]),
            (
                "/admin/update/status",
                vec![
                    applying("download"),
                    Down,
                    Down,
                    Down,
                    ok(json!({"status": "completed"})),
                ],
            ),
            ("/health", health_script),
        ]);
        assert!(
            matches!(outcome, Outcome::Updated { .. }),
            "{outcome:?} {lines:#?}"
        );
        let back = lines
            .iter()
            .find_map(|l| {
                l.split("Restarted the background service - back in ")
                    .nth(1)
            })
            .unwrap_or_else(|| panic!("{lines:#?}"));
        let secs: f64 = back.trim_end_matches('s').parse().expect("seconds");
        assert!(secs >= 0.1, "timed from the drop: {back} {lines:#?}");
    }

    /// Nothing listening costs a connect timeout, not Windows' SYN retries.
    #[test]
    fn no_daemon_is_found_fast() {
        let closed = TcpListener::bind("127.0.0.1:0")
            .and_then(|l| l.local_addr())
            .expect("a free port")
            .port();
        let started = Instant::now();
        let (outcome, _) = on_rail(up_to_date("0.5.8".into(), "0.5.8", closed));
        assert!(matches!(outcome, Outcome::UpToDate { stale: None, .. }));
        assert!(
            started.elapsed() < Duration::from_millis(1500),
            "{:?}",
            started.elapsed()
        );
    }

    /// A refused `cargo install` binary still closes a log with its line.
    #[test]
    fn a_refusal_before_the_check_writes_its_result_line() {
        let (exit, lines) = on_rail(async {
            ui::intro("Updating OpenLatch");
            stop(&Stop::new(cargo_refusal(CARGO_SUGGESTION), 5))
        });
        assert_eq!(exit, 5);
        assert_eq!(lines[0], "Updating OpenLatch");
        assert!(lines[1].ends_with("(OL-1505)"), "{lines:#?}");
        assert_eq!(
            lines.last().map(String::as_str),
            Some("result=failed code=OL-1505 exit=5")
        );
    }
}