openlatch-provider 0.2.0

Self-service onboarding CLI + runtime daemon for OpenLatch Editors and Providers
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
//! Auto-update mechanism — verbatim port of `openlatch-client::core::update`
//! adjusted for the openlatch-provider single-binary topology.
//!
//! See `.claude/rules/auto-update.md` for the trust boundary, the 10
//! invariants, and the 12 forbidden patterns governing every change in this
//! module. The cross-repo parity audit (2026-05-07) demands this module
//! match openlatch-client's `core/update.rs` decision-by-decision; the
//! single deviation is that we have no `openlatch-hook` companion to swap
//! in lockstep with the daemon, so the swap pipeline drops the hook
//! handling and the tar allowlist drops to 4 entries (`openlatch-provider`
//! + `openlatch-provider.exe` + their `.minisig` siblings).
//!
//! Surface (mirrors openlatch-client symbol-for-symbol where applicable):
//!
//! - [`check_for_update`] — startup probe (returns the latest version
//!   string when newer; never errors out at startup).
//! - [`check`] — 3-phase npm registry probe returning a [`CheckResult`].
//! - [`platform_package_name`] / [`version_at_least`] — host-target +
//!   semver helpers.
//! - [`trusted_keys`] / [`verify_with_any_trusted_key`] — multi-key
//!   minisign verification against `signing/openlatch-provider.pub`.
//! - [`download_tarball`] — SHA-512 SRI verify (constant-time compare).
//! - [`extract_to_staging`] — hardened tar unpacker (8 invariants).
//! - [`sanity_check_version`] — runs `<staging> --version` and matches.
//! - [`perform_swap`] / [`restore_from_bak`] — single-binary atomic swap
//!   via `self_replace`.
//! - [`prepare_swap_artefacts`] / [`apply_local`] — full in-process apply
//!   pipeline used by the CLI's no-daemon path.
//! - [`should_apply_now`] — 5-row decision matrix consumed by the daemon
//!   worker (T2c).
//! - [`should_rollback`] / [`rollback_from_bak`] — supervisor-restart-loop
//!   rollback path called from the very top of `main()`.
//! - [`write_sentinel`] / [`read_sentinel`] / [`delete_sentinel`] —
//!   sentinel file at `~/.openlatch/provider/update-sentinel.json`.
//! - [`restart_into_new_binary`] — Unix execv / Windows spawn-detached.

#![allow(clippy::too_many_arguments)]

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

pub mod install_state;
pub mod worker;

// ---------------------------------------------------------------------------
// Startup-only npm-registry version check (cheap, lossy)
// ---------------------------------------------------------------------------

/// Lightweight check that returns the latest version string when one is
/// newer than `current_version`, or `None` otherwise. Errors are swallowed
/// — the check must never affect daemon startup.
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%2Fprovider/latest")
        .header("Accept", "application/json")
        .send()
        .await
        .ok()?;

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

    let body: serde_json::Value = resp.json().await.ok()?;
    let latest = body.get("version")?.as_str()?;
    (latest != current_version).then_some(latest.to_string())
}

// ---------------------------------------------------------------------------
// Trusted-key bake (`include_str!` per the cross-repo parity audit)
// ---------------------------------------------------------------------------

const TRUSTED_KEYS_FILE: &str = include_str!("../../signing/openlatch-provider.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_PROVIDER_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_PROVIDER_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
/// matching key on success — useful for rotation telemetry.
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-provider.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(())
}

// ---------------------------------------------------------------------------
// Atomic swap (single-binary — no companion hook)
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum SwapError {
    #[error("could not resolve current executable: {0}")]
    CurrentExe(#[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`].
#[derive(Debug, Clone)]
pub struct SwapHandle {
    /// Path the running binary lived at when the swap began.
    pub current_exe: PathBuf,
    /// Pre-swap snapshot at deterministic `<exe>.bak`.
    pub current_exe_bak: PathBuf,
}

/// Atomically swap the running binary to the staged version.
///
/// Order:
///
/// 1. `fs::copy(current_exe, current_exe.bak)` — captures the pre-swap
///    bytes at a deterministic path so the restart-loop rollback can find
///    them.
/// 2. `self_replace::self_replace(staging_exe)` — atomic on every
///    supported OS; on Windows it handles the running-binary file lock by
///    moving aside to a hidden `.<random>` sibling.
///
/// On any step-2 failure the `<exe>.bak` is removed so we don't leave a
/// stray binary behind. **Never pre-rename `current_exe`** — that defeats
/// `self_replace`'s own move-aside dance.
pub fn perform_swap(staging_exe: &Path) -> Result<SwapHandle, SwapError> {
    let current_exe = std::env::current_exe().map_err(SwapError::CurrentExe)?;
    let current_exe_bak = current_exe.with_extension("bak");

    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()
        )));
    }

    if let Err(e) = self_replace::self_replace(staging_exe) {
        let _ = std::fs::remove_file(&current_exe_bak);
        return Err(SwapError::SelfReplace(format!("{e}")));
    }

    Ok(SwapHandle {
        current_exe,
        current_exe_bak,
    })
}

