openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
//! Update mechanism.
//!
//! Currently scopes:
//!
//! - **Existing**: async npm-registry version check
//!   ([`check_for_update`]). Surfaces "newer version available" hints
//!   at daemon startup without applying anything.
//! - **Phase 1**: trust root + verifier ([`verify_with_any_trusted_key`]),
//!   sanity check ([`sanity_check_version`]), hook resolver, atomic swap
//!   ([`perform_swap`]).
//! - **Phase 2** (this module): manifest fetch + semver compare
//!   ([`check`]), platform-tarball download + SHA-512 SRI verify
//!   ([`download_tarball`]), tar extraction with full hardening
//!   ([`extract_to_staging`]), in-process apply pipeline
//!   ([`apply_local`]), install-method detection
//!   ([`detect_install_method`]), daemon-side restart helpers
//!   ([`write_sentinel`], [`read_sentinel`], [`restart_into_new_binary`]).
//!
//! See `.claude/rules/auto-update.md` for the trust boundary +
//! invariants governing any change in this module.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// ---------------------------------------------------------------------------
// npm-registry version check (pre-existing)
// ---------------------------------------------------------------------------

/// Check whether a newer version of openlatch is available on the npm registry.
///
/// Returns `Some(latest_version)` if `latest_version != current_version`, or
/// `None` if the current version is up-to-date or the check could not be completed.
///
/// All errors are silently swallowed — the update check must never affect
/// daemon startup or normal operation (T-02-14: DoS mitigation via timeout +
/// silent failure).
pub async fn check_for_update(current_version: &str) -> Option<String> {
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .build()
        .ok()?;

    let resp = client
        .get("https://registry.npmjs.org/@openlatch%2Fclient/latest")
        .header("Accept", "application/json")
        .send()
        .await
        .ok()?;

    if !resp.status().is_success() {
        return None;
    }

    let body: serde_json::Value = resp.json().await.ok()?;

    // T-02-13: Response is untrusted; only read the `version` string field.
    let latest = body.get("version")?.as_str()?;

    (latest != current_version).then_some(latest.to_string())
}

// ---------------------------------------------------------------------------
// Trusted-key bake (Phase 1 spike)
// ---------------------------------------------------------------------------

const TRUSTED_KEYS_FILE: &str = include_str!("../../signing/openlatch.pub");

/// Returns the list of trusted minisign public keys (base64) baked into the
/// binary at compile time.
///
/// In test builds (or with the `insecure-test-keys` cargo feature), the
/// `OPENLATCH_TRUSTED_KEYS` env var (comma-separated) overrides the baked
/// list. The feature is OFF in release builds — disabling a release-build
/// signing bypass via env var.
pub fn trusted_keys() -> Vec<String> {
    #[cfg(any(test, feature = "insecure-test-keys"))]
    if let Ok(test_keys) = std::env::var("OPENLATCH_TRUSTED_KEYS") {
        if !test_keys.trim().is_empty() {
            return test_keys
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
        }
    }
    parse_trusted_keys(TRUSTED_KEYS_FILE)
}

fn parse_trusted_keys(input: &str) -> Vec<String> {
    input
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .map(String::from)
        .take(3)
        .collect()
}

// ---------------------------------------------------------------------------
// Signature verification (multi-key — accept ANY trusted match)
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum VerifyError {
    #[error("malformed minisign artefact: {0}")]
    Malformed(String),

    #[error("no trusted public key matched the signature")]
    NoTrustedKeyMatched,

    #[error("io error reading signed binary or signature: {0}")]
    Io(#[from] std::io::Error),
}

/// Verify `binary_path` against `sig_path` (a minisign `.minisig` file)
/// using every trusted key in turn.
///
/// Returns the (zero-based) index of the trusted key that matched, useful for
/// telemetry / rotation observability. Returns
/// [`VerifyError::NoTrustedKeyMatched`] if none of the keys verify.
///
/// Pre-hashed and non-pre-hashed signatures are both accepted; the publish
/// pipeline uses `minisign -S -H` (pre-hashed) but legacy is allowed so a
/// transitional period that re-signs without `-H` does not silently break.
pub fn verify_with_any_trusted_key(
    binary_path: &Path,
    sig_path: &Path,
) -> Result<usize, VerifyError> {
    use minisign_verify::{PublicKey, Signature};

    let sig_text = std::fs::read_to_string(sig_path)?;
    let sig = Signature::decode(&sig_text)
        .map_err(|e| VerifyError::Malformed(format!("decode signature: {e}")))?;

    let content = std::fs::read(binary_path)?;

    let keys = trusted_keys();
    if keys.is_empty() {
        return Err(VerifyError::Malformed(
            "no trusted keys configured (signing/openlatch.pub is empty)".into(),
        ));
    }

    for (idx, key_b64) in keys.iter().enumerate() {
        let pk = PublicKey::from_base64(key_b64)
            .map_err(|e| VerifyError::Malformed(format!("trusted key #{idx} is invalid: {e}")))?;
        if pk.verify(&content, &sig, /* allow_legacy = */ true).is_ok() {
            return Ok(idx);
        }
    }

    Err(VerifyError::NoTrustedKeyMatched)
}

// ---------------------------------------------------------------------------
// Sanity check (run staging binary's --version, parse output)
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum SanityError {
    #[error("staging binary failed to execute: {0}")]
    ExecFailed(#[from] std::io::Error),

    #[error("staging binary exited non-zero ({0})")]
    NonZeroExit(i32),

    #[error("staging binary's --version output ({stdout:?}) did not contain expected version ({expected:?})")]
    VersionMismatch { stdout: String, expected: String },
}

/// Spawn `staging_binary --version` and assert that stdout contains
/// `expected_version`. Catches truncated downloads, wrong-architecture
/// binaries, and accidentally-staged build artefacts before the swap commits.
pub fn sanity_check_version(
    staging_binary: &Path,
    expected_version: &str,
) -> Result<(), SanityError> {
    let out = std::process::Command::new(staging_binary)
        .arg("--version")
        .output()?;

    if !out.status.success() {
        return Err(SanityError::NonZeroExit(out.status.code().unwrap_or(-1)));
    }

    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    if !stdout.contains(expected_version) {
        return Err(SanityError::VersionMismatch {
            stdout,
            expected: expected_version.to_string(),
        });
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Hook binary location resolver (delegates to existing src/hooks/mod.rs)
// ---------------------------------------------------------------------------

/// Resolve the absolute path to the `openlatch-hook` binary the swap should
/// target.
///
/// Delegates to [`crate::hooks::resolve_hook_binary_path`] (the same resolver
/// used at install time) and then asserts the resolved path exists on disk.
/// Returns [`std::io::ErrorKind::NotFound`] when no candidate exists — the
/// spike refuses to "swap" a hook that was never installed.
pub fn locate_hook_binary() -> std::io::Result<PathBuf> {
    let path = crate::hooks::resolve_hook_binary_path();
    if path.is_file() {
        Ok(path)
    } else {
        Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("hook binary not found at {}", path.display()),
        ))
    }
}

// ---------------------------------------------------------------------------
// Atomic swap (Phase 1 spike)
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum SwapError {
    #[error("could not resolve current executable: {0}")]
    CurrentExe(#[source] std::io::Error),

    #[error("hook binary swap failed: {0}")]
    HookSwap(#[source] std::io::Error),

    #[error("self-replace of running daemon binary failed: {0}")]
    SelfReplace(String),
}

/// Identifies the artefacts produced by [`perform_swap`] so a caller can
/// reverse the change via [`restore_from_bak`].
///
/// Both sides expose deterministic backup paths so the Phase 3 restart-
/// loop rollback can recover from a crash-looping update with no
/// directory-scanning heuristics. The daemon-side backup is produced by
/// `fs::copy(current_exe, current_exe.bak)` BEFORE `self_replace` runs —
/// `self_replace` leaves its own implementation-defined sibling on
/// Windows, but we never depend on it.
#[derive(Debug, Clone)]
pub struct SwapHandle {
    /// The path the running binary lived at when the swap began.
    pub current_exe: PathBuf,
    /// The running daemon's pre-swap backup. Deterministic —
    /// `<exe>.bak`. P3's [`rollback_from_bak`] consumes it after a
    /// supervisor-restart-loop trigger.
    pub current_exe_bak: PathBuf,
    /// The hook binary's install path (now points at the new bytes).
    pub hook_path: PathBuf,
    /// The hook binary's pre-swap backup. Deterministic — `<hook>.bak`.
    pub hook_bak: PathBuf,
}

/// Atomically swap both binaries to the staged versions.
///
/// **Order** (matters):
///
/// 1. `fs::copy(current_exe, current_exe.bak)` — captures the pre-swap
///    daemon bytes at a deterministic path so P3's restart-loop
///    rollback can find them. Reading a running binary is safe on every
///    supported OS (Unix execve mappings stay live across an unlink;
///    Windows `CreateFileW` allows `FILE_SHARE_READ` on running PEs).
/// 2. `fs::rename(hook_path, hook.bak)` — cheap, the hook isn't running.
/// 3. `fs::rename(staging_hook, hook_path)` — installs the new hook.
/// 4. `self_replace::self_replace(staging_exe)` — atomic on every supported
///    OS; on Windows it handles the running-binary file lock internally by
///    moving the old binary aside to a hidden `.<random>` sibling and
///    installing the new bytes at the original path.
///
/// **DO NOT** pre-rename `current_exe` — that defeats `self_replace`'s
/// own move-aside dance. We *copy* (step 1) instead; the running binary
/// stays at its original path so `self_replace` works normally.
///
/// On any failure after step 1, the `<exe>.bak` copy is removed so we
/// don't leave a stray binary behind. Hook-side rollbacks mirror the
/// pre-swap state.
pub fn perform_swap(
    staging_exe: &Path,
    staging_hook: &Path,
    hook_path: &Path,
) -> Result<SwapHandle, SwapError> {
    let current_exe = std::env::current_exe().map_err(SwapError::CurrentExe)?;
    let hook_bak = hook_path.with_extension("bak");
    let current_exe_bak = current_exe.with_extension("bak");

    // Step 1: snapshot the running daemon bytes to a deterministic
    // `<exe>.bak` path so the restart-loop rollback path has a known
    // rollback target. A failure here aborts the swap before we touch
    // anything else on disk.
    if let Err(e) = std::fs::copy(&current_exe, &current_exe_bak) {
        return Err(SwapError::SelfReplace(format!(
            "snapshot current_exe to {}: {e}",
            current_exe_bak.display()
        )));
    }

    // Step 2: hook → hook.bak.
    if let Err(e) = std::fs::rename(hook_path, &hook_bak) {
        let _ = std::fs::remove_file(&current_exe_bak);
        return Err(SwapError::HookSwap(e));
    }

    // Step 3: staging-hook → hook.
    if let Err(e) = std::fs::rename(staging_hook, hook_path) {
        let _ = std::fs::rename(&hook_bak, hook_path);
        let _ = std::fs::remove_file(&current_exe_bak);
        return Err(SwapError::HookSwap(e));
    }

    // Step 4: self-replace the running daemon binary.
    if let Err(e) = self_replace::self_replace(staging_exe) {
        // Daemon swap failed — best-effort hook rollback so we don't
        // leave a daemon/hook version mismatch on disk, plus drop the
        // pre-swap snapshot since the daemon path was never modified.
        let recovery = hook_path.with_extension("hook-pending-recovery");
        let _ = std::fs::rename(hook_path, &recovery);
        let _ = std::fs::rename(&hook_bak, hook_path);
        let _ = std::fs::remove_file(&current_exe_bak);
        return Err(SwapError::SelfReplace(format!("{e}")));
    }

    Ok(SwapHandle {
        current_exe,
        current_exe_bak,
        hook_path: hook_path.to_path_buf(),
        hook_bak,
    })
}

/// Restore the hook binary from its `.bak` sibling. No-op when the backup
/// does not exist (e.g. the swap completed and the backup was already
/// cleaned up).
///
/// The daemon-side `current_exe` restore is intentionally not handled here
/// — see [`SwapHandle`] for why. P3's restart-loop rollback owns that.
pub fn restore_from_bak(handle: &SwapHandle) -> std::io::Result<()> {
    if handle.hook_bak.exists() {
        std::fs::rename(&handle.hook_bak, &handle.hook_path)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Manifest fetch + semver + platform-tarball check
// ---------------------------------------------------------------------------

/// Severity hint published per-release on each platform package's
/// `openlatch.severity` field. The auto-update worker bypasses
/// activity-aware deferral when this is `Critical`. Default `Normal`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Severity {
    #[default]
    Normal,
    Critical,
}

impl Severity {
    fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "normal" => Some(Self::Normal),
            "critical" => Some(Self::Critical),
            _ => None,
        }
    }

    /// Lowercase wire form: `"normal"` | `"critical"`. Used as a
    /// telemetry property and surfaced in `/admin/update/status`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Critical => "critical",
        }
    }
}

impl serde::Serialize for Severity {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

/// Outcome of a single manifest probe against the npm registry.
#[derive(Debug, Clone)]
pub enum CheckResult {
    /// Local binary is at or ahead of the registry's `latest` tag.
    UpToDate { current: String },
    /// A newer version is published AND the platform-specific package +
    /// tarball CDN entry are reachable.
    Available {
        current: String,
        latest: String,
        severity: Severity,
        /// `min_supported_client` declared by the new release. If our
        /// current version is older than this, the daemon refuses the
        /// update and surfaces the manual `npm install -g` recovery path.
        min_supported: Option<String>,
        tarball_url: String,
        /// SRI string from `dist.integrity` (e.g.
        /// `"sha512-aGVsbG8h..."`). Used by [`download_tarball`] to verify
        /// bytes against the manifest before extraction.
        tarball_integrity: String,
    },
    /// The check could not complete. Reasons include: registry
    /// unreachable, manifest malformed, platform package not yet
    /// propagated to the CDN. Treated as "no update yet" — never an
    /// error.
    Failed { reason: String },
}

/// Map the host's `target_os` + `target_arch` to the npm platform package
/// name. Returns `None` on unsupported targets (e.g. an Android build —
/// out of scope for this client).
pub fn platform_package_name() -> Option<&'static str> {
    if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
        Some("@openlatch/client-darwin-arm64")
    } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
        Some("@openlatch/client-darwin-x64")
    } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
        Some("@openlatch/client-linux-x64")
    } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
        Some("@openlatch/client-linux-arm64")
    } else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
        Some("@openlatch/client-win32-x64")
    } else {
        None
    }
}

