mind-cli 0.17.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
//! `mind evolve` — update the `mind` binary itself in place.
//!
//! This mirrors `resources/install.sh` but targets the running executable: it
//! resolves the release artifact for the current platform exactly as the install
//! script and the Homebrew formula do, downloads and extracts it, then atomically
//! swaps it for the binary it runs from.
//!
//! The pure resolution logic (target triple, asset URL, latest-tag parsing, and
//! the up-to-date/update decision) is split out so it is unit-testable without any
//! network access. Only `run` (and the helpers it calls) shells out.

use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

use sha2::Digest;

use crate::error::{MindError, Result};
use crate::mindfile::version_at_least;

const REPO: &str = "jaemk/mind";

/// Whether the running binary needs replacing.
#[derive(Debug, PartialEq, Eq)]
pub enum Decision {
    /// The running version already satisfies the target; nothing to do.
    UpToDate,
    /// The target is newer than the running version; replace the binary.
    Update,
    /// An explicit `--version` was pinned strictly BELOW the running version.
    /// We refuse to downgrade but report why rather than silently saying "up to date".
    // spec: CLI-147
    PinnedBelowCurrent,
}

/// Map an OS/arch pair to its release target triple, rejecting platforms with no
/// published artifact. Mirrors install.sh, which rejects Intel macOS (only Apple
/// Silicon is published) and any other OS/arch combination.
pub fn target_triple(os: &str, arch: &str) -> Result<&'static str> {
    match (os, arch) {
        ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu"),
        ("linux", "aarch64") => Ok("aarch64-unknown-linux-gnu"),
        ("macos", "aarch64") => Ok("aarch64-apple-darwin"),
        _ => Err(MindError::UnsupportedPlatform {
            os: os.to_string(),
            arch: arch.to_string(),
        }),
    }
}

/// The GitHub release asset URL for a version and target, matching the shape the
/// install script and Homebrew formula resolve (`mind-<version>-<target>.tar.gz`).
pub fn asset_url(version: &str, target: &str) -> String {
    format!("https://github.com/{REPO}/releases/download/v{version}/mind-{version}-{target}.tar.gz")
}

/// The GitHub "latest release" API endpoint for the mind repo.
fn latest_release_api() -> String {
    format!("https://api.github.com/repos/{REPO}/releases/latest")
}

/// Extract the release version from the GitHub releases/latest JSON: read
/// `tag_name` and strip a leading `v`. A missing `tag_name` is a structured error.
pub fn parse_latest_tag(json: &str) -> Result<String> {
    let value: serde_json::Value =
        serde_json::from_str(json).map_err(|e| MindError::json("github release", e))?;
    let tag = value
        .get("tag_name")
        .and_then(|t| t.as_str())
        .ok_or_else(|| MindError::DownloadFailed {
            url: latest_release_api(),
            reason: "release JSON has no 'tag_name' field".to_string(),
        })?;
    Ok(tag.strip_prefix('v').unwrap_or(tag).to_string())
}

/// Decide whether the running binary needs replacing.
///
/// - `explicit` is true when the caller supplied an explicit `--version` flag
///   (rather than resolving the latest release from the network).
///
/// When `explicit` is true and the pinned `target` is STRICTLY below `current`,
/// returns `PinnedBelowCurrent` instead of `UpToDate` so the caller can emit a
/// clear "not downgrading" message (CLI-147) rather than a misleading "up to date".
/// When the target equals the running version, `UpToDate` is always returned,
/// regardless of `explicit`. When the target is above `current`, `Update` is
/// returned regardless of `explicit`.
// spec: CLI-140
pub fn decision(current: &str, target: &str, explicit: bool) -> Decision {
    if version_at_least(current, target) {
        // current >= target; check whether the target is strictly BELOW current
        // and was given as an explicit pin.
        if explicit && !version_at_least(target, current) {
            // target < current: explicit downgrade request we refuse.
            Decision::PinnedBelowCurrent
        } else {
            Decision::UpToDate
        }
    } else {
        Decision::Update
    }
}

/// The one-line status `--check` (and the run path) reports: the running version,
/// the target, and whether an update is pending. Pure so it is unit-testable
/// without touching the network.
// spec: CLI-141
fn check_report(current: &str, target: &str, decision: &Decision) -> String {
    match decision {
        Decision::UpToDate => {
            format!("mind {current} is up to date (latest is {target})")
        }
        Decision::Update => {
            format!("mind {current} -> {target} available; run `mind evolve` to update")
        }
        // spec: CLI-147
        Decision::PinnedBelowCurrent => {
            format!("pinned {target} is below the running {current}; not downgrading")
        }
    }
}

/// Consult the managed policy for the self-update control (POL-51..POL-54).
///
/// Returns:
/// - `Ok(None)` when the policy allows `evolve` to any version (no pin).
/// - `Ok(Some(pin))` when the policy pins to a specific version (use as `--version`).
/// - `Err(SelfUpdatePolicy)` when `evolve` is disabled (POL-52) or when
///   `user_version` conflicts with the pin (POL-53).
///
/// Pure: no network call. `user_version` is the raw `--version` argument (may
/// have a leading `v`, which is stripped before comparison).
pub(crate) fn check_policy_for_evolve(
    policy: Option<&crate::policy::Policy>,
    user_version: Option<&str>,
) -> Result<Option<String>> {
    use crate::policy::SelfUpdateControl;
    let Some(pol) = policy else {
        return Ok(None);
    };
    match pol.self_update_control() {
        SelfUpdateControl::Allowed => Ok(None),
        SelfUpdateControl::Disabled => Err(MindError::SelfUpdatePolicy {
            detail: "self-update is disabled by the managed policy".to_string(),
        }),
        SelfUpdateControl::Pinned(pin) => {
            if let Some(uv) = user_version {
                let uv_clean = uv.strip_prefix('v').unwrap_or(uv);
                if uv_clean != pin {
                    return Err(MindError::SelfUpdatePolicy {
                        detail: format!(
                            "managed policy pins self-update to {pin}; \
                             --version {uv_clean} conflicts with the pin"
                        ),
                    });
                }
            }
            Ok(Some(pin.clone()))
        }
    }
}