/// Restore the running binary from its `.bak` sibling. The daemon-side
/// rollback (running-binary swap) is owned by [`rollback_from_bak`] —
/// this helper exists for symmetry with openlatch-client's surface.
pub fn restore_from_bak(handle: &SwapHandle) -> std::io::Result<()> {
    if handle.current_exe_bak.exists() {
        self_replace::self_replace(&handle.current_exe_bak)
            .map_err(|e| std::io::Error::other(format!("self_replace: {e}")))?;
        let _ = std::fs::remove_file(&handle.current_exe_bak);
    }
    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`.
#[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,
        }
    }

    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())
    }
}

#[derive(Debug, Clone)]
pub enum CheckResult {
    UpToDate {
        current: String,
    },
    Available {
        current: String,
        latest: String,
        severity: Severity,
        /// `min_supported_provider` declared by the new release. If the
        /// running version is older, apply is refused with OL-4259.
        min_supported: Option<String>,
        tarball_url: String,
        tarball_integrity: String,
    },
    Failed {
        reason: String,
    },
}

/// Map host target to npm platform package name.
pub fn platform_package_name() -> Option<&'static str> {
    if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
        Some("@openlatch/provider-darwin-arm64")
    } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
        Some("@openlatch/provider-darwin-x64")
    } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
        Some("@openlatch/provider-linux-x64")
    } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
        Some("@openlatch/provider-linux-arm64")
    } else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
        Some("@openlatch/provider-win32-x64")
    } else {
        None
    }
}

/// Returns true if `current >= min`. Both must parse as semver; either
/// failure is treated conservatively as `false`.
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,
    }
}

/// 3-phase manifest probe against the npm registry.
pub async fn check(current_version: &str, registry_origin: &str) -> CheckResult {
    use semver::Version;

    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}"),
            }
        }
    };

    let registry = registry_origin.trim_end_matches('/');
    let meta_url = format!("{registry}/@openlatch%2Fprovider/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(),
        };
    };

    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(),
        };
    }

    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,
        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(),
        };
    };

    if !http_head_ok(&client, &tarball_url).await {
        return CheckResult::Failed {
            reason: "platform tarball not yet reachable on registry CDN".into(),
        };
    }

    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_provider")
        .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
// ---------------------------------------------------------------------------

#[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 the npm
/// `dist.integrity` SRI string `"sha512-<base64>"`. Constant-time compare
/// via `subtle::ConstantTimeEq`.
pub async fn download_tarball(
    url: &str,
    sri: &str,
    timeout: Duration,
) -> Result<Vec<u8>, DownloadError> {
    use sha2::{Digest, Sha512};
    use subtle::ConstantTimeEq;

    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;
    STANDARD
        .decode(b64.as_bytes())
        .or_else(|_| STANDARD_NO_PAD.decode(b64.as_bytes()))
        .map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Hardened tar extraction (4-entry allowlist, single binary)
// ---------------------------------------------------------------------------

const ENTRY_SIZE_CAP: u64 = 64 * 1024 * 1024;

#[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),
}

/// Single-binary allowlist (4 entries — daemon binary + sig per host
/// naming). openlatch-client has 8 entries because of the openlatch-hook
/// companion; we have only the daemon, so the list is half the size.
const EXTRACT_ALLOWLIST: &[&str] = &[
    "openlatch-provider",
    "openlatch-provider.exe",
    "openlatch-provider.minisig",
    "openlatch-provider.exe.minisig",
];

/// Extract a gzip-compressed npm tarball into `staging_dir` with the
/// 8-invariant hardening contract from `.claude/rules/auto-update.md`.
pub fn extract_to_staging(tarball_bytes: &[u8], staging_dir: &Path) -> Result<(), ExtractError> {
    use std::io::Read;
    use tar::EntryType;

    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?;

        if entry.header().entry_type() != EntryType::Regular {
            continue;
        }
        if entry.size() > ENTRY_SIZE_CAP {
            return Err(ExtractError::EntryTooLarge);
        }

        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;
        };

        if basename.contains("..") || basename.contains('/') || basename.contains('\\') {
            return Err(ExtractError::SuspiciousFilename(basename.to_string()));
        }
        if !EXTRACT_ALLOWLIST.contains(&basename) {
            continue;
        }
        if !seen.insert(basename.to_string()) {
            return Err(ExtractError::DuplicateEntry(basename.to_string()));
        }

        let dest = staging_dir.join(basename);
        let mut out = std::fs::File::create(&dest)?;
        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);

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))?;
        }
    }

    let required: &[&str] = if cfg!(windows) {
        &["openlatch-provider.exe", "openlatch-provider.exe.minisig"]
    } else {
        &["openlatch-provider", "openlatch-provider.minisig"]
    };
    for r in required {
        if !staging_dir.join(r).exists() {
            return Err(ExtractError::MissingRequired((*r).to_string()));
        }
    }

    Ok(())
}

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

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UpdateSentinel {
    pub from: String,
    pub to: String,
    pub applied_at: String,
}

pub fn sentinel_path() -> PathBuf {
    crate::config::provider_dir().join("update-sentinel.json")
}

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(())
}

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
        }
    }
}

pub fn delete_sentinel() -> std::io::Result<()> {
    match std::fs::remove_file(sentinel_path()) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

/// Remove the `<exe>.bak` sibling left behind by [`perform_swap`] and
/// the `restart-tracker.json` so subsequent restarts start from a clean
/// slate. Called by the daemon's post-restart healthz probe (T2b) on
/// success.
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(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()`.
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;

        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;
        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
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApplyMode {
    Rpc,
    InProcess,
}

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

#[derive(Debug, Clone)]
pub struct ApplyOptions {
    pub current_version: String,
    pub registry_origin: String,
    pub download_timeout: Duration,
    pub force_cargo_install: bool,
    pub mode: ApplyMode,
}

impl ApplyOptions {
    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,
        }
    }
}