/// Returns true if `current` is greater than or equal to `min`.
/// Both must be valid semver. Returns `false` if either fails to parse —
/// callers treat parse failure conservatively as "out of band".
pub fn version_at_least(current: &str, min: &str) -> bool {
    use semver::Version;
    match (Version::parse(current), Version::parse(min)) {
        (Ok(cur), Ok(m)) => cur >= m,
        _ => false,
    }
}

/// Probe the npm registry for a newer release of the platform package.
///
/// Returns a [`CheckResult`] in three flavours:
///
/// 1. [`CheckResult::UpToDate`] — local version >= registry `latest`.
/// 2. [`CheckResult::Available`] — newer version published AND the
///    platform-specific tarball CDN entry is reachable AND the manifest
///    contains a valid `dist.integrity` SRI string. The caller should
///    pass the returned `tarball_url` + `tarball_integrity` directly to
///    [`download_tarball`].
/// 3. [`CheckResult::Failed`] — the check could not complete (registry
///    down, manifest malformed, propagation race where the meta-package
///    `latest` tag points at a version not yet on the CDN). NOT an
///    error — callers treat as "no update yet, retry next cycle".
///
/// `registry_origin` is the bare origin (e.g.
/// `"https://registry.npmjs.org"`); the function appends the
/// percent-encoded scoped package paths itself.
pub async fn check(current_version: &str, registry_origin: &str) -> CheckResult {
    use semver::Version;

    // One client across all three registry calls — connection pool +
    // single TLS context + single DNS resolver. `.use_rustls_tls()` is
    // mandatory per `.claude/rules/security-constraints.md` (rustls-only
    // policy; no openssl-sys in the dep tree).
    let client = match reqwest::Client::builder()
        .timeout(Duration::from_secs(5))
        .use_rustls_tls()
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            return CheckResult::Failed {
                reason: format!("http client build: {e}"),
            }
        }
    };

    // 1. Fetch the meta-package's `latest` dist-tag.
    let registry = registry_origin.trim_end_matches('/');
    let meta_url = format!("{registry}/@openlatch%2Fclient/latest");
    let manifest = match http_get_json(&client, &meta_url).await {
        Ok(v) => v,
        Err(e) => {
            return CheckResult::Failed {
                reason: format!("manifest fetch: {e}"),
            }
        }
    };
    let Some(latest_str) = manifest.get("version").and_then(|v| v.as_str()) else {
        return CheckResult::Failed {
            reason: "manifest missing version".into(),
        };
    };

    // 2. Semver compare. String equality is wrong: a 0.1.10 release looks
    //    "older" than 0.1.9 lexically.
    let (Ok(current), Ok(latest)) = (Version::parse(current_version), Version::parse(latest_str))
    else {
        return CheckResult::Failed {
            reason: "version parse failed".into(),
        };
    };
    if latest <= current {
        return CheckResult::UpToDate {
            current: current_version.to_string(),
        };
    }

    // 3. Fetch the version-specific platform package manifest. Hitting
    //    `{registry}/{pkg}/{version}` returns just that one version's
    //    document instead of the full versions history (which can be
    //    100+ entries × multi-KB each on a long-lived package).
    let Some(platform_pkg) = platform_package_name() else {
        return CheckResult::Failed {
            reason: format!(
                "no platform package for target_os={} target_arch={} — cannot auto-update",
                std::env::consts::OS,
                std::env::consts::ARCH,
            ),
        };
    };
    let plat_url = format!(
        "{registry}/{}/{latest_str}",
        platform_pkg.replace('/', "%2F"),
    );
    let v = match http_get_json(&client, &plat_url).await {
        Ok(v) => v,
        // 404 is the npm propagation race: meta-package `latest` was
        // bumped, but the platform package's CDN entry hasn't caught
        // up yet. Clean failure — caller retries next cycle.
        Err(e) => {
            return CheckResult::Failed {
                reason: format!(
                    "platform package {platform_pkg} version {latest_str} not yet on registry: {e}"
                ),
            };
        }
    };

    let Some(tarball_url) = v
        .pointer("/dist/tarball")
        .and_then(|t| t.as_str())
        .map(String::from)
    else {
        return CheckResult::Failed {
            reason: "platform manifest missing dist.tarball".into(),
        };
    };
    let Some(tarball_integrity) = v
        .pointer("/dist/integrity")
        .and_then(|t| t.as_str())
        .map(String::from)
    else {
        return CheckResult::Failed {
            reason: "platform manifest missing dist.integrity".into(),
        };
    };

    // 4. HEAD-check the tarball URL to catch the "manifest published, CDN
    //    still propagating" window before we commit to a download.
    if !http_head_ok(&client, &tarball_url).await {
        return CheckResult::Failed {
            reason: "platform tarball not yet reachable on registry CDN".into(),
        };
    }

    // 5. Optional metadata: severity + min_supported_client. Both default
    //    sensibly when absent so older releases (which don't carry the
    //    `openlatch` block) keep working.
    let severity = v
        .pointer("/openlatch/severity")
        .and_then(|s| s.as_str())
        .and_then(Severity::from_str_opt)
        .unwrap_or_default();
    let min_supported = v
        .pointer("/openlatch/min_supported_client")
        .and_then(|s| s.as_str())
        .map(String::from);

    CheckResult::Available {
        current: current_version.to_string(),
        latest: latest_str.to_string(),
        severity,
        min_supported,
        tarball_url,
        tarball_integrity,
    }
}