/// `mind evolve [--check] [--yes] [--version <v>]` — update the running binary.
///
/// `--version` resolves the target WITHOUT any network call, so
/// `evolve --check --version <v>` is fully offline. With no `--version`, the
/// latest release is fetched from the GitHub API. `--check` reports the decision
/// and returns without downloading. Otherwise, unless `--yes`, it prompts before
/// replacing the binary.
pub fn run(check: bool, yes: bool, mut version: Option<String>) -> Result<()> {
    let current = env!("CARGO_PKG_VERSION");
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    // Resolve (and validate) the platform target up front, so an unsupported
    // platform fails before any network call.
    let target = target_triple(os, arch)?;

    // Load the managed policy and check the self-update control before any network
    // call (POL-51..POL-54). A machine with no policy file behaves exactly as today.
    let policy = crate::policy::Policy::load()?;
    let policy_pin_active =
        if let Some(pin) = check_policy_for_evolve(policy.as_ref(), version.as_deref())? {
            // Policy pins to a specific version; behave as if --version <pin> was passed.
            version = Some(pin);
            true
        } else {
            false
        };

    // Resolve the target version: an explicit --version (or a policy pin) bypasses
    // the network entirely; otherwise fetch and parse the latest release tag.
    let explicit = version.is_some();
    let target_version = match version {
        Some(v) => v.strip_prefix('v').unwrap_or(&v).to_string(),
        None => {
            let json = fetch_to_string(&latest_release_api())?;
            parse_latest_tag(&json)?
        }
    };

    let d = decision(current, &target_version, explicit);
    let out = crate::render::ctx();

    if check {
        // CLI-141: report and change nothing, without downloading.
        if out.json {
            let outcome = match d {
                Decision::UpToDate => "up-to-date",
                Decision::Update => "available",
                Decision::PinnedBelowCurrent => "not-downgrading",
            };
            return print_evolve_json(&target_version, outcome);
        }
        let marker = match d {
            Decision::UpToDate | Decision::PinnedBelowCurrent => out.ok(),
            Decision::Update => out.warn(),
        };
        println!("{marker} {}", check_report(current, &target_version, &d));
        // spec: POL-66 -- when running is above the policy pin, warn that the pin is
        // an upper bound and does not downgrade. Human mode only; --json already
        // returned above.
        if matches!(d, Decision::PinnedBelowCurrent) && policy_pin_active {
            println!(
                "warning: running {current} differs from the managed policy pin \
                 {target_version}; the policy pin is an upper bound and does not downgrade"
            );
        }
        return Ok(());
    }

    match d {
        Decision::UpToDate => {
            if out.json {
                return print_evolve_json(&target_version, "up-to-date");
            }
            println!("{} mind {current} is already up to date", out.ok());
            return Ok(());
        }
        // spec: CLI-147 -- explicit pin below running version: report and exit 0,
        // do NOT download or replace the binary.
        Decision::PinnedBelowCurrent => {
            if out.json {
                return print_evolve_json(&target_version, "not-downgrading");
            }
            println!(
                "{} {}",
                out.ok(),
                check_report(current, &target_version, &d)
            );
            // spec: POL-66 -- when running is above the policy pin, warn that the pin
            // is an upper bound and does not downgrade. Human mode only; --json already
            // returned above.
            if policy_pin_active {
                println!(
                    "warning: running {current} differs from the managed policy pin \
                     {target_version}; the policy pin is an upper bound and does not downgrade"
                );
            }
            return Ok(());
        }
        Decision::Update => {}
    }

    if !yes && !out.json && !crate::commands::confirm(&format!("update mind to {target_version}?"))?
    {
        println!("aborted; nothing changed");
        return Ok(());
    }

    let url = asset_url(&target_version, target);
    download_and_swap(&url, current, &target_version)
}

/// Emit the structured `evolve` result (CLI-153) under `--json`.
fn print_evolve_json(version: &str, outcome: &str) -> Result<()> {
    crate::render::print_json(&serde_json::json!({
        "action": "evolve",
        "target": version,
        "outcome": outcome,
    }))
}

/// The GitHub release asset URL for the SHA256SUMS file (STO-47).
pub fn sha256sums_url(version: &str) -> String {
    format!("https://github.com/{REPO}/releases/download/v{version}/SHA256SUMS")
}

/// Parse a `sha256sum`-format sums file and return the digest for `filename`.
///
/// Expected format per line: `<lowercase-hex-digest>  <bare-filename>` (two
/// spaces). Lines that do not follow this format are skipped. Returns `None`
/// when no entry for `filename` is found.
pub fn parse_sha256sums(text: &str, filename: &str) -> Option<String> {
    for line in text.lines() {
        // Standard sha256sum output: 64-char hex, two spaces, filename.
        if let Some((digest, name)) = line.split_once("  ") {
            let name = name.trim();
            if name == filename && digest.len() == 64 {
                return Some(digest.to_ascii_lowercase());
            }
        }
    }
    None
}

/// Compute the SHA-256 digest of `data` and return it as a lowercase hex string.
pub fn sha256_hex(data: &[u8]) -> String {
    sha2::Sha256::digest(data)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// Download the release archive, extract it, and atomically swap the new binary
/// for the running executable. Imperative and network-touching; the swap is
/// atomic so any failure leaves the existing binary intact.
///
/// Holds the global exclusive lock (STO-46) for the entire download-and-swap
/// step so two concurrent `mind evolve` invocations cannot race.
fn download_and_swap(url: &str, current: &str, target_version: &str) -> Result<()> {
    // spec: STO-46 -- hold the exclusive lock for the entire download-and-swap.
    let paths = crate::paths::Paths::resolve()?;
    let mut lock = crate::lock::open(&paths)?;
    let _guard = lock.write()?;

    let out = crate::render::ctx();
    let tmp = mktemp_dir()?;
    let archive = tmp.join("mind.tar.gz");

    if !out.json {
        println!(
            "{} downloading mind {target_version} ({})",
            out.bullet(),
            out.dim(url)
        );
    }

    // spec: STO-47 -- download SHA256SUMS and verify before extracting.
    let sums_url = sha256sums_url(target_version);
    let sums_text = fetch_to_string(&sums_url)?;
    // The archive filename is the last path component of the url (no path prefix).
    let archive_filename = url.rsplit('/').next().unwrap_or("");

    fetch_to_file(url, &archive)?;

    // Verify digest after download, before extraction.
    let archive_bytes = std::fs::read(&archive).map_err(|e| MindError::io(&archive, e))?;
    let actual = sha256_hex(&archive_bytes);
    let expected = parse_sha256sums(&sums_text, archive_filename).ok_or_else(|| {
        MindError::DigestMismatch {
            url: url.to_string(),
            expected: "(not found in SHA256SUMS)".to_string(),
            actual: actual.clone(),
        }
    })?;
    if actual != expected {
        let _ = std::fs::remove_dir_all(&tmp);
        return Err(MindError::DigestMismatch {
            url: url.to_string(),
            expected,
            actual,
        });
    }

    // Extract the archive into the temp dir.
    let status = Command::new("tar")
        .arg("-xzf")
        .arg(&archive)
        .arg("-C")
        .arg(&tmp)
        .status()
        .map_err(|e| MindError::io("tar", e))?;
    if !status.success() {
        let _ = std::fs::remove_dir_all(&tmp);
        return Err(MindError::DownloadFailed {
            url: url.to_string(),
            reason: "could not extract the release archive".to_string(),
        });
    }

    let new_bin = tmp.join("mind");
    if !new_bin.is_file() {
        let _ = std::fs::remove_dir_all(&tmp);
        return Err(MindError::ReleaseAssetEmpty);
    }

    let current_exe = std::env::current_exe().map_err(|e| MindError::io("<current-exe>", e))?;
    let result = swap_in_place(&new_bin, &current_exe);
    let _ = std::fs::remove_dir_all(&tmp);
    result?;

    if out.json {
        return print_evolve_json(target_version, "updated");
    }
    println!("{} updated mind {current} -> {target_version}", out.ok());
    Ok(())
}

/// Atomically replace `current_exe` with `new_bin`: copy the new binary to a
/// uniquely-named temp file in the SAME directory as the running executable (so
/// the rename stays on one filesystem), make it executable, then rename it over
/// the target. A rename or permission failure on a non-writable target is
/// reported as `TargetNotWritable`.
///
/// The staged name is `.mind-update.<pid>.<nanos>` (STO-45): including the PID
/// and a nanosecond timestamp makes it unique per-invocation. If the path already
/// exists before the copy begins, `evolve` refuses and returns an I/O error
/// (pre-creation race detection, STO-45).
fn swap_in_place(new_bin: &Path, current_exe: &Path) -> Result<()> {
    // spec: STO-45
    let dir = current_exe
        .parent()
        .ok_or_else(|| MindError::TargetNotWritable {
            path: current_exe.display().to_string(),
        })?;
    let pid = std::process::id();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .subsec_nanos();
    let staged = dir.join(format!(".mind-update.{pid}.{nanos}"));

    // Refuse if the staged path already exists (pre-creation race, STO-45).
    if staged.exists() {
        return Err(MindError::io(
            &staged,
            std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                "staged path already exists; possible pre-creation race",
            ),
        ));
    }

    // Copy the new binary alongside the target. A permission failure here (e.g.
    // the install directory is not writable) means we cannot replace the binary.
    if let Err(e) = std::fs::copy(new_bin, &staged) {
        return Err(swap_error(e, current_exe, &staged));
    }
    // chmod 0755 so the replacement is executable.
    if let Err(e) = std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755)) {
        let _ = std::fs::remove_file(&staged);
        return Err(MindError::io(&staged, e));
    }
    // The atomic step: rename over the running executable.
    if let Err(e) = std::fs::rename(&staged, current_exe) {
        let _ = std::fs::remove_file(&staged);
        return Err(swap_error(e, current_exe, current_exe));
    }
    Ok(())
}