#[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",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateStatusKind {
    Idle,
    InProgress,
    Completed,
    Failed,
}

#[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,
        }
    }
}

#[derive(Debug, Clone)]
pub enum ApplyResult {
    Applied {
        from: String,
        to: String,
        severity: Severity,
        duration_ms: u64,
    },
    UpToDate {
        current: String,
    },
    RefusedCargoInstall {
        suggestion: String,
    },
    Failed {
        stage: ApplyStage,
        reason: String,
    },
}

pub struct SwapArtefacts {
    pub staging_dir: tempfile::TempDir,
    pub staging_exe: 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 staged artefacts or an [`ApplyResult`] short-circuit.
pub async fn prepare_swap_artefacts(opts: &ApplyOptions) -> Result<SwapArtefacts, ApplyResult> {
    use install_state::{detect_install_method, InstallMethod};

    if !opts.force_cargo_install && matches!(detect_install_method(), InstallMethod::CargoInstall) {
        let suggestion = "Run: cargo install --force --locked openlatch-provider".to_string();
        tracing::warn!(target: "update", "refusing to auto-update cargo-install binary");
        return Err(ApplyResult::RefusedCargoInstall { suggestion });
    }

    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 } => {
            return Err(ApplyResult::UpToDate { current });
        }
        CheckResult::Failed { reason } => {
            return Err(ApplyResult::Failed {
                stage: ApplyStage::Check,
                reason,
            });
        }
        CheckResult::Available {
            latest,
            severity,
            min_supported,
            tarball_url,
            tarball_integrity,
            ..
        } => (
            latest,
            severity,
            min_supported,
            tarball_url,
            tarball_integrity,
        ),
    };

    if let Some(ref min) = min_supported {
        if !version_at_least(&opts.current_version, min) {
            return Err(ApplyResult::Failed {
                stage: ApplyStage::Check,
                reason: format!(
                    "current version {} is older than min_supported_provider {} for release {} — manual `npm install -g @openlatch/provider@{}` required",
                    opts.current_version, min, latest, latest
                ),
            });
        }
    }

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

    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(),
            });
        }
    };

    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) = if cfg!(windows) {
        ("openlatch-provider.exe", "openlatch-provider.exe.minisig")
    } else {
        ("openlatch-provider", "openlatch-provider.minisig")
    };
    let staging_exe = staging_dir.path().join(exe_name);
    let staging_exe_sig = staging_dir.path().join(exe_sig_name);

    if let Err(e) = verify_with_any_trusted_key(&staging_exe, &staging_exe_sig) {
        tracing::warn!(
            target: "update",
            error = %e,
            stage = "verify",
            binary = "openlatch-provider",
            "signature verification failed"
        );
        return Err(ApplyResult::Failed {
            stage: ApplyStage::Verify,
            reason: format!("openlatch-provider verify: {e}"),
        });
    }

    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,
        from: opts.current_version.clone(),
        to: latest,
        severity,
    })
}