async fn http_get_json(client: &reqwest::Client, url: &str) -> Result<serde_json::Value, String> {
    let resp = client
        .get(url)
        .header("Accept", "application/json")
        .send()
        .await
        .map_err(|e| format!("send: {e}"))?;
    if !resp.status().is_success() {
        return Err(format!("HTTP {}", resp.status()));
    }
    resp.json::<serde_json::Value>()
        .await
        .map_err(|e| format!("json: {e}"))
}

async fn http_head_ok(client: &reqwest::Client, url: &str) -> bool {
    matches!(client.head(url).send().await, Ok(r) if r.status().is_success())
}

// ---------------------------------------------------------------------------
// Tarball download + SHA-512 SRI verify
// ---------------------------------------------------------------------------

/// Failure modes for [`download_tarball`].
#[derive(Debug, thiserror::Error)]
pub enum DownloadError {
    #[error("tarball download failed: {0}")]
    Http(String),

    #[error("integrity field is not a recognised SRI hash: {0}")]
    IntegrityFormat(String),

    #[error("downloaded tarball failed integrity check (SRI mismatch)")]
    IntegrityMismatch,
}

/// Download `url` to memory and verify the bytes against `sri`, an
/// [npm `dist.integrity`][1] string of the form `"sha512-<base64>"`.
///
/// The SRI value comes from the platform manifest returned by
/// [`check`] — verifying it before any tarball-extraction code runs is
/// the first defence against a tampered-CDN scenario where the manifest
/// is genuine but the tarball it points at has been swapped. This is
/// strictly weaker than minisign verification on the unpacked binaries
/// (which P1 enforces post-extract) — but it short-circuits the
/// extraction step entirely on a mismatch.
///
/// No size cap by design — the platform manifest's integrity field
/// itself is the authoritative bound on bytes accepted.
///
/// [1]: https://docs.npmjs.com/about-package-tarballs
pub async fn download_tarball(
    url: &str,
    sri: &str,
    timeout: Duration,
) -> Result<Vec<u8>, DownloadError> {
    use sha2::{Digest, Sha512};
    use subtle::ConstantTimeEq;

    // Parse SRI. We accept exactly `sha512-<base64>` — the only digest
    // algorithm npm currently emits. (`integrity` may carry multiple
    // space-separated hashes; we pick the first sha512 entry.)
    let expected_b64 = sri
        .split_ascii_whitespace()
        .find_map(|tok| tok.strip_prefix("sha512-"))
        .ok_or_else(|| {
            DownloadError::IntegrityFormat(format!(
                "expected `sha512-...`, got {}",
                sri.chars().take(40).collect::<String>()
            ))
        })?;
    let expected = base64_decode_lenient(expected_b64).map_err(|e| {
        DownloadError::IntegrityFormat(format!("base64 decode of integrity hash failed: {e}"))
    })?;
    if expected.len() != 64 {
        return Err(DownloadError::IntegrityFormat(format!(
            "sha512 digest must be 64 bytes; got {}",
            expected.len()
        )));
    }

    let client = reqwest::Client::builder()
        .timeout(timeout)
        .use_rustls_tls()
        .build()
        .map_err(|e| DownloadError::Http(format!("client build: {e}")))?;
    let resp = client
        .get(url)
        .send()
        .await
        .map_err(|e| DownloadError::Http(format!("send: {e}")))?;
    if !resp.status().is_success() {
        return Err(DownloadError::Http(format!("HTTP {}", resp.status())));
    }
    let bytes = resp
        .bytes()
        .await
        .map_err(|e| DownloadError::Http(format!("read body: {e}")))?
        .to_vec();

    let mut hasher = Sha512::new();
    hasher.update(&bytes);
    let actual = hasher.finalize();
    if !bool::from(actual.as_slice().ct_eq(&expected)) {
        return Err(DownloadError::IntegrityMismatch);
    }

    Ok(bytes)
}

fn base64_decode_lenient(b64: &str) -> Result<Vec<u8>, String> {
    use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD};
    use base64::Engine;
    // npm's SRI strings are padded standard base64 in practice, but we
    // accept either form so a manifest emitted by an older publisher
    // still verifies.
    STANDARD
        .decode(b64.as_bytes())
        .or_else(|_| STANDARD_NO_PAD.decode(b64.as_bytes()))
        .map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Hardened tar extraction
// ---------------------------------------------------------------------------

/// Per-entry size cap during extraction. Today's binaries are ~10 MB; 64 MB
/// gives generous headroom while still bounding worst-case extraction work
/// against a malicious or corrupted tarball.
const ENTRY_SIZE_CAP: u64 = 64 * 1024 * 1024;

/// Failure modes for [`extract_to_staging`].
#[derive(Debug, thiserror::Error)]
pub enum ExtractError {
    #[error("io error during extraction: {0}")]
    Io(#[from] std::io::Error),

    #[error("tar entry exceeds 64 MB cap")]
    EntryTooLarge,

    #[error("tar entry has suspicious filename: {0}")]
    SuspiciousFilename(String),

    #[error("tar contains duplicate entry for: {0}")]
    DuplicateEntry(String),

    #[error("tar missing required file after extraction: {0}")]
    MissingRequired(String),
}

/// Files we are willing to extract from a tarball. Anything else is
/// silently skipped — npm's `npm pack` adds `package.json`, `README.md`,
/// etc. by default, and we don't want to fail on their presence.
const EXTRACT_ALLOWLIST: &[&str] = &[
    "openlatch",
    "openlatch.exe",
    "openlatch-hook",
    "openlatch-hook.exe",
    "openlatch.minisig",
    "openlatch.exe.minisig",
    "openlatch-hook.minisig",
    "openlatch-hook.exe.minisig",
];

/// Extract a gzip-compressed npm-style tarball into `staging_dir` with
/// the full hardening contract from `.local/brainstorms/auto-update/PHASE-2-manual-via-rpc.md`
/// section 8.
///
/// **Hardening invariants** (each one is a CVE-class avoidance):
///
/// 1. Only regular files are accepted. Symlinks, hardlinks, char/block
///    devices, FIFOs, and directory entries are skipped — not errors,
///    because npm pack legitimately includes a `package/` directory entry.
/// 2. Each entry is capped at [`ENTRY_SIZE_CAP`] (64 MB). A malicious tar
///    advertising 10 GB never proceeds past this check.
/// 3. Only files whose **basename** matches [`EXTRACT_ALLOWLIST`] are
///    written. Everything else is skipped silently.
/// 4. Even within the allowlist, basenames containing `..` or `/` or `\`
///    are rejected with [`ExtractError::SuspiciousFilename`] — defence in
///    depth against a basename like `openlatch/../../etc/passwd`.
/// 5. The basename is what's joined to `staging_dir`; the tar header's
///    full path (typically `package/openlatch`) is ignored. Path traversal
///    is structurally impossible.
/// 6. Duplicate basenames are an error — a tar with two `openlatch`
///    entries can't both win, and the order would be exploitable.
/// 7. On Unix, every extracted file is forced to mode `0o755` *after*
///    write, ignoring the tar header's perms entirely.
/// 8. Required files (binaries + sigs for the host platform) MUST all
///    be present after the loop; otherwise [`ExtractError::MissingRequired`].
pub fn extract_to_staging(tarball_bytes: &[u8], staging_dir: &Path) -> Result<(), ExtractError> {
    use std::io::Read;
    use tar::EntryType;

    // Caller is expected to pass an empty staging dir; create it if
    // missing rather than failing — keeps callers terser.
    std::fs::create_dir_all(staging_dir)?;

    let gz = flate2::read::GzDecoder::new(tarball_bytes);
    let mut archive = tar::Archive::new(gz);

    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();

    for entry in archive.entries()? {
        let mut entry = entry?;

        // Invariant 1: regular files only. This skip is silent — npm tarballs
        // legitimately carry a `package/` directory entry.
        if entry.header().entry_type() != EntryType::Regular {
            continue;
        }

        // Invariant 2: per-entry size cap.
        if entry.size() > ENTRY_SIZE_CAP {
            return Err(ExtractError::EntryTooLarge);
        }

        // Resolve the basename — the tar's path is ignored.
        let path_in_tar = entry.path()?;
        let Some(basename_os) = path_in_tar.file_name() else {
            continue;
        };
        let Some(basename) = basename_os.to_str() else {
            continue;
        };

        // Invariant 4: defence in depth — refuse anything that smells like
        // path traversal even after we already extracted the basename.
        if basename.contains("..") || basename.contains('/') || basename.contains('\\') {
            return Err(ExtractError::SuspiciousFilename(basename.to_string()));
        }

        // Invariant 3: allowlist match (silent skip on miss).
        if !EXTRACT_ALLOWLIST.contains(&basename) {
            continue;
        }

        // Invariant 6: duplicate rejection.
        if !seen.insert(basename.to_string()) {
            return Err(ExtractError::DuplicateEntry(basename.to_string()));
        }

        // Invariant 5: dest is `staging_dir/<basename>` — never anywhere
        // else.
        let dest = staging_dir.join(basename);
        let mut out = std::fs::File::create(&dest)?;
        // Manual copy with our own size guard, matching `entry.size()`
        // precisely. `tar::Entry` already enforces the declared size
        // via `Read`, but we cap the copy too so a header that
        // misadvertises size cannot blow past the cap mid-stream.
        let mut buf = [0u8; 64 * 1024];
        let mut written: u64 = 0;
        loop {
            let n = entry.read(&mut buf)?;
            if n == 0 {
                break;
            }
            written = written.saturating_add(n as u64);
            if written > ENTRY_SIZE_CAP {
                return Err(ExtractError::EntryTooLarge);
            }
            std::io::Write::write_all(&mut out, &buf[..n])?;
        }
        drop(out);

        // Invariant 7: force perms on Unix.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))?;
        }
    }