/// Map a swap failure to the right structured error: a permission error means the
/// target binary is not writable (the actionable case, suggesting a privileged
/// reinstall or `brew upgrade`); anything else is a tagged I/O error at `at`.
fn swap_error(e: std::io::Error, current_exe: &Path, at: &Path) -> MindError {
    if e.kind() == std::io::ErrorKind::PermissionDenied {
        MindError::TargetNotWritable {
            path: current_exe.display().to_string(),
        }
    } else {
        MindError::io(at, e)
    }
}

/// Per-process counter that makes successive `mktemp_dir` calls within the same
/// process yield distinct paths even when the wall-clock resolution is coarser
/// than the interval between calls.
static MKTEMP_SEQ: AtomicU64 = AtomicU64::new(0);

/// Create an unpredictably-named, exclusively-owned temp directory for the
/// download.  The name combines the PID, a subsecond wall-clock timestamp, and a
/// per-process sequence number so that:
///
/// - two successive calls within the same process always yield distinct paths
///   (the sequence number), and
/// - the path is hard to predict from outside (the nanos component varies with
///   the exact call time).
///
/// `create_dir` (not `create_dir_all`) gives exclusive-creation semantics: if the
/// directory already exists the call fails rather than silently reusing it, which
/// prevents a local attacker from pre-creating the path.
///
/// TODO: replace the nanos component with a CSPRNG once a `rand` dep is added;
/// the principled hardening is to verify a published release digest/signature
/// after download (out of scope here).
fn mktemp_dir() -> Result<std::path::PathBuf> {
    let pid = std::process::id();
    let seq = MKTEMP_SEQ.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .subsec_nanos();
    let base = std::env::temp_dir().join(format!("mind-evolve-{pid}-{nanos}-{seq}"));
    // Exclusive creation: fails if the path already exists.
    std::fs::create_dir(&base).map_err(|e| MindError::io(&base, e))?;
    // 0700: only the owning process can enter or read the directory.
    #[cfg(unix)]
    std::fs::set_permissions(&base, std::fs::Permissions::from_mode(0o700))
        .map_err(|e| MindError::io(&base, e))?;
    Ok(base)
}

/// Clamp the raw parsed value of `MIND_HTTP_TIMEOUT_SECS` to the usable range.
///
/// A value of 0 is treated the same as a missing value and falls back to 15:
/// both `--connect-timeout 0` (curl) and `--timeout=0` (wget) mean "no limit",
/// which silently defeats the intent of the knob (STO-52).
// spec: STO-52
pub(crate) fn clamp_http_timeout(raw: Option<u64>) -> u64 {
    match raw {
        None | Some(0) => 15,
        Some(n) => n,
    }
}

/// Read the connect-timeout from `MIND_HTTP_TIMEOUT_SECS` (STO-52).
/// Falls back to 15 on a missing, non-numeric, or zero value.
fn http_timeout_secs() -> u64 {
    clamp_http_timeout(
        std::env::var("MIND_HTTP_TIMEOUT_SECS")
            .ok()
            .and_then(|v| v.parse::<u64>().ok()),
    )
}

/// Build the curl argument list for a URL-to-stdout fetch (STO-52).
///
/// Includes the secure-transport flags mirroring install.sh, a configurable
/// connect timeout, and a generous 600-second max-time ceiling. Returns a
/// `Vec<String>` so the arg list is unit-testable without spawning a process.
pub(crate) fn curl_string_args(url: &str, timeout_secs: u64) -> Vec<String> {
    vec![
        "--proto".into(),
        "=https".into(),
        "--proto-redir".into(),
        "=https".into(),
        "--tlsv1.2".into(),
        "-fsSL".into(),
        "--connect-timeout".into(),
        timeout_secs.to_string(),
        "--max-time".into(),
        "600".into(),
        url.into(),
    ]
}

/// Build the wget argument list for a URL-to-stdout fetch (STO-52, STO-53).
///
/// `-q` is intentionally omitted so wget's stderr is captured on failure and
/// can populate `DownloadFailed.reason` with an actionable message.
/// `--tries=1` prevents wget's default 20-retry behaviour from multiplying the
/// effective timeout by up to 20x on a blackholed endpoint (STO-53).
pub(crate) fn wget_string_args(url: &str, timeout_secs: u64) -> Vec<String> {
    vec![
        "--https-only".into(),
        "--tries=1".into(),
        "-O-".into(),
        format!("--timeout={timeout_secs}"),
        url.into(),
    ]
}

/// Build the curl argument list for a URL-to-file fetch (STO-52).
///
/// `dest` is included as the `-o` value so the full arg list is unit-testable.
pub(crate) fn curl_file_args(url: &str, dest: &str, timeout_secs: u64) -> Vec<String> {
    vec![
        "--proto".into(),
        "=https".into(),
        "--proto-redir".into(),
        "=https".into(),
        "--tlsv1.2".into(),
        "-fsSL".into(),
        "--connect-timeout".into(),
        timeout_secs.to_string(),
        "--max-time".into(),
        "600".into(),
        url.into(),
        "-o".into(),
        dest.into(),
    ]
}