/// Apply an update entirely in the calling process — the CLI's no-daemon
/// fallback path. Composes [`prepare_swap_artefacts`] + [`perform_swap`]
/// + an `install-state.json` stamp.
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,
    };

    if let Err(e) = perform_swap(&artefacts.staging_exe) {
        return ApplyResult::Failed {
            stage: ApplyStage::Swap,
            reason: e.to_string(),
        };
    }

    let duration_ms = started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64;
    install_state::InstallState::stamp_for_running_binary(&artefacts.to);

    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 (5-row matrix, consumed by T2c worker)
// ---------------------------------------------------------------------------

/// 5-row decision matrix:
///
/// | severity | last_event age | in_flight | pending_age   | apply? |
/// |----------|----------------|-----------|---------------|--------|
/// | Critical | any            | any       | any           | yes    |
/// | Normal   | >= quiet       | 0         | any           | yes    |
/// | Normal   | >= quiet       | > 0       | < max_defer   | no     |
/// | Normal   | < quiet        | any       | < max_defer   | no     |
/// | Normal   | any            | any       | >= max_defer  | yes    |
pub fn should_apply_now(
    severity: Severity,
    last_event_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_event_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
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct RestartTracker {
    starts: Vec<u64>,
}

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

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

/// Returns true only when ALL of:
/// - >= 3 starts in the last 60 s,
/// - sentinel file exists,
/// - daemon-side `<exe>.bak` exists.
///
/// Fast path is two `Path::exists()` calls so a normal startup never
/// reads/writes 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() {
            let _ = std::fs::remove_file(&tmp);
        }
    }

    tracker.starts.len() >= RESTART_LOOP_THRESHOLD
}

/// Roll the running binary back to the `.bak` sibling left by
/// [`perform_swap`]. Called from the very top of `main()` BEFORE logging
/// init when [`should_rollback`] returns true. Uses `eprintln!` only.
pub fn rollback_from_bak() -> std::io::Result<()> {
    let cur = std::env::current_exe()?;
    let exe_bak = cur.with_extension("bak");

    if exe_bak.exists() {
        self_replace::self_replace(&exe_bak)
            .map_err(|e| std::io::Error::other(format!("self_replace: {e}")))?;
        let _ = std::fs::remove_file(&exe_bak);
    }

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

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

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

    #[test]
    fn parse_trusted_keys_strips_comments_and_blanks() {
        let input = "\
# heading comment

RWQ_FAKE_KEY_ONE
   # indented comment

RWQ_FAKE_KEY_TWO
RWQ_FAKE_KEY_THREE

RWQ_EXTRA_KEY_DROPPED
";
        let parsed = parse_trusted_keys(input);
        assert_eq!(
            parsed,
            vec![
                "RWQ_FAKE_KEY_ONE".to_string(),
                "RWQ_FAKE_KEY_TWO".to_string(),
                "RWQ_FAKE_KEY_THREE".to_string(),
            ],
        );
    }

    #[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());
    }

    #[test]
    fn version_at_least_handles_semver_correctly() {
        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"));
        assert!(!version_at_least("0.1.0", "0.2.0"));
        assert!(!version_at_least("0.1.9", "0.1.10"));
        assert!(version_at_least("0.1.5", "0.1.5"));
    }

    #[test]
    fn version_at_least_returns_false_on_unparsable() {
        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::Normal.as_str(), "normal");
        assert_eq!(Severity::Critical.as_str(), "critical");
    }

    #[test]
    fn platform_package_name_resolves_for_current_target() {
        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/provider-"));
    }

    #[tokio::test]
    async fn download_tarball_rejects_non_sha512_integrity() {
        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:?}"
        );
    }

    #[test]
    fn should_apply_now_critical_bypasses_everything() {
        let last = AtomicU64::new(0);
        let live = AtomicU32::new(5);
        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() {
        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() {
        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]);
    }
}