    // Invariant 8: required-file presence. The signature siblings are
    // mandatory — without them the swap pipeline cannot verify, and
    // refusing here is cheaper than failing inside `verify_with_any_trusted_key`.
    let required: &[&str] = if cfg!(windows) {
        &[
            "openlatch.exe",
            "openlatch-hook.exe",
            "openlatch.exe.minisig",
            "openlatch-hook.exe.minisig",
        ]
    } else {
        &[
            "openlatch",
            "openlatch-hook",
            "openlatch.minisig",
            "openlatch-hook.minisig",
        ]
    };
    for r in required {
        if !staging_dir.join(r).exists() {
            return Err(ExtractError::MissingRequired((*r).to_string()));
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Update sentinel + restart helpers
// ---------------------------------------------------------------------------

/// Single-shot breadcrumb written by the daemon **after** a successful
/// swap and **before** the drain → restart sequence. The new daemon
/// reads this file in [`read_sentinel`] at startup; if present and the
/// post-restart `/health` probe succeeds, the new daemon cleans up the
/// `.bak` siblings + sentinel itself.
///
/// Persisted at `~/.openlatch/update-sentinel.json`. Schema is
/// intentionally tiny so partial writes are never ambiguous.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UpdateSentinel {
    pub from: String,
    pub to: String,
    /// RFC 3339 UTC timestamp.
    pub applied_at: String,
}

/// Path of the sentinel inside `openlatch_dir()`.
pub fn sentinel_path() -> PathBuf {
    crate::config::openlatch_dir().join("update-sentinel.json")
}

/// Atomically write the sentinel file (temp + rename).
pub fn write_sentinel(s: &UpdateSentinel) -> std::io::Result<()> {
    let path = sentinel_path();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let body = serde_json::to_string_pretty(s).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("serialise sentinel: {e}"),
        )
    })?;
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, body)?;
    std::fs::rename(&tmp, &path)?;
    Ok(())
}

/// Read the sentinel if present. Parse failures are swallowed (log a
/// warning) — a malformed sentinel must never block the new daemon's
/// startup.
pub fn read_sentinel() -> Option<UpdateSentinel> {
    let path = sentinel_path();
    let raw = std::fs::read_to_string(&path).ok()?;
    match serde_json::from_str::<UpdateSentinel>(&raw) {
        Ok(s) => Some(s),
        Err(e) => {
            tracing::warn!(target: "update", error = %e, "update sentinel malformed; ignoring");
            None
        }
    }
}

/// Remove the sentinel — called by the new daemon after a successful
/// post-restart `/health` probe.
pub fn delete_sentinel() -> std::io::Result<()> {
    let path = sentinel_path();
    match std::fs::remove_file(&path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

/// Remove the `<hook>.bak` and `<exe>.bak` siblings left behind by
/// [`perform_swap`]. Idempotent — a missing file is a no-op. Called
/// after the post-restart `/health` probe confirms the new daemon is
/// alive; a failed probe leaves both files in place so P3's
/// [`should_rollback`] can recover.
///
/// Also clears `~/.openlatch/restart-tracker.json` — once a release
/// has booted cleanly the update episode is over and any residual
/// startup timestamps are dead weight. Leaving them would let three
/// crash starts inside a single 60 s window count cumulatively across
/// two unrelated update episodes.
pub fn cleanup_bak_files() -> std::io::Result<()> {
    fn remove_if_present(p: &Path) -> std::io::Result<()> {
        match std::fs::remove_file(p) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(e),
        }
    }
    if let Ok(hook) = locate_hook_binary() {
        remove_if_present(&hook.with_extension("bak"))?;
    }
    if let Ok(exe) = std::env::current_exe() {
        remove_if_present(&exe.with_extension("bak"))?;
    }
    let _ = std::fs::remove_file(restart_tracker_path());
    Ok(())
}

/// Re-exec into the freshly-swapped binary at `current_exe()`.
///
/// **Unix**: `execv()` replaces the current process image, retaining
/// the daemon's PID — supervisors (launchd, systemd-user) see no
/// process exit. Returns `Err` only on the rare case where execv
/// itself fails (ENOEXEC, EACCES). On success the function does not
/// return.
///
/// **Windows**: the running process cannot replace its own image, so
/// we spawn a detached child of the new binary (passing through our
/// argv) and `process::exit(0)` from the parent. Task Scheduler's
/// auto-restart bridge is what carries the PID change in this path —
/// not retained, but the user-visible behaviour is "the daemon
/// restarted".
pub fn restart_into_new_binary() -> Result<(), String> {
    let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
    let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();

    tracing::info!(target: "update", exe = %exe.display(), "re-executing into new binary");

    #[cfg(unix)]
    {
        use std::ffi::CString;
        use std::os::unix::ffi::OsStrExt;

        // Build the argv vec — argv[0] is the program name, the rest
        // come from the daemon's own argv.
        let mut argv: Vec<CString> = Vec::with_capacity(args.len() + 1);
        argv.push(
            CString::new(exe.as_os_str().as_bytes()).map_err(|e| format!("argv0 cstring: {e}"))?,
        );
        for a in &args {
            argv.push(CString::new(a.as_bytes()).map_err(|e| format!("argv cstring: {e}"))?);
        }
        let argv_refs: Vec<&std::ffi::CStr> = argv.iter().map(|c| c.as_c_str()).collect();
        let cstr_path = CString::new(exe.as_os_str().as_bytes())
            .map_err(|e| format!("exe path cstring: {e}"))?;
        match nix::unistd::execv(&cstr_path, &argv_refs) {
            Ok(_void) => Ok(()),
            Err(e) => Err(format!("execv: {e}")),
        }
    }

    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        // CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS — the child
        // outlives this process and does not share its console.
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
        const DETACHED_PROCESS: u32 = 0x0000_0008;

        let res = std::process::Command::new(&exe)
            .args(&args)
            .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
            .spawn();
        match res {
            Ok(_child) => {
                std::process::exit(0);
            }
            Err(e) => Err(format!("spawn-detached: {e}")),
        }
    }

    #[cfg(not(any(unix, windows)))]
    {
        Err("restart_into_new_binary: unsupported platform".into())
    }
}

// ---------------------------------------------------------------------------
// In-process apply orchestrator
// ---------------------------------------------------------------------------

/// Which entrypoint drove an apply pipeline. Surfaces as a low-cardinality
/// telemetry property and as the `mode` field in `/admin/update/status`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApplyMode {
    /// CLI invoked the daemon's `POST /admin/update` RPC.
    Rpc,
    /// CLI ran the apply pipeline in its own process (no daemon up).
    InProcess,
}

impl ApplyMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Rpc => "rpc",
            Self::InProcess => "in_process",
        }
    }
}

/// Tunables for [`apply_local`] / [`prepare_swap_artefacts`].
#[derive(Debug, Clone)]
pub struct ApplyOptions {
    /// Current daemon/CLI version — usually `env!("CARGO_PKG_VERSION")`.
    pub current_version: String,
    /// Registry origin (e.g. `https://registry.npmjs.org`).
    pub registry_origin: String,
    /// Tarball download timeout.
    pub download_timeout: Duration,
    /// When `true`, the cargo-install gate is bypassed. The CLI exposes
    /// this via `--force-cargo` for maintainers who really do want to
    /// auto-update an unsupported install.
    pub force_cargo_install: bool,
    /// Which entrypoint drove the apply — surfaced in telemetry.
    pub mode: ApplyMode,
}

impl ApplyOptions {
    /// Default options for the CLI's no-daemon path.
    pub fn for_cli(current_version: impl Into<String>, registry_origin: impl Into<String>) -> Self {
        Self {
            current_version: current_version.into(),
            registry_origin: registry_origin.into(),
            download_timeout: Duration::from_secs(60),
            force_cargo_install: false,
            mode: ApplyMode::InProcess,
        }
    }
}

/// Stages of the apply pipeline. Surfaced in failure responses so
/// `openlatch update` (and `/admin/update/status` in the daemon path)
/// can tell the user where it broke without having to log-dive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ApplyStage {
    Check,
    Download,
    Extract,
    Verify,
    Sanity,
    Swap,
    Drain,
    Restart,
    Healthz,
}

impl ApplyStage {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Check => "check",
            Self::Download => "download",
            Self::Extract => "extract",
            Self::Verify => "verify",
            Self::Sanity => "sanity",
            Self::Swap => "swap",
            Self::Drain => "drain",
            Self::Restart => "restart",
            Self::Healthz => "healthz",
        }
    }
}

/// Lifecycle states the apply pipeline reports through the daemon's
/// `/admin/update/status` endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateStatusKind {
    Idle,
    InProgress,
    Completed,
    Failed,
}

/// Snapshot of the in-flight (or last) apply pipeline. Updated in place
/// by the spawned apply task so the CLI's long-poll surface renders
/// meaningful progress.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UpdateStatusSnapshot {
    pub status: UpdateStatusKind,
    pub stage: Option<ApplyStage>,
    pub from: Option<String>,
    pub to: Option<String>,
    pub started_at: Option<String>,
    pub ended_at: Option<String>,
    pub error: Option<String>,
}

impl UpdateStatusSnapshot {
    pub fn idle() -> Self {
        Self {
            status: UpdateStatusKind::Idle,
            stage: None,
            from: None,
            to: None,
            started_at: None,
            ended_at: None,
            error: None,
        }
    }
}

/// Outcome of [`apply_local`]. Distinct from [`CheckResult`] because
/// apply has more failure surfaces (signature, sanity, swap) that the
/// caller surfaces to the user as distinct CLI exits.
#[derive(Debug, Clone)]
pub enum ApplyResult {
    /// New version installed end-to-end (in the in-process case the CLI
    /// is about to exit; in the daemon case the daemon is about to
    /// restart).
    Applied {
        from: String,
        to: String,
        severity: Severity,
        duration_ms: u64,
    },
    /// Already on the latest version — apply is idempotent.
    UpToDate { current: String },
    /// Caller's binary is `cargo install`-managed — auto-update will
    /// not modify it. Includes the recovery suggestion verbatim.
    RefusedCargoInstall { suggestion: String },
    /// Pipeline failed at the named stage.
    Failed { stage: ApplyStage, reason: String },
}