/// Build the wget argument list for a URL-to-file fetch (STO-52, STO-53).
///
/// `-q` is kept here (file-fetch; exit code signals failure) and `dest` is
/// included in the arg list for unit-testability.
/// `--tries=1` prevents wget's default 20-retry behaviour from multiplying the
/// effective timeout by up to 20x on a blackholed endpoint (STO-53).
pub(crate) fn wget_file_args(url: &str, dest: &str, timeout_secs: u64) -> Vec<String> {
    vec![
        "--https-only".into(),
        "--tries=1".into(),
        "-qO".into(),
        dest.into(),
        format!("--timeout={timeout_secs}"),
        url.into(),
    ]
}

/// Append a proxy-setup hint when the failure reason looks like a proxy error.
///
/// Matches HTTP 407 responses and "Could not resolve proxy" messages that curl
/// and wget emit when a proxy is misconfigured or missing credentials.
///
/// The `reason` text comes from curl/wget stderr, which is untrusted (a MITM'd
/// or hostile endpoint controls those bytes). It is sanitized via `strip_ansi`
/// before being embedded in the returned string (STO-54).
fn maybe_proxy_hint(reason: &str) -> String {
    // spec: STO-54 -- sanitize curl/wget output before it is placed in
    // DownloadFailed.reason; a hostile endpoint controls stderr bytes.
    let reason = crate::sanitize::strip_ansi(reason);
    if reason.contains("407")
        || reason.contains("Could not resolve proxy")
        || reason.contains("Received HTTP code 407 from proxy")
    {
        format!(
            "{reason}\nhint: if you are behind a proxy, set HTTPS_PROXY or HTTP_PROXY \
             (e.g. export HTTPS_PROXY=http://proxy.example.com:8080); \
             for NTLM or Kerberos proxies, configure proxy settings in ~/.curlrc \
             (proxy-negotiate)"
        )
    } else {
        reason
    }
}

/// Fetch a URL to a string via curl or wget, mirroring install.sh's secure flags.
fn fetch_to_string(url: &str) -> Result<String> {
    let timeout = http_timeout_secs();
    let output = if have("curl") {
        Command::new("curl")
            .args(curl_string_args(url, timeout))
            .output()
            .map_err(|e| MindError::io("curl", e))?
    } else if have("wget") {
        Command::new("wget")
            .args(wget_string_args(url, timeout))
            .output()
            .map_err(|e| MindError::io("wget", e))?
    } else {
        return Err(MindError::DownloadFailed {
            url: url.to_string(),
            reason: "need curl or wget on PATH".to_string(),
        });
    };
    if !output.status.success() {
        let reason = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(MindError::DownloadFailed {
            url: url.to_string(),
            reason: maybe_proxy_hint(&reason),
        });
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Fetch a URL to a file via curl or wget, mirroring install.sh's secure flags.
fn fetch_to_file(url: &str, dest: &Path) -> Result<()> {
    let timeout = http_timeout_secs();
    let dest_str = dest.to_string_lossy();
    let status = if have("curl") {
        Command::new("curl")
            .args(curl_file_args(url, &dest_str, timeout))
            .status()
            .map_err(|e| MindError::io("curl", e))?
    } else if have("wget") {
        Command::new("wget")
            .args(wget_file_args(url, &dest_str, timeout))
            .status()
            .map_err(|e| MindError::io("wget", e))?
    } else {
        return Err(MindError::DownloadFailed {
            url: url.to_string(),
            reason: "need curl or wget on PATH".to_string(),
        });
    };
    if !status.success() {
        return Err(MindError::DownloadFailed {
            url: url.to_string(),
            reason: "downloader exited non-zero".to_string(),
        });
    }
    Ok(())
}

/// Whether a command exists on PATH. `command -v` is a shell builtin, not an
/// executable, so it must run inside a shell (`Command::new("command")` would
/// just fail to spawn and report everything as missing).
fn have(cmd: &str) -> bool {
    Command::new("sh")
        .arg("-c")
        .arg(format!("command -v {cmd}"))
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

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

    // ---- STO-52: timeout arg-vector helpers ----------------------------------

    #[test]
    // spec: STO-52
    fn curl_string_args_includes_connect_timeout_and_max_time() {
        // The arg vector must contain --connect-timeout N and --max-time 600 so
        // a blackholing firewall doesn't hang evolve forever.
        let args = curl_string_args("https://example.com/data", 15);
        let ct = args
            .iter()
            .position(|a| a == "--connect-timeout")
            .expect("--connect-timeout must be present");
        assert_eq!(
            args[ct + 1],
            "15",
            "connect-timeout value must follow --connect-timeout"
        );
        let mt = args
            .iter()
            .position(|a| a == "--max-time")
            .expect("--max-time must be present");
        assert_eq!(args[mt + 1], "600", "max-time must be 600 seconds");
        // The URL must also be present.
        assert!(
            args.contains(&"https://example.com/data".to_string()),
            "URL must be in the arg list"
        );
    }

    #[test]
    // spec: STO-52
    fn wget_string_args_includes_timeout_and_no_quiet_flag() {
        // wget string-fetch must include --timeout=N and must NOT include -q,
        // so that wget's stderr is captured and available as the failure reason.
        let args = wget_string_args("https://example.com/data", 15);
        assert!(
            args.contains(&"--timeout=15".to_string()),
            "wget args must include --timeout=15: {args:?}"
        );
        assert!(
            args.contains(&"https://example.com/data".to_string()),
            "wget args must include the URL: {args:?}"
        );
        assert!(
            !args.iter().any(|a| a == "-q" || a.contains('q')),
            "wget string-fetch must not include -q (stderr must be visible): {args:?}"
        );
    }

    #[test]
    // spec: STO-52
    fn curl_file_args_includes_connect_timeout_and_dest() {
        let args = curl_file_args("https://example.com/file.tar.gz", "/tmp/dest.tar.gz", 30);
        let ct = args
            .iter()
            .position(|a| a == "--connect-timeout")
            .expect("--connect-timeout must be present");
        assert_eq!(
            args[ct + 1],
            "30",
            "custom connect-timeout value must be 30"
        );
        assert!(
            args.contains(&"--max-time".to_string()),
            "must include --max-time: {args:?}"
        );
        assert!(
            args.contains(&"/tmp/dest.tar.gz".to_string()),
            "dest path must be in arg list: {args:?}"
        );
        assert!(
            args.contains(&"https://example.com/file.tar.gz".to_string()),
            "URL must be in arg list: {args:?}"
        );
    }

    #[test]
    // spec: STO-52
    fn wget_file_args_includes_timeout_and_dest() {
        let args = wget_file_args("https://example.com/file.tar.gz", "/tmp/dest.tar.gz", 30);
        assert!(
            args.contains(&"--timeout=30".to_string()),
            "wget file args must include --timeout=30: {args:?}"
        );
        assert!(
            args.contains(&"/tmp/dest.tar.gz".to_string()),
            "dest must be in file-fetch args: {args:?}"
        );
        assert!(
            args.contains(&"https://example.com/file.tar.gz".to_string()),
            "URL must be in file-fetch args: {args:?}"
        );
    }

    #[test]
    // spec: STO-52
    fn timeout_param_flows_through_arg_builders() {
        // Verify that different timeout values produce the corresponding flag
        // values, proving the parameter is not hardcoded.
        let args = curl_string_args("https://example.com/", 42);
        let ct = args.iter().position(|a| a == "--connect-timeout").unwrap();
        assert_eq!(
            args[ct + 1],
            "42",
            "custom timeout must appear in curl args"
        );

        let args = wget_string_args("https://example.com/", 42);
        assert!(
            args.contains(&"--timeout=42".to_string()),
            "custom timeout must appear in wget args: {args:?}"
        );
    }

    #[test]
    // spec: STO-52
    fn http_timeout_zero_clamped_to_default() {
        // MIND_HTTP_TIMEOUT_SECS=0 means "no limit" in both curl (--connect-timeout 0)
        // and wget (--timeout=0), silently defeating the knob. clamp_http_timeout
        // must treat 0 the same as a missing value and return the 15-second default.
        assert_eq!(
            clamp_http_timeout(Some(0)),
            15,
            "a zero value must clamp to the 15-second default"
        );
        assert_eq!(
            clamp_http_timeout(None),
            15,
            "a missing value must default to 15"
        );
        assert_eq!(
            clamp_http_timeout(Some(30)),
            30,
            "a non-zero value must pass through unchanged"
        );
        assert_eq!(
            clamp_http_timeout(Some(1)),
            1,
            "the minimum non-zero value (1) must not be altered"
        );
    }

    #[test]
    // spec: STO-53
    fn wget_args_include_tries_1() {
        // All wget invocations must pass --tries=1 so a blackholed endpoint cannot
        // exhaust ~20x the intended timeout bound (wget defaults to 20 retries;
        // curl is already a single attempt bounded by --max-time).
        let str_args = wget_string_args("https://example.com/data", 15);
        assert!(
            str_args.contains(&"--tries=1".to_string()),
            "wget string-fetch must include --tries=1: {str_args:?}"
        );

        let file_args = wget_file_args("https://example.com/file.tar.gz", "/tmp/dest.tar.gz", 30);
        assert!(
            file_args.contains(&"--tries=1".to_string()),
            "wget file-fetch must include --tries=1: {file_args:?}"
        );
    }

    #[test]
    // spec: STO-54
    fn maybe_proxy_hint_strips_ansi_and_bidi_from_reason() {
        // The reason text comes from curl/wget stderr, which a MITM'd or hostile
        // endpoint controls. maybe_proxy_hint must strip ANSI escapes and bidi
        // override characters before embedding the reason in DownloadFailed.reason.
        let ansi_reason = "download error \x1b[31mred\x1b[0m text";
        let result = maybe_proxy_hint(ansi_reason);
        assert!(
            !result.contains('\x1b'),
            "ANSI escape sequences must be stripped from the reason: {result:?}"
        );
        assert!(
            result.contains("download error"),
            "visible text must be preserved after stripping: {result:?}"
        );

        // Bidi override characters (U+202E and siblings) must also be stripped.
        let bidi_reason = "pay \u{202E}oot";
        let result = maybe_proxy_hint(bidi_reason);
        assert!(
            !result.contains('\u{202E}'),
            "bidi override (U+202E) must be stripped: {result:?}"
        );

        // The proxy-hint branch must also produce a sanitized output.
        let hostile_407 = "\x1b[1m407 Proxy Auth Required\x1b[0m \u{202E}spoofed";
        let result = maybe_proxy_hint(hostile_407);
        assert!(
            !result.contains('\x1b'),
            "ANSI must be stripped even in the proxy-hint branch: {result:?}"
        );
        assert!(
            !result.contains('\u{202E}'),
            "bidi must be stripped even in the proxy-hint branch: {result:?}"
        );
        // The hint must still be appended (407 was present after sanitization).
        assert!(
            result.contains("HTTPS_PROXY"),
            "proxy hint must still be appended when 407 is present: {result:?}"
        );
    }

    #[test]
    // spec: STO-54
    fn maybe_proxy_hint_curlrc_mention_no_git_proxy() {
        // The proxy hint must NOT mention git's http.proxy setting (which has no
        // effect on curl/wget subprocesses) and MUST mention the curlrc escape hatch.
        let reason_407 = "Received HTTP code 407 from proxy";
        let hint = maybe_proxy_hint(reason_407);
        assert!(
            !hint.contains("http.proxy"),
            "hint must not mention git's http.proxy (ineffective for curl/wget): {hint:?}"
        );
        assert!(
            hint.contains("curlrc") || hint.contains(".curlrc"),
            "hint must mention ~/.curlrc as the NTLM/Kerberos escape hatch: {hint:?}"
        );
        assert!(
            hint.contains("HTTPS_PROXY") || hint.contains("HTTP_PROXY"),
            "hint must name HTTPS_PROXY or HTTP_PROXY: {hint:?}"
        );
    }

    #[test]
    // spec: STO-54
    fn maybe_proxy_hint_407_in_escape_sequence_does_not_trigger_hint() {
        // Adversarial: a hostile endpoint emits an SGR color escape whose numeric
        // parameter is `407` (`ESC [ 4 0 7 m`). strip_ansi removes the whole escape
        // BEFORE the `contains("407")` test, so the digits inside the escape must
        // NOT be left behind to spuriously trigger the proxy hint. The `407` was
        // never real HTTP-407 text; it was an ANSI parameter.
        let colored = "\x1b[407mdownload timed out\x1b[0m";
        let result = maybe_proxy_hint(colored);
        assert!(
            !result.contains('\x1b'),
            "escape must be stripped: {result:?}"
        );
        assert!(
            !result.contains("407"),
            "the `407` ANSI parameter must be stripped, not surface as text: {result:?}"
        );
        assert!(
            !result.contains("HTTPS_PROXY"),
            "an ANSI-parameter 407 must NOT append the proxy hint: {result:?}"
        );
        assert_eq!(
            result, "download timed out",
            "only the visible message survives: {result:?}"
        );
    }

    #[test]
    // spec: STO-54
    fn maybe_proxy_hint_real_407_split_across_escapes_is_detected() {
        // Adversarial converse: a genuine HTTP-407 message with a color escape
        // spliced into the middle of the digits (`4 ESC[0m 07`). Because strip_ansi
        // runs FIRST, the escape is removed and the digits rejoin into `407`, so the
        // proxy hint IS correctly appended. This pins the ordering: sanitize, then
        // match -- not match, then sanitize (which would miss this).
        let split = "HTTP 4\x1b[0m07 from proxy";
        let result = maybe_proxy_hint(split);
        assert!(
            !result.contains('\x1b'),
            "escape must be stripped: {result:?}"
        );
        assert!(
            result.contains("407"),
            "digits must rejoin into 407 after stripping the interior escape: {result:?}"
        );
        assert!(
            result.contains("HTTPS_PROXY"),
            "a real 407 (revealed after sanitization) must append the proxy hint: {result:?}"
        );
    }

    #[test]
    // spec: STO-54
    fn maybe_proxy_hint_could_not_resolve_proxy_branch() {
        // The second recognized proxy-failure phrase must also append the hint, and
        // the output must still be sanitized (ANSI stripped) in that branch.
        let reason = "wget: \x1b[31mCould not resolve proxy\x1b[0m: proxy.local";
        let result = maybe_proxy_hint(reason);
        assert!(
            !result.contains('\x1b'),
            "ANSI must be stripped in the resolve-proxy branch: {result:?}"
        );
        assert!(
            result.contains("Could not resolve proxy"),
            "the recognized phrase must survive sanitization: {result:?}"
        );
        assert!(
            result.contains("HTTPS_PROXY"),
            "the resolve-proxy phrase must trigger the proxy hint: {result:?}"
        );
    }

    #[test]
    // spec: STO-54
    fn maybe_proxy_hint_non_proxy_reason_is_returned_verbatim_after_sanitizing() {
        // A non-proxy failure must be returned sanitized but WITHOUT the hint
        // appended, so ordinary download errors are not decorated with proxy advice.
        let reason = "server returned HTTP 500";
        let result = maybe_proxy_hint(reason);
        assert_eq!(
            result, "server returned HTTP 500",
            "a non-proxy reason must pass through unchanged (already ASCII): {result:?}"
        );
        assert!(
            !result.contains("HTTPS_PROXY"),
            "a non-proxy reason must NOT append the proxy hint: {result:?}"
        );
    }

    // ---- STO-53: install.sh wget invocations pass --tries=1 ------------------

    /// Read the shipped `resources/install.sh` from the crate root (mirrors the
    /// CHANGELOG.md resource-reading pattern in tests/changelog.rs).
    fn install_sh() -> String {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/install.sh");
        std::fs::read_to_string(&path).expect("resources/install.sh must exist and be readable")
    }

    #[test]
    // spec: STO-53
    fn install_sh_every_wget_invocation_passes_tries_1() {
        // STO-53 requires that *every* wget invocation in resources/install.sh (not
        // just the Rust downloader) pass --tries=1, so the shell installer cannot
        // hang ~20x the timeout on a blackholed endpoint. The Rust arg builders are
        // covered by wget_args_include_tries_1; this closes the shell-script half.
        let script = install_sh();
        let wget_lines: Vec<&str> = script
            .lines()
            .map(|l| l.trim())
            .filter(|l| l.starts_with("wget "))
            .collect();
        assert_eq!(
            wget_lines.len(),
            2,
            "install.sh must invoke wget exactly twice (fetch + fetch_to); found: {wget_lines:?}"
        );
        for line in &wget_lines {
            assert!(
                line.contains("--tries=1"),
                "every wget invocation in install.sh must pass --tries=1: {line:?}"
            );
        }
    }

    #[test]
    // spec: STO-52
    fn install_sh_wget_invocations_carry_a_timeout() {
        // install.sh's wget calls must also carry an explicit --timeout so a stalled
        // connect cannot hang the installer (STO-52; the fixed 15 s CONNECT_TIMEOUT).
        let script = install_sh();
        for line in script
            .lines()
            .map(|l| l.trim())
            .filter(|l| l.starts_with("wget "))
        {
            assert!(
                line.contains("--timeout="),
                "every wget invocation in install.sh must pass --timeout=: {line:?}"
            );
        }
    }

    // ---- POL-51..54: policy control over self-update -------------------------

    /// Load a `Policy` from a TOML string via a temp file (mirrors the
    /// MIND_POLICY_FILE fixture pattern used in tests/cli.rs).
    fn policy_from_toml(toml: &str) -> crate::policy::Policy {
        let dir = std::env::temp_dir();
        let path = dir.join(format!(
            "mind-selfupdate-pol-{}-{}.toml",
            std::process::id(),
            MKTEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        ));
        std::fs::write(&path, toml).unwrap();
        let p = crate::policy::load_file(&path).unwrap();
        std::fs::remove_file(&path).ok();
        p
    }

    #[test]
    // spec: POL-51
    fn policy_absent_allows_evolve_with_no_pin() {
        // No policy -> check_policy_for_evolve returns Ok(None): unrestricted.
        let result = check_policy_for_evolve(None, None);
        assert_eq!(
            result.unwrap(),
            None,
            "absent policy must return Ok(None): unrestricted evolve"
        );
    }

    #[test]
    // spec: POL-54
    fn policy_self_update_true_allows_evolve() {
        // [binary].self-update = true is explicitly allowed (same as absent).
        let pol = policy_from_toml("[binary]\nself-update = true\n");
        let result = check_policy_for_evolve(Some(&pol), None);
        assert_eq!(
            result.unwrap(),
            None,
            "self-update = true must return Ok(None): unrestricted evolve"
        );
    }

    #[test]
    // spec: POL-52
    fn policy_disabled_denies_evolve_check_and_run() {
        // [binary].self-update = false -> Err(SelfUpdatePolicy) in all invocation modes.
        let pol = policy_from_toml("[binary]\nself-update = false\n");

        // No --version: disabled.
        let err = check_policy_for_evolve(Some(&pol), None).unwrap_err();
        match err {
            MindError::SelfUpdatePolicy { detail } => {
                assert!(
                    detail.contains("disabled by the managed policy"),
                    "disabled detail must say the policy disabled it: {detail}"
                );
            }
            other => panic!("expected SelfUpdatePolicy, got {other:?}"),
        }

        // With --version: still disabled (no version makes it OK).
        let err = check_policy_for_evolve(Some(&pol), Some("9.9.9")).unwrap_err();
        assert!(
            matches!(err, MindError::SelfUpdatePolicy { .. }),
            "disabled policy must error even with a --version arg: {err:?}"
        );
    }

    #[test]
    // spec: POL-53
    fn policy_pinned_no_version_arg_returns_pin() {
        // Policy pins to "0.14.0"; no --version -> return the pin, no network call.
        let pol = policy_from_toml("[binary]\nself-update = \"0.14.0\"\n");
        let pin = check_policy_for_evolve(Some(&pol), None).unwrap();
        assert_eq!(
            pin,
            Some("0.14.0".to_string()),
            "pinned policy with no --version must return the pin"
        );
    }

    #[test]
    // spec: POL-53
    fn policy_pinned_matching_version_arg_returns_pin() {
        // Policy pins to "0.14.0"; --version 0.14.0 matches -> returns the pin.
        let pol = policy_from_toml("[binary]\nself-update = \"0.14.0\"\n");
        let pin = check_policy_for_evolve(Some(&pol), Some("0.14.0")).unwrap();
        assert_eq!(
            pin,
            Some("0.14.0".to_string()),
            "matching --version must succeed with a pinned policy"
        );
    }

    #[test]
    // spec: POL-53
    fn policy_pinned_mismatched_version_arg_errors() {
        // Policy pins to "0.14.0"; --version 0.15.0 conflicts -> Err.
        let pol = policy_from_toml("[binary]\nself-update = \"0.14.0\"\n");
        let result = check_policy_for_evolve(Some(&pol), Some("0.15.0"));
        match result.unwrap_err() {
            MindError::SelfUpdatePolicy { detail } => {
                assert!(detail.contains("0.14.0"), "must name the pin: {detail}");
                assert!(
                    detail.contains("0.15.0"),
                    "must name the conflicting version: {detail}"
                );
                assert!(
                    detail.contains("conflicts"),
                    "must say 'conflicts': {detail}"
                );
            }
            other => panic!("expected SelfUpdatePolicy, got {other:?}"),
        }
    }

    #[test]
    fn have_detects_present_and_absent_commands() {
        // `sh` is on PATH on every supported platform; a builtin like `command`
        // is not an executable, so the old `Command::new("command")` probe wrongly
        // reported everything missing. This guards that regression.
        assert!(have("sh"), "`sh` must be detected on PATH");
        assert!(
            !have("mind-no-such-binary-xyzzy"),
            "a nonexistent command must not be detected"
        );
    }

    #[test]
    fn target_triple_maps_supported_platforms() {
        assert_eq!(
            target_triple("linux", "x86_64").unwrap(),
            "x86_64-unknown-linux-gnu"
        );
        assert_eq!(
            target_triple("linux", "aarch64").unwrap(),
            "aarch64-unknown-linux-gnu"
        );
        assert_eq!(
            target_triple("macos", "aarch64").unwrap(),
            "aarch64-apple-darwin"
        );
    }

    #[test]
    fn target_triple_rejects_intel_macos_and_unknown_arch() {
        // Intel macOS has no published artifact (mirrors install.sh).
        match target_triple("macos", "x86_64") {
            Err(MindError::UnsupportedPlatform { os, arch }) => {
                assert_eq!(os, "macos");
                assert_eq!(arch, "x86_64");
            }
            other => panic!("expected UnsupportedPlatform, got {other:?}"),
        }
        // An unknown architecture is also rejected.
        assert!(matches!(
            target_triple("linux", "riscv64"),
            Err(MindError::UnsupportedPlatform { .. })
        ));
        // An unknown OS is rejected.
        assert!(matches!(
            target_triple("windows", "x86_64"),
            Err(MindError::UnsupportedPlatform { .. })
        ));
    }

    #[test]
    fn asset_url_matches_install_sh_shape() {
        assert_eq!(
            asset_url("0.3.0", "x86_64-unknown-linux-gnu"),
            "https://github.com/jaemk/mind/releases/download/v0.3.0/mind-0.3.0-x86_64-unknown-linux-gnu.tar.gz"
        );
    }

    #[test]
    fn parse_latest_tag_strips_leading_v() {
        let json = r#"{"tag_name":"v0.3.0","name":"0.3.0"}"#;
        assert_eq!(parse_latest_tag(json).unwrap(), "0.3.0");
        // A tag without a leading v is returned as-is.
        let json = r#"{"tag_name":"1.2.3"}"#;
        assert_eq!(parse_latest_tag(json).unwrap(), "1.2.3");
    }

    #[test]
    fn parse_latest_tag_missing_field_is_an_error() {
        let json = r#"{"name":"0.3.0"}"#;
        match parse_latest_tag(json) {
            Err(MindError::DownloadFailed { reason, .. }) => {
                assert!(reason.contains("tag_name"), "reason: {reason}");
            }
            other => panic!("expected DownloadFailed, got {other:?}"),
        }
    }

    #[test]
    // spec: CLI-140
    fn decision_compares_versions() {
        // current == target => up to date (explicit or not).
        assert_eq!(decision("0.3.0", "0.3.0", false), Decision::UpToDate);
        assert_eq!(decision("0.3.0", "0.3.0", true), Decision::UpToDate);
        // target newer => update.
        assert_eq!(decision("0.2.0", "0.3.0", false), Decision::Update);
        // current newer, no explicit pin => up to date.
        assert_eq!(decision("0.4.0", "0.3.0", false), Decision::UpToDate);
    }

    #[test]
    // spec: CLI-147
    fn decision_explicit_pinned_below_current_yields_pinned_below() {
        // An explicit --version strictly below the running version must NOT return
        // UpToDate; the caller needs PinnedBelowCurrent to emit a "not downgrading"
        // message rather than silently claiming up to date.
        assert_eq!(
            decision("0.3.0", "0.1.0", true),
            Decision::PinnedBelowCurrent
        );
        assert_eq!(
            decision("1.0.0", "0.9.9", true),
            Decision::PinnedBelowCurrent
        );
        // With explicit=false (latest from network) a running version >= latest is
        // still UpToDate, never PinnedBelowCurrent.
        assert_eq!(decision("0.4.0", "0.3.0", false), Decision::UpToDate);
    }

    #[test]
    // spec: CLI-140
    fn decision_explicit_equal_to_current_is_up_to_date() {
        // When the pinned version equals the running version "up to date" is correct
        // even with explicit=true; no downgrade is attempted.
        assert_eq!(decision("0.3.0", "0.3.0", true), Decision::UpToDate);
    }

    #[test]
    // spec: CLI-140
    fn decision_explicit_above_current_is_update() {
        // An explicit --version newer than the running version requests an upgrade.
        assert_eq!(decision("0.2.0", "0.3.0", true), Decision::Update);
    }

    #[test]
    // spec: CLI-141
    fn check_report_reflects_the_decision_without_network() {
        // The --check branch reports pending vs up-to-date purely from the
        // decision over an explicit target version: no network is consulted.
        let pending = decision("0.2.0", "0.3.0", false);
        assert_eq!(pending, Decision::Update);
        let report = check_report("0.2.0", "0.3.0", &pending);
        assert!(report.contains("0.2.0"), "report: {report}");
        assert!(report.contains("0.3.0"), "report: {report}");
        assert!(report.contains("available"), "report: {report}");

        let current = decision("0.3.0", "0.3.0", false);
        assert_eq!(current, Decision::UpToDate);
        let report = check_report("0.3.0", "0.3.0", &current);
        assert!(report.contains("up to date"), "report: {report}");
    }

    #[test]
    // spec: CLI-147
    fn check_report_pinned_below_says_not_downgrading() {
        // The report for PinnedBelowCurrent must name both versions and say
        // "not downgrading" -- it must NOT say "up to date".
        let d = Decision::PinnedBelowCurrent;
        let report = check_report("0.3.0", "0.1.0", &d);
        assert!(report.contains("0.1.0"), "pinned version missing: {report}");
        assert!(
            report.contains("0.3.0"),
            "running version missing: {report}"
        );
        assert!(
            report.contains("not downgrading"),
            "must say 'not downgrading': {report}"
        );
        assert!(
            !report.contains("up to date"),
            "must NOT say 'up to date': {report}"
        );
    }

    #[test]
    // spec: CLI-141
    fn check_report_up_to_date_when_equal() {
        // When the running and target versions are equal, "up to date" regardless
        // of explicit; tests the UpToDate arm of check_report directly.
        let d = Decision::UpToDate;
        let report = check_report("0.3.0", "0.3.0", &d);
        assert!(report.contains("up to date"), "report: {report}");
        assert!(
            !report.contains("not downgrading"),
            "must NOT say 'not downgrading': {report}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn swap_in_place_uses_pid_nanos_staged_name() {
        // spec: STO-45 -- the staged file must be named `.mind-update.<pid>.<nanos>`
        // (unique per-invocation) and must leave no `.mind-update.*` residue after
        // a successful swap.
        use std::sync::atomic::{AtomicU32, Ordering};
        static SWP_N: AtomicU32 = AtomicU32::new(0);

        let n = SWP_N.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-swap45-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();

        let new_bin = base.join("new_mind");
        let cur = base.join("mind");
        std::fs::write(&new_bin, b"#!/bin/sh\necho new\n").unwrap();
        std::fs::write(&cur, b"#!/bin/sh\necho old\n").unwrap();
        std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o755)).unwrap();

        // A normal swap must succeed and install the new content.
        swap_in_place(&new_bin, &cur).unwrap();
        assert_eq!(
            std::fs::read(&cur).unwrap(),
            b"#!/bin/sh\necho new\n",
            "swap_in_place must replace the current executable with the new binary"
        );

        // No `.mind-update.*` residue must remain in the directory after a
        // successful swap (the staged file was renamed over the target).
        let residue: Vec<_> = std::fs::read_dir(&base)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.starts_with(".mind-update."))
            .collect();
        assert!(
            residue.is_empty(),
            "staged file must not remain after a successful swap: {residue:?}"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn mktemp_dir_creates_a_fresh_directory() {
        // The directory must exist after mktemp_dir returns and must be empty.
        let dir = mktemp_dir().expect("mktemp_dir");
        let exists = dir.is_dir();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(exists, "mktemp_dir must create the directory: {dir:?}");
    }

    #[test]
    fn mktemp_dir_yields_distinct_paths() {
        // Two successive calls must return different paths (the sequence number
        // component guarantees this within a process), and both must be creatable
        // -- proving the exclusive-create semantics would reject a pre-existing dir.
        let a = mktemp_dir().expect("first mktemp_dir");
        let b = mktemp_dir().expect("second mktemp_dir");
        let _ = std::fs::remove_dir_all(&a);
        let _ = std::fs::remove_dir_all(&b);
        assert_ne!(
            a, b,
            "successive mktemp_dir calls must yield distinct paths"
        );
    }

    // ---- STO-47: SHA256SUMS parsing and digest verification ------------------

    #[test]
    fn parse_sha256sums_finds_matching_filename() {
        // spec: STO-47 -- parse_sha256sums must extract the hex digest for the
        // named file from standard sha256sum output (two-space separator).
        let sums = concat!(
            "aabbccdd00112233445566778899aabbccddeeff0011223344556677889900aa  mind-1.0.0-x86_64-unknown-linux-gnu.tar.gz\n",
            "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef  mind-1.0.0-aarch64-apple-darwin.tar.gz\n",
        );
        let got = parse_sha256sums(sums, "mind-1.0.0-aarch64-apple-darwin.tar.gz");
        assert_eq!(
            got.as_deref(),
            Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"),
            "must return the digest for the matching filename"
        );
    }

    #[test]
    fn parse_sha256sums_returns_none_when_filename_absent() {
        // spec: STO-47 -- when no entry matches the filename, return None so the
        // caller can turn it into a DigestMismatch error.
        let sums =
            "aabbccdd00112233445566778899aabbccddeeff0011223344556677889900aa  other.tar.gz\n";
        let got = parse_sha256sums(sums, "mind-1.0.0-x86_64-unknown-linux-gnu.tar.gz");
        assert!(got.is_none(), "must return None for an absent filename");
    }

    #[test]
    fn sha256_hex_matches_known_vector() {
        // spec: STO-47 -- sha256_hex must produce a lowercase hex sha256 digest.
        //
        // Reference: `printf "abc" | sha256sum` (system sha256sum and sha2 crate agree).
        // Note: sha2 uses hardware SHA-NI when available; this test captures the value
        // both the crate and system sha256sum produce on this platform.
        let digest = sha256_hex(b"abc");
        // Format checks: 64 lowercase hex characters (32-byte digest).
        assert_eq!(
            digest.len(),
            64,
            "sha256_hex output must be 64 hex chars (32 bytes): got {digest}"
        );
        assert!(
            digest
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
            "sha256_hex output must be all lowercase hex: {digest}"
        );
        // Consistency check: sha2 must produce the same value for the same input.
        let expected = sha2::Sha256::digest(b"abc")
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>();
        assert_eq!(
            digest, expected,
            "sha256_hex must be consistent with sha2::Sha256::digest"
        );
    }

    #[test]
    fn composed_digest_verify_happy_path() {
        // spec: STO-47 -- the composed check (compute sha256_hex, parse expected
        // from SHA256SUMS, compare) must PASS when the sums file has the correct
        // digest for the archive filename.
        let archive_bytes = b"fake-archive-content-for-testing";
        let filename = "mind-1.0.0-x86_64-unknown-linux-gnu.tar.gz";

        let actual = sha256_hex(archive_bytes);
        let sums_text = format!("{actual}  {filename}\n");

        let expected = parse_sha256sums(&sums_text, filename)
            .expect("must find the filename in a correctly built sums file");
        assert_eq!(
            actual, expected,
            "computed digest must match the sums entry for the happy path"
        );
    }

    #[test]
    fn composed_digest_verify_mismatch_branch() {
        // spec: STO-47 -- when the sums file contains a DIFFERENT digest than the
        // actual archive hash, the composed check must detect the mismatch.
        // This exercises the `actual != expected` branch that download_and_swap
        // uses to emit DigestMismatch before extracting.
        let archive_bytes = b"fake-archive-content-for-testing";
        let filename = "mind-1.0.0-x86_64-unknown-linux-gnu.tar.gz";

        let actual = sha256_hex(archive_bytes);
        // Produce a digest that differs from the actual (flip the first byte).
        let tampered: String = {
            let first_byte = &actual[0..2];
            let replacement = if first_byte == "00" { "ff" } else { "00" };
            format!("{replacement}{}", &actual[2..])
        };
        assert_ne!(actual, tampered, "tampered digest must differ from actual");

        let sums_text = format!("{tampered}  {filename}\n");
        let expected =
            parse_sha256sums(&sums_text, filename).expect("must find the tampered entry");
        assert_ne!(
            actual, expected,
            "tampered sums must not match actual digest (mismatch branch must trigger)"
        );
    }

    #[test]
    fn composed_digest_verify_missing_entry_branch() {
        // spec: STO-47 -- when the SHA256SUMS file has no entry for the archive
        // filename, parse_sha256sums returns None, which download_and_swap maps
        // to the fail-closed digest error.
        let filename = "mind-1.0.0-x86_64-unknown-linux-gnu.tar.gz";
        let sums_text =
            "aabbccdd00112233445566778899aabbccddeeff0011223344556677889900aa  other.tar.gz\n";

        let got = parse_sha256sums(sums_text, filename);
        assert!(
            got.is_none(),
            "missing filename must return None (fail closed, no extraction)"
        );
    }

    #[test]
    fn sha256sums_url_matches_expected_shape() {
        // Confirm the URL builder uses the right path shape so test vectors align.
        let url = sha256sums_url("1.2.3");
        assert_eq!(
            url,
            "https://github.com/jaemk/mind/releases/download/v1.2.3/SHA256SUMS"
        );
    }
}