/// Stage-2 artefacts produced by [`prepare_swap_artefacts`]: a staging
/// directory holding verified binaries + signatures, ready to feed into
/// [`perform_swap`]. The daemon path also lifts these out and runs the
/// drain + restart sequence around them.
pub struct SwapArtefacts {
    pub staging_dir: tempfile::TempDir,
    pub staging_exe: PathBuf,
    pub staging_hook: PathBuf,
    pub from: String,
    pub to: String,
    pub severity: Severity,
}

/// Run the full apply pipeline up to (but not including) the swap
/// itself. Returns either the staged-artefacts handle that the caller
/// will hand to [`perform_swap`], or an [`ApplyResult`] short-circuit
/// describing why apply will not proceed (already up to date, refused,
/// failed).
///
/// Splitting check + download + verify + sanity from the swap step lets
/// the daemon path interleave drain/restart logic at a single,
/// well-defined seam, rather than forcing the whole pipeline through
/// a single function.
pub async fn prepare_swap_artefacts(opts: &ApplyOptions) -> Result<SwapArtefacts, ApplyResult> {
    use crate::install_state::{detect_install_method, InstallMethod};

    // Stage 0: cargo-install gate. Done first so we never hit the
    // network for a binary we won't update.
    if !opts.force_cargo_install && matches!(detect_install_method(), InstallMethod::CargoInstall) {
        let suggestion = "Run: cargo install --force --locked openlatch-client".to_string();
        tracing::warn!(target: "update", "refusing to auto-update cargo-install binary");
        return Err(ApplyResult::RefusedCargoInstall { suggestion });
    }

    // Stage 1: manifest probe.
    let check_result = check(&opts.current_version, &opts.registry_origin).await;
    let (latest, severity, min_supported, tarball_url, tarball_integrity) = match check_result {
        CheckResult::UpToDate { current } => {
            crate::telemetry::capture_global(crate::telemetry::Event::update_check(
                "up_to_date",
                None,
                None,
            ));
            return Err(ApplyResult::UpToDate { current });
        }
        CheckResult::Failed { reason } => {
            crate::telemetry::capture_global(crate::telemetry::Event::update_check(
                "failed", None, None,
            ));
            return Err(ApplyResult::Failed {
                stage: ApplyStage::Check,
                reason,
            });
        }
        CheckResult::Available {
            latest,
            severity,
            min_supported,
            tarball_url,
            tarball_integrity,
            ..
        } => {
            crate::telemetry::capture_global(crate::telemetry::Event::update_check(
                "available",
                Some(&latest),
                Some(severity.as_str()),
            ));
            (
                latest,
                severity,
                min_supported,
                tarball_url,
                tarball_integrity,
            )
        }
    };

    // Stage 2: min_supported gate. Telemetry captures the long-tail of
    // clients who can't be auto-updated.
    if let Some(ref min) = min_supported {
        if !version_at_least(&opts.current_version, min) {
            crate::telemetry::capture_global(
                crate::telemetry::Event::update_blocked_by_min_supported(
                    &opts.current_version,
                    &latest,
                    min,
                ),
            );
            return Err(ApplyResult::Failed {
                stage: ApplyStage::Check,
                reason: format!(
                    "current version {} is older than min_supported_client {} for release {} — manual `npm install -g @openlatch/client@{}` required",
                    opts.current_version, min, latest, latest
                ),
            });
        }
    }

    // Telemetry: pipeline begins.
    crate::telemetry::capture_global(crate::telemetry::Event::update_started(
        &opts.current_version,
        &latest,
        severity.as_str(),
        opts.mode.as_str(),
    ));

    tracing::info!(target: "update", from = %opts.current_version, to = %latest, severity = %severity.as_str(), "auto-update apply started");

    // Stage 3: download + integrity verify.
    let bytes = match download_tarball(&tarball_url, &tarball_integrity, opts.download_timeout)
        .await
    {
        Ok(b) => b,
        Err(e) => {
            tracing::warn!(target: "update", error = %e, stage = "download", "tarball download failed");
            return Err(ApplyResult::Failed {
                stage: ApplyStage::Download,
                reason: e.to_string(),
            });
        }
    };

    // Stage 4: extract into a tempdir so a swap failure leaves no
    // partial state on disk.
    let staging_dir = tempfile::tempdir().map_err(|e| ApplyResult::Failed {
        stage: ApplyStage::Extract,
        reason: format!("create staging tempdir: {e}"),
    })?;
    if let Err(e) = extract_to_staging(&bytes, staging_dir.path()) {
        tracing::warn!(target: "update", error = %e, stage = "extract", "tar extraction failed");
        return Err(ApplyResult::Failed {
            stage: ApplyStage::Extract,
            reason: e.to_string(),
        });
    }

    let (exe_name, exe_sig_name, hook_name, hook_sig_name) = if cfg!(windows) {
        (
            "openlatch.exe",
            "openlatch.exe.minisig",
            "openlatch-hook.exe",
            "openlatch-hook.exe.minisig",
        )
    } else {
        (
            "openlatch",
            "openlatch.minisig",
            "openlatch-hook",
            "openlatch-hook.minisig",
        )
    };
    let staging_exe = staging_dir.path().join(exe_name);
    let staging_exe_sig = staging_dir.path().join(exe_sig_name);
    let staging_hook = staging_dir.path().join(hook_name);
    let staging_hook_sig = staging_dir.path().join(hook_sig_name);

    // Stage 5: minisign verify on both binaries. A failure here is the
    // most severe signal we have — emit `update_signature_failed`.
    if let Err(e) = verify_with_any_trusted_key(&staging_exe, &staging_exe_sig) {
        crate::telemetry::capture_global(crate::telemetry::Event::update_signature_failed(
            &opts.current_version,
            &latest,
            "openlatch",
        ));
        tracing::warn!(target: "update", error = %e, stage = "verify", binary = "openlatch", "signature verification failed");
        return Err(ApplyResult::Failed {
            stage: ApplyStage::Verify,
            reason: format!("openlatch verify: {e}"),
        });
    }
    if let Err(e) = verify_with_any_trusted_key(&staging_hook, &staging_hook_sig) {
        crate::telemetry::capture_global(crate::telemetry::Event::update_signature_failed(
            &opts.current_version,
            &latest,
            "openlatch-hook",
        ));
        tracing::warn!(target: "update", error = %e, stage = "verify", binary = "openlatch-hook", "signature verification failed");
        return Err(ApplyResult::Failed {
            stage: ApplyStage::Verify,
            reason: format!("openlatch-hook verify: {e}"),
        });
    }

    // Stage 6: sanity check — does the staging binary print the
    // expected version? Catches truncated downloads, accidentally
    // wrong-architecture binaries, broken signatures-but-good-payload
    // edge cases.
    if let Err(e) = sanity_check_version(&staging_exe, &latest) {
        tracing::warn!(target: "update", error = %e, stage = "sanity", "sanity check failed");
        return Err(ApplyResult::Failed {
            stage: ApplyStage::Sanity,
            reason: e.to_string(),
        });
    }

    Ok(SwapArtefacts {
        staging_dir,
        staging_exe,
        staging_hook,
        from: opts.current_version.clone(),
        to: latest,
        severity,
    })
}

/// Apply an update entirely in the calling process — used by the CLI's
/// no-daemon fallback (`openlatch update --apply --yes` when no daemon
/// is running).
///
/// Coordinates [`prepare_swap_artefacts`] + [`perform_swap`] + an
/// install-state.json write. This path **does NOT** drain or restart
/// anything (the CLI is the only thing running) — the new binary takes
/// effect on the next invocation.
pub async fn apply_local(opts: ApplyOptions) -> ApplyResult {
    let started = std::time::Instant::now();
    let artefacts = match prepare_swap_artefacts(&opts).await {
        Ok(a) => a,
        Err(short_circuit) => return short_circuit,
    };

    // Stage 7: locate live hook + swap.
    let hook_path = match locate_hook_binary() {
        Ok(p) => p,
        Err(e) => {
            return ApplyResult::Failed {
                stage: ApplyStage::Swap,
                reason: format!("locate hook binary: {e}"),
            };
        }
    };
    if let Err(e) = perform_swap(&artefacts.staging_exe, &artefacts.staging_hook, &hook_path) {
        return ApplyResult::Failed {
            stage: ApplyStage::Swap,
            reason: e.to_string(),
        };
    }

    let duration_ms = started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64;

    // Stage 8: stamp install-state.json. Save failure is non-fatal —
    // the swap already succeeded; drift surfacing in status/doctor
    // degrades gracefully when the file is absent.
    crate::install_state::InstallState::stamp_for_running_binary(&artefacts.to);

    crate::telemetry::capture_global(crate::telemetry::Event::update_completed(
        &artefacts.from,
        &artefacts.to,
        artefacts.severity.as_str(),
        opts.mode.as_str(),
        true,
        Some(duration_ms),
        false,
    ));

    tracing::info!(target: "update", from = %artefacts.from, to = %artefacts.to, duration_ms = duration_ms, "auto-update apply completed");

    ApplyResult::Applied {
        from: artefacts.from,
        to: artefacts.to,
        severity: artefacts.severity,
        duration_ms,
    }
}

// ---------------------------------------------------------------------------
// Auto-apply decision logic
// ---------------------------------------------------------------------------

/// Decide whether the daemon should apply an available update right now.
///
/// Decision table:
///
/// | severity | last_hook age   | in_flight | pending_age   | apply? |
/// |----------|-----------------|-----------|---------------|--------|
/// | Critical | any             | any       | any           | yes    |
/// | Normal   | ≥ quiet_window  | 0         | any           | yes    |
/// | Normal   | ≥ quiet_window  | > 0       | < max_defer   | no     |
/// | Normal   | < quiet_window  | any       | < max_defer   | no     |
/// | Normal   | any             | any       | ≥ max_defer   | yes    |
///
/// Both `last_hook_at` ≥ quiet_window AND `hooks_in_flight == 0` must
/// hold for a non-critical apply: a 90 s hook with no other traffic
/// would look idle under entry-only timestamping; the in-flight counter
/// catches that case.
pub fn should_apply_now(
    severity: Severity,
    last_hook_at: &AtomicU64,
    in_flight: &AtomicU32,
    pending_age: Duration,
    quiet_window_secs: u64,
    max_defer_secs: u64,
) -> bool {
    if severity == Severity::Critical {
        return true;
    }

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let last = last_hook_at.load(Ordering::Relaxed);
    let idle_secs = now.saturating_sub(last);
    let live = in_flight.load(Ordering::Acquire);

    if idle_secs >= quiet_window_secs && live == 0 {
        return true;
    }

    if pending_age.as_secs() >= max_defer_secs {
        return true;
    }

    false
}

// ---------------------------------------------------------------------------
// Restart-loop rollback tracker
// ---------------------------------------------------------------------------

/// Tracks the most recent N daemon-binary startups so the supervisor's
/// restart-loop can be detected on a freshly-applied update. Persisted
/// at `~/.openlatch/restart-tracker.json`.
///
/// On every `main()` entry the tracker is read, pruned to entries
/// younger than 60 s, the current timestamp is appended, and the file
/// is written back. If the tracker has ≥ 3 entries AND the sentinel
/// AND the daemon-side `.bak` are all present, the rollback fires.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct RestartTracker {
    /// Unix-seconds timestamps of recent startups, oldest first.
    starts: Vec<u64>,
}

fn restart_tracker_path() -> PathBuf {
    crate::config::openlatch_dir().join("restart-tracker.json")
}

const RESTART_LOOP_THRESHOLD: usize = 3;
const RESTART_LOOP_WINDOW_SECS: u64 = 60;
const RESTART_TRACKER_CAP: usize = 10;

/// Update the restart tracker and report whether a rollback should
/// fire. Best-effort I/O — a write failure does not block startup, it
/// just degrades the next iteration's accuracy.
///
/// Returns `true` only when ALL of:
/// - ≥ `RESTART_LOOP_THRESHOLD` starts in the last `RESTART_LOOP_WINDOW_SECS`
/// - sentinel file exists (the most recent action was an update)
/// - daemon-side `<exe>.bak` exists (rollback target available)
///
/// `main()` calls this on every CLI invocation including `--version`
/// and `--help`, so the fast path returns after two `stat()` calls
/// (sentinel + bak) without touching the tracker JSON. Only a present
/// sentinel + bak warrants the full read-prune-append-write cycle.
pub fn should_rollback() -> bool {
    if !sentinel_path().exists() {
        return false;
    }
    let exe = match std::env::current_exe() {
        Ok(e) => e,
        Err(_) => return false,
    };
    if !exe.with_extension("bak").exists() {
        return false;
    }

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let path = restart_tracker_path();
    let mut tracker: RestartTracker = std::fs::read_to_string(&path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default();

    tracker
        .starts
        .retain(|t| now.saturating_sub(*t) <= RESTART_LOOP_WINDOW_SECS);
    tracker.starts.push(now);
    if tracker.starts.len() > RESTART_TRACKER_CAP {
        let drop_n = tracker.starts.len() - RESTART_TRACKER_CAP;
        tracker.starts.drain(0..drop_n);
    }

    if let Ok(body) = serde_json::to_string(&tracker) {
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let tmp = path.with_extension("json.tmp");
        if std::fs::write(&tmp, body).is_ok() && std::fs::rename(&tmp, &path).is_err() {
            // Tmp survived the failed rename; clean up so stray
            // .json.tmp files don't accumulate across restart loops.
            let _ = std::fs::remove_file(&tmp);
        }
    }

    tracker.starts.len() >= RESTART_LOOP_THRESHOLD
}

/// Roll the daemon and hook binaries back to the `.bak` siblings left
/// by [`perform_swap`]. Called from the very top of `main()` (BEFORE
/// any logging/telemetry init) when [`should_rollback`] returns true,
/// and also from the daemon's apply pipeline when a post-swap step
/// (e.g. `write_sentinel`) fails and the only safe recovery is to
/// undo the swap before surrendering the runtime.
///
/// **Order matters.** The hook is rolled back FIRST because
/// `fs::rename` on a non-running binary is the simplest possible
/// operation — fewer failure modes than `self_replace` on the live
/// daemon image (Windows AV/EDR locks, perms, ENOSPC). If the hook
/// rollback fails the daemon is never touched and the on-disk pair
/// stays coherent at the NEW version; the sentinel + `.bak` siblings
/// remain in place so the next supervisor restart retries cleanly.
///
/// On full success the sentinel AND the restart-tracker are deleted so
/// the next start is treated as a normal startup, not a fresh
/// post-update probe — clearing the tracker also prevents the stale
/// timestamps that triggered THIS rollback from poisoning a hotfix
/// or manual retry that lands inside the 60 s detection window.
pub fn rollback_from_bak() -> std::io::Result<()> {
    let cur = std::env::current_exe()?;
    let exe_bak = cur.with_extension("bak");

    // Step 1: hook first. If this fails the daemon is untouched and
    // the system stays in a coherent NEW state until the next retry.
    if let Ok(hook) = locate_hook_binary() {
        let hook_bak = hook.with_extension("bak");
        if hook_bak.exists() {
            std::fs::rename(&hook_bak, &hook)?;
        }
    }

    // Step 2: daemon. self_replace handles the running-binary file
    // lock on Windows by moving the in-memory image aside and
    // installing the rolled-back bytes at the original path.
    if exe_bak.exists() {
        self_replace::self_replace(&exe_bak)
            .map_err(|e| std::io::Error::other(format!("self_replace: {e}")))?;
        // self_replace consumes the source on success; the remove is a
        // belt-and-braces guard for platforms where it might leave a
        // residue.
        let _ = std::fs::remove_file(&exe_bak);
    }

    let _ = delete_sentinel();
    let _ = std::fs::remove_file(restart_tracker_path());
    Ok(())
}

#[cfg(test)]
mod p3_tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, AtomicU64};

    #[test]
    fn should_apply_now_critical_bypasses_everything() {
        let last = AtomicU64::new(0);
        let live = AtomicU32::new(5);
        // No matter what the activity counters say, Critical applies.
        // The current Unix time is always >> 0 so idle_secs is huge,
        // but the in_flight=5 should normally defer; Critical wins.
        assert!(should_apply_now(
            Severity::Critical,
            &last,
            &live,
            Duration::from_secs(0),
            60,
            86_400,
        ));
    }

    #[test]
    fn should_apply_now_normal_quiet_and_idle_applies() {
        // last_hook_at = 0 → idle_secs ≈ now (huge), passes 60s quiet.
        let last = AtomicU64::new(0);
        let live = AtomicU32::new(0);
        assert!(should_apply_now(
            Severity::Normal,
            &last,
            &live,
            Duration::from_secs(0),
            60,
            86_400,
        ));
    }

    #[test]
    fn should_apply_now_normal_in_flight_defers_within_cap() {
        let last = AtomicU64::new(0);
        let live = AtomicU32::new(1);
        assert!(!should_apply_now(
            Severity::Normal,
            &last,
            &live,
            Duration::from_secs(0),
            60,
            86_400,
        ));
    }

    #[test]
    fn should_apply_now_normal_recent_activity_defers_within_cap() {
        // last_hook_at = now → idle_secs == 0 < quiet_window.
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let last = AtomicU64::new(now);
        let live = AtomicU32::new(0);
        assert!(!should_apply_now(
            Severity::Normal,
            &last,
            &live,
            Duration::from_secs(0),
            60,
            86_400,
        ));
    }

    #[test]
    fn should_apply_now_normal_hard_cap_overrides_in_flight() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let last = AtomicU64::new(now);
        let live = AtomicU32::new(3);
        assert!(should_apply_now(
            Severity::Normal,
            &last,
            &live,
            Duration::from_secs(86_400),
            60,
            86_400,
        ));
    }

    #[test]
    fn restart_tracker_serialises_round_trip() {
        let mut t = RestartTracker::default();
        t.starts.push(100);
        t.starts.push(200);
        let json = serde_json::to_string(&t).unwrap();
        let back: RestartTracker = serde_json::from_str(&json).unwrap();
        assert_eq!(back.starts, vec![100, 200]);
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[tokio::test]
    async fn test_check_for_update_returns_none_for_nonexistent_package() {
        let result = check_for_update("__openlatch_nonexistent_pkg_xyz_9999__").await;
        let _ = result; // No panic, that's the contract.
    }

    #[test]
    fn version_at_least_handles_semver_correctly() {
        // 0.1.10 is GREATER than 0.1.9 — string comparison would get this wrong.
        assert!(version_at_least("0.1.10", "0.1.9"));
        assert!(version_at_least("0.2.0", "0.1.99"));
        assert!(version_at_least("1.0.0", "0.99.99"));

        // Strict less-than → false.
        assert!(!version_at_least("0.1.0", "0.2.0"));
        assert!(!version_at_least("0.1.9", "0.1.10"));

        // Equal → true (>= semantics).
        assert!(version_at_least("0.1.5", "0.1.5"));
    }

    #[test]
    fn version_at_least_returns_false_on_unparsable() {
        // Conservative: garbage input is treated as not-meeting-min so the
        // caller falls through to the manual recovery path instead of
        // silently bypassing the gate.
        assert!(!version_at_least("not-a-version", "0.1.0"));
        assert!(!version_at_least("0.1.0", "not-a-version"));
    }

    #[test]
    fn severity_from_str_opt_round_trip() {
        assert_eq!(Severity::from_str_opt("normal"), Some(Severity::Normal));
        assert_eq!(Severity::from_str_opt("critical"), Some(Severity::Critical));
        assert_eq!(Severity::from_str_opt("warning"), None);
        assert_eq!(Severity::from_str_opt(""), None);
        assert_eq!(Severity::Normal.as_str(), "normal");
        assert_eq!(Severity::Critical.as_str(), "critical");
    }

    #[test]
    fn platform_package_name_resolves_for_current_target() {
        // We only run tests on supported targets, so this should always
        // be Some.
        let name = platform_package_name();
        assert!(
            name.is_some(),
            "every CI target must have a platform package"
        );
        let n = name.unwrap();
        assert!(n.starts_with("@openlatch/client-"));
    }

    #[tokio::test]
    async fn download_tarball_rejects_non_sha512_integrity() {
        // Even though we never reach the network in this test (the
        // SRI parse fails before any HTTP send), the function signature
        // forces us to pass a URL — use a localhost address that will
        // never be reached.
        let err = download_tarball(
            "http://127.0.0.1:1/never",
            "sha256-abcd",
            Duration::from_secs(1),
        )
        .await
        .expect_err("must reject sha256 SRI");
        assert!(
            matches!(err, DownloadError::IntegrityFormat(_)),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn download_tarball_rejects_malformed_base64() {
        let err = download_tarball(
            "http://127.0.0.1:1/never",
            "sha512-not!valid!base64",
            Duration::from_secs(1),
        )
        .await
        .expect_err("must reject non-base64 hash");
        assert!(
            matches!(err, DownloadError::IntegrityFormat(_)),
            "got {err:?}"
        );
    }

    // ---- Hardened tar extraction ----

    /// Build a valid gzip-compressed tarball containing the host's
    /// required files plus any extra entries from `extra`. Each
    /// `(basename, bytes, entry_type)` triple is added to the tar.
    fn build_test_tarball(
        required_payload: &[u8],
        extra: &[(&str, &[u8], tar::EntryType)],
    ) -> Vec<u8> {
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        {
            let mut tb = tar::Builder::new(&mut gz);
            // Mimic npm's `package/` prefix to keep the test honest about
            // path stripping.
            let required = if cfg!(windows) {
                [
                    "package/openlatch.exe",
                    "package/openlatch-hook.exe",
                    "package/openlatch.exe.minisig",
                    "package/openlatch-hook.exe.minisig",
                ]
            } else {
                [
                    "package/openlatch",
                    "package/openlatch-hook",
                    "package/openlatch.minisig",
                    "package/openlatch-hook.minisig",
                ]
            };
            for path in required {
                let mut header = tar::Header::new_gnu();
                header.set_size(required_payload.len() as u64);
                header.set_mode(0o644);
                header.set_entry_type(tar::EntryType::Regular);
                header.set_cksum();
                tb.append_data(&mut header, path, required_payload).unwrap();
            }
            for (name, bytes, et) in extra {
                let mut header = tar::Header::new_gnu();
                header.set_size(bytes.len() as u64);
                header.set_mode(0o644);
                header.set_entry_type(*et);
                header.set_cksum();
                tb.append_data(&mut header, name, *bytes).unwrap();
            }
            tb.into_inner().unwrap();
        }
        gz.finish().unwrap()
    }

    #[test]
    fn extract_writes_required_files_by_basename() {
        let dir = tempfile::tempdir().unwrap();
        let payload = b"binary bytes";
        let tar = build_test_tarball(payload, &[]);
        extract_to_staging(&tar, dir.path()).expect("happy path must succeed");

        let required = if cfg!(windows) {
            [
                "openlatch.exe",
                "openlatch-hook.exe",
                "openlatch.exe.minisig",
                "openlatch-hook.exe.minisig",
            ]
        } else {
            [
                "openlatch",
                "openlatch-hook",
                "openlatch.minisig",
                "openlatch-hook.minisig",
            ]
        };
        for r in required {
            let p = dir.path().join(r);
            assert!(p.is_file(), "missing extracted file: {}", p.display());
            assert_eq!(std::fs::read(&p).unwrap(), payload);
        }
    }

    #[test]
    fn extract_rejects_traversal_basename() {
        // Build a tarball whose extra entry has a basename containing
        // ".." even after path stripping. The tar crate is fine with
        // such a path; our hardening must reject it before write.
        // We construct it manually because `append_data(path)` would
        // normalise the path and could strip the ..
        let dir = tempfile::tempdir().unwrap();
        let payload = b"x";
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        {
            let mut tb = tar::Builder::new(&mut gz);
            // Required files first so MissingRequired never fires.
            let required = if cfg!(windows) {
                [
                    "package/openlatch.exe",
                    "package/openlatch-hook.exe",
                    "package/openlatch.exe.minisig",
                    "package/openlatch-hook.exe.minisig",
                ]
            } else {
                [
                    "package/openlatch",
                    "package/openlatch-hook",
                    "package/openlatch.minisig",
                    "package/openlatch-hook.minisig",
                ]
            };
            for path in required {
                let mut header = tar::Header::new_gnu();
                header.set_size(payload.len() as u64);
                header.set_mode(0o644);
                header.set_entry_type(tar::EntryType::Regular);
                header.set_cksum();
                tb.append_data(&mut header, path, &payload[..]).unwrap();
            }
            // Now append a malicious entry whose basename literally
            // contains "../" — `append_data` accepts arbitrary path
            // strings.
            let mut h = tar::Header::new_gnu();
            h.set_size(payload.len() as u64);
            h.set_mode(0o644);
            h.set_entry_type(tar::EntryType::Regular);
            h.set_cksum();
            tb.append_data(&mut h, "package/openlatch..", &payload[..])
                .unwrap();
            tb.into_inner().unwrap();
        }
        let tar = gz.finish().unwrap();

        // The malicious entry's basename "openlatch.." contains "..",
        // hits the SuspiciousFilename guard. (The tar crate normalises
        // separators, so `package/..` would be filtered out earlier.)
        let res = extract_to_staging(&tar, dir.path());
        assert!(
            matches!(res, Err(ExtractError::SuspiciousFilename(_))),
            "got {res:?}"
        );
    }

    #[test]
    fn extract_rejects_duplicate_allowlisted_entry() {
        let dir = tempfile::tempdir().unwrap();
        let payload = b"y";
        // Add a duplicate of one of the required files under the same
        // basename. `append_data` lets us emit the same path twice.
        let dup_path = if cfg!(windows) {
            "package/openlatch.exe"
        } else {
            "package/openlatch"
        };
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        {
            let mut tb = tar::Builder::new(&mut gz);
            let required = if cfg!(windows) {
                [
                    "package/openlatch.exe",
                    "package/openlatch-hook.exe",
                    "package/openlatch.exe.minisig",
                    "package/openlatch-hook.exe.minisig",
                ]
            } else {
                [
                    "package/openlatch",
                    "package/openlatch-hook",
                    "package/openlatch.minisig",
                    "package/openlatch-hook.minisig",
                ]
            };
            for path in required {
                let mut header = tar::Header::new_gnu();
                header.set_size(payload.len() as u64);
                header.set_mode(0o644);
                header.set_entry_type(tar::EntryType::Regular);
                header.set_cksum();
                tb.append_data(&mut header, path, &payload[..]).unwrap();
            }
            let mut header = tar::Header::new_gnu();
            header.set_size(payload.len() as u64);
            header.set_mode(0o644);
            header.set_entry_type(tar::EntryType::Regular);
            header.set_cksum();
            tb.append_data(&mut header, dup_path, &payload[..]).unwrap();
            tb.into_inner().unwrap();
        }
        let tar = gz.finish().unwrap();
        let res = extract_to_staging(&tar, dir.path());
        assert!(
            matches!(res, Err(ExtractError::DuplicateEntry(_))),
            "got {res:?}"
        );
    }

    #[test]
    fn extract_rejects_oversize_entry() {
        let dir = tempfile::tempdir().unwrap();
        // Build a tarball where the header advertises ENTRY_SIZE_CAP+1
        // bytes for an allowlisted file. We use the writer's append
        // helpers to keep the gzip header valid; a real attacker can
        // hand-craft this without our help.
        let oversize = vec![0u8; (ENTRY_SIZE_CAP + 1) as usize];
        let path = if cfg!(windows) {
            "package/openlatch.exe"
        } else {
            "package/openlatch"
        };
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        {
            let mut tb = tar::Builder::new(&mut gz);
            let mut h = tar::Header::new_gnu();
            h.set_size(oversize.len() as u64);
            h.set_mode(0o644);
            h.set_entry_type(tar::EntryType::Regular);
            h.set_cksum();
            tb.append_data(&mut h, path, &oversize[..]).unwrap();
            tb.into_inner().unwrap();
        }
        let tar = gz.finish().unwrap();
        let res = extract_to_staging(&tar, dir.path());
        assert!(
            matches!(res, Err(ExtractError::EntryTooLarge)),
            "got {res:?}"
        );
    }

    #[test]
    fn extract_skips_non_regular_entries_silently() {
        // Add a symlink entry — must be skipped, not error. The required
        // files alone must still satisfy the presence check.
        let dir = tempfile::tempdir().unwrap();
        let payload = b"z";
        let tar = build_test_tarball(
            payload,
            &[("package/some-symlink", b"target", tar::EntryType::Symlink)],
        );
        extract_to_staging(&tar, dir.path()).expect("symlink entry must be silently skipped");
        // Symlink target must NOT appear on disk.
        assert!(!dir.path().join("some-symlink").exists());
    }

    #[test]
    fn extract_fails_when_required_file_missing() {
        // Build a tarball that drops the hook binary. The required-file
        // presence check must catch it.
        let dir = tempfile::tempdir().unwrap();
        let payload = b"only-daemon-here";
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        {
            let mut tb = tar::Builder::new(&mut gz);
            let path = if cfg!(windows) {
                "package/openlatch.exe"
            } else {
                "package/openlatch"
            };
            let sig_path = if cfg!(windows) {
                "package/openlatch.exe.minisig"
            } else {
                "package/openlatch.minisig"
            };
            for p in [path, sig_path] {
                let mut h = tar::Header::new_gnu();
                h.set_size(payload.len() as u64);
                h.set_mode(0o644);
                h.set_entry_type(tar::EntryType::Regular);
                h.set_cksum();
                tb.append_data(&mut h, p, &payload[..]).unwrap();
            }
            tb.into_inner().unwrap();
        }
        let tar = gz.finish().unwrap();
        let res = extract_to_staging(&tar, dir.path());
        assert!(
            matches!(res, Err(ExtractError::MissingRequired(_))),
            "got {res:?}"
        );
    }

    #[tokio::test]
    async fn download_tarball_verifies_against_real_sri() {
        // Build a tiny "tarball" + matching SRI, serve from a mockito
        // server, and verify the round trip. Then mutate one byte of the
        // expected SRI and assert IntegrityMismatch.
        use sha2::{Digest, Sha512};

        let payload = b"this-isn't-a-real-tar-but-the-bytes-don't-matter-for-sri";
        let mut hasher = Sha512::new();
        hasher.update(payload);
        let digest = hasher.finalize();
        let b64 = {
            use base64::engine::general_purpose::STANDARD;
            use base64::Engine;
            STANDARD.encode(digest)
        };
        let good_sri = format!("sha512-{b64}");

        let mut server = mockito::Server::new_async().await;
        let m = server
            .mock("GET", "/tarball.tgz")
            .with_status(200)
            .with_body(payload)
            .expect_at_least(1)
            .create_async()
            .await;
        let url = format!("{}/tarball.tgz", server.url());

        let bytes = download_tarball(&url, &good_sri, Duration::from_secs(5))
            .await
            .expect("good SRI must verify");
        assert_eq!(bytes, payload);

        // Flip the last byte of the digest to fail verification.
        let mut bad_digest: [u8; 64] = digest.into();
        bad_digest[63] ^= 0xff;
        let bad_b64 = {
            use base64::engine::general_purpose::STANDARD;
            use base64::Engine;
            STANDARD.encode(bad_digest)
        };
        let bad_sri = format!("sha512-{bad_b64}");
        let err = download_tarball(&url, &bad_sri, Duration::from_secs(5))
            .await
            .expect_err("mutated digest must fail");
        assert!(
            matches!(err, DownloadError::IntegrityMismatch),
            "got {err:?}"
        );
        m.assert_async().await;
    }

    #[test]
    fn parse_trusted_keys_strips_comments_and_blanks() {
        let input = "\
# heading comment
\n\
RWQg/8aFoqOdxLNNmlDoPgvFUcBgu6kNbR7yFSJxYVzL3JIyuNvmfTJX
   # indented comment

RWQfsAmblWLXIDfeq5BmgmJBfg7nGJZ08gCQpRVNZi5jw4cN77WhwhcK
RWQ123456THIRDKEY7890

RWQEXTRAKEYDROPPED
";
        let parsed = parse_trusted_keys(input);
        assert_eq!(
            parsed,
            vec![
                "RWQg/8aFoqOdxLNNmlDoPgvFUcBgu6kNbR7yFSJxYVzL3JIyuNvmfTJX".to_string(),
                "RWQfsAmblWLXIDfeq5BmgmJBfg7nGJZ08gCQpRVNZi5jw4cN77WhwhcK".to_string(),
                "RWQ123456THIRDKEY7890".to_string(),
            ],
            "expected exactly 3 keys with comments stripped and overflow truncated"
        );
    }

    #[test]
    fn parse_trusted_keys_empty_when_only_comments() {
        let input = "# comment one\n# comment two\n\n";
        assert!(parse_trusted_keys(input).is_empty());
    }

    /// Serializes the three tests below against each other.
    ///
    /// `OPENLATCH_TRUSTED_KEYS` is process-global: each of them sets it, reads
    /// it back, and removes it. Run in parallel (cargo's default) one test's
    /// `remove_var` lands between another's `set_var` and its read, and that
    /// one sees the baked key list instead of its own — an intermittent
    /// failure with nothing wrong in the code under test. Same idiom as
    /// `ENV_LOCK` in `cli/commands/lifecycle.rs`. Poison is ignored: a panic
    /// in one of these tests must not cascade into the others.
    static TRUSTED_KEYS_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn trusted_keys_env_override_when_set() {
        let _env = TRUSTED_KEYS_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        std::env::set_var("OPENLATCH_TRUSTED_KEYS", "KEY_A, KEY_B ,KEY_C");
        let keys = trusted_keys();
        std::env::remove_var("OPENLATCH_TRUSTED_KEYS");
        assert_eq!(
            keys,
            vec![
                "KEY_A".to_string(),
                "KEY_B".to_string(),
                "KEY_C".to_string()
            ]
        );
    }

    #[test]
    fn trusted_keys_env_override_blank_falls_through_to_baked() {
        let _env = TRUSTED_KEYS_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        std::env::set_var("OPENLATCH_TRUSTED_KEYS", "  ");
        let keys = trusted_keys();
        std::env::remove_var("OPENLATCH_TRUSTED_KEYS");
        // A blank env override must fall through to the baked file. The
        // committed `signing/openlatch.pub` always has at least the active
        // key on it, so this list is never empty in a built binary.
        // (When CI runs `cargo install` on crates.io with no key file
        // accessible, the bake fails at compile time — different failure
        // mode, not this test's concern.)
        assert!(
            !keys.is_empty(),
            "baked openlatch.pub should contain at least the active key; got {keys:?}"
        );
        // Sanity: keys are base64-shaped (no whitespace, no trailing comments).
        for k in &keys {
            assert!(!k.is_empty(), "trusted key entry must not be empty");
            assert!(
                !k.contains(' ') && !k.contains('#'),
                "trusted key entry leaked whitespace or a comment: {k:?}"
            );
        }
    }

    #[test]
    fn verify_returns_no_match_when_keys_dont_verify_signature() {
        // Build a fake .minisig with random non-base64 garbage; we only
        // need the decode to succeed for this test path. Easier: point at
        // a real signature with a key that doesn't match.
        // Approach: generate a random invalid signature string that the
        // minisign-verify decoder accepts structurally but no key matches.
        //
        // Since we cannot sign without a private key in pure-Rust deps,
        // this test instead asserts the no-trusted-keys path returns
        // Malformed (covered) and the malformed-signature path returns
        // Malformed (also covered). The end-to-end "wrong key" assertion
        // lives in tests/spike_update.rs with a real signing CLI shell-out.

        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("bin");
        let sig = dir.path().join("bin.minisig");
        std::fs::write(&bin, b"not a real binary").unwrap();
        std::fs::write(&sig, b"this is not a minisig").unwrap();

        let _env = TRUSTED_KEYS_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        std::env::set_var("OPENLATCH_TRUSTED_KEYS", "KEY_A");
        let res = verify_with_any_trusted_key(&bin, &sig);
        std::env::remove_var("OPENLATCH_TRUSTED_KEYS");
        assert!(matches!(res, Err(VerifyError::Malformed(_))), "got {res:?}");
    }

    #[test]
    fn sanity_check_version_reports_mismatch() {
        // Use the rust toolchain's `cargo --version` as an external
        // process whose stdout we can predict (it contains "cargo").
        // Asserting the negative path keeps the test platform-agnostic.
        let cargo = which_cargo();
        let res = sanity_check_version(&cargo, "definitely-not-the-version-string-9.9.9");
        assert!(
            matches!(res, Err(SanityError::VersionMismatch { .. })),
            "expected VersionMismatch, got {res:?}"
        );
    }

    #[test]
    fn sanity_check_version_accepts_match() {
        let cargo = which_cargo();
        // Every modern cargo prints a line starting with "cargo " — that
        // substring will be present.
        let res = sanity_check_version(&cargo, "cargo");
        assert!(res.is_ok(), "expected Ok, got {res:?}");
    }

    fn which_cargo() -> PathBuf {
        // CARGO env var is set by `cargo test` itself.
        std::env::var_os("CARGO")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("cargo"))
    }

    #[test]
    fn perform_swap_renames_hook_and_keeps_bak() {
        // Daemon-side self_replace would mutate the test binary on disk —
        // we skip that branch here by passing a path equal to the staging
        // exe so self_replace is essentially a no-op copy. We still want
        // to verify hook rename mechanics + handle return values.

        let dir = tempfile::tempdir().unwrap();
        let install = dir.path().join("install");
        std::fs::create_dir_all(&install).unwrap();

        let hook_path = install.join(if cfg!(windows) {
            "openlatch-hook.exe"
        } else {
            "openlatch-hook"
        });
        std::fs::write(&hook_path, b"OLD HOOK").unwrap();

        let staging = dir.path().join("staging");
        std::fs::create_dir_all(&staging).unwrap();
        let staging_hook = staging.join("new-hook");
        std::fs::write(&staging_hook, b"NEW HOOK").unwrap();

        // Use the test process's own binary as the "staging exe" and
        // self_replace it onto a *copy* — but self_replace targets
        // current_exe, which is the test runner. Replacing the running
        // test runner mid-test is too dangerous. Bypass step 3 by only
        // exercising steps 1 + 2 directly.

        let hook_bak = hook_path.with_extension("bak");
        std::fs::rename(&hook_path, &hook_bak).unwrap();
        std::fs::rename(&staging_hook, &hook_path).unwrap();

        assert_eq!(std::fs::read(&hook_path).unwrap(), b"NEW HOOK");
        assert_eq!(std::fs::read(&hook_bak).unwrap(), b"OLD HOOK");

        // Then exercise restore_from_bak.
        let handle = SwapHandle {
            current_exe: PathBuf::from("/dev/null"),
            current_exe_bak: PathBuf::from("/dev/null.bak"),
            hook_path: hook_path.clone(),
            hook_bak: hook_bak.clone(),
        };
        restore_from_bak(&handle).unwrap();

        assert_eq!(
            std::fs::read(&hook_path).unwrap(),
            b"OLD HOOK",
            "rollback should restore old hook bytes"
        );
        assert!(!hook_bak.exists(), "rollback should consume the .bak");
    }
}