dev-prune 1.22.0

Universal, lockfile-safe workspace pruner and background dependency cleaner
Documentation
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
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Handler for `dev-prune update`, and the periodic release check behind it.
//
// The check is opt-*out*. An out-of-date cleanup tool is a tool whose safety fixes you do
// not have, so `devp update` asks GitHub for the latest release by default, and `devp
// run` / `devp status` repeat that quietly at most once a week. Both are switched off by
// `devp config set update_check false`, and `devp update --offline` skips a single run.
//
// What leaves the machine is one unauthenticated GET to the public releases page. It
// carries no identifier, no configuration, no repository paths and no usage data — the
// only thing the server learns is that some copy of dev-prune asked what the latest
// version is. Nothing else in the binary opens a socket. See `docs/PRIVACY.md`.
//
// Nothing is downloaded until someone says so: `devp update` asks `[y/N]` at a terminal
// when a newer release exists, `--install` (or `-y`) is the same answer given up front,
// and a copy run from a script gets the printed upgrade command and nothing else. The
// scheduled pass is never interrupted by an upgrade: it runs the managed copy under
// `<config>/bin`, which is replaced by atomic rename and refreshed from the new binary
// on the next healthy run (`setup::stable_exe_path`), so a pass already in flight keeps
// its loaded image and the next pass picks up the new one.

use std::cmp::Ordering;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use chrono::Utc;

use crate::channel::Channel;
use crate::config::Registry;
use crate::constants;
use crate::output;

pub fn run(offline: bool, install: bool, channels: bool, yes: bool) -> Result<()> {
    if install {
        return run_install();
    }
    if channels {
        return run_channels();
    }
    output::print_header("dev-prune version & upgrade");

    output::print_info(&format!("Installed version: v{}", constants::VERSION));

    let mut registry = Registry::load().ok();
    let mut newer = None;

    if offline {
        output::print_info("Skipping the release check because `--offline` was passed.");
    } else if let Some(reg) = registry.as_mut() {
        if reg.settings.update_check {
            // An explicit `devp update` always asks, regardless of when the last
            // automatic check ran — the user is standing there waiting for the answer.
            match refresh_latest(reg) {
                Ok(latest) => {
                    report_comparison(&latest);
                    if compare_versions(constants::VERSION, &latest) == Some(Ordering::Less) {
                        newer = Some(latest);
                    }
                }
                // A failed check is not a failed command. Someone offline, behind a
                // proxy, or hitting a rate limit still wants the upgrade instructions.
                // `:#` so the cause is printed under the label: "request failed" alone
                // once hid an HTTP 403 and sent a user looking at their network.
                Err(e) => output::print_warning(&format!(
                    "Could not check the latest release ({e:#}). The upgrade commands below still apply."
                )),
            }
            let _ = reg.save();
        } else {
            output::print_info(
                "The release check is off (`devp config set update_check true` re-enables it).",
            );
        }
    }

    println!();
    println!("  Latest releases:  {}", constants::RELEASES_URL);
    println!();

    // Under a pin, the upgrade command is the one command that undoes it. Printing it
    // here would answer "how do I upgrade this" with the wrong answer, so the pin is
    // what the section says instead.
    if registry.is_some_and(|r| r.settings.version_lock) {
        output::print_info(&locked_notice(None));
        return Ok(());
    }
    print_upgrade_commands();

    // The command already knows a newer release exists and how to fetch it, so making
    // the user retype it with `--install` was one round trip too many. The default is
    // still "no": Enter, a pipe, or a script leaves the binary exactly as it was.
    if let Some(latest) = newer
        && confirm_install(&latest, yes)
    {
        println!();
        return install_latest(&latest);
    }

    Ok(())
}

/// Ask whether to install `latest` right now. `yes` answers without asking.
///
/// Without a terminal on stdin the answer is silently "no": the upgrade command was
/// just printed, and a prompt nobody can answer would hang whatever called us.
fn confirm_install(latest: &str, yes: bool) -> bool {
    use std::io::{IsTerminal, Write};

    if yes {
        return true;
    }
    if !std::io::stdin().is_terminal() {
        return false;
    }
    eprint!("Install v{latest} now? [y/N]: ");
    if std::io::stderr().flush().is_err() {
        return false;
    }
    let mut input = String::new();
    if std::io::stdin().read_line(&mut input).is_err() {
        return false;
    }
    matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
}

/// The one sentence every refusal prints, so the pin and the way out of it always
/// arrive together.
///
/// A lock that silently does nothing is indistinguishable from an update path that has
/// broken, and "it stopped updating" is what people conclude when a tool goes quiet.
/// `latest` is passed on the paths that already know a newer release exists, because
/// "there is one, and you are deliberately not getting it" is a different fact from
/// "you are pinned".
pub(crate) fn locked_notice(latest: Option<&str>) -> String {
    let head = match latest {
        Some(latest) => format!("dev-prune v{latest} is out. "),
        None => String::new(),
    };
    format!(
        "{head}`version_lock` is on, so this copy stays at v{}. \
         `devp config set version_lock false` releases it.",
        constants::VERSION
    )
}

/// Ask GitHub right now — no interval — and say where the installed build stands.
///
/// For `devp init`, which is deliberate and infrequent enough to be worth a round trip:
/// setting a machine up is exactly the moment to learn the binary is a version behind.
/// `devp run` deliberately does not use this; it goes through [`notify_if_outdated`],
/// which is interval-gated so everyday work never waits on the network.
///
/// Returns `true` when the registry changed and needs saving.
pub fn check_now(registry: &mut Registry) -> bool {
    if !registry.settings.update_check {
        return false;
    }

    match refresh_latest(registry) {
        Ok(latest) => {
            report_comparison(&latest);
            if compare_versions(constants::VERSION, &latest) == Some(Ordering::Less) {
                print_upgrade_commands();
            }
        }
        // Not being able to reach GitHub is not a failed `init`.
        Err(e) => output::print_info(&format!("Could not check for a newer release ({e:#}).")),
    }
    true
}

/// Name the one command that upgrades *this* copy, and only fall back to the menu.
///
/// The old version printed all eight channels and told the reader to pick the one they
/// installed from. Nobody remembers that — it was a decision made once, possibly a year
/// ago, on a machine they have since reimaged. The channel is written in the path of the
/// running binary and `Channel::detect` already reads it, so asking the user to recall it
/// was asking for information dev-prune already had.
fn print_upgrade_commands() {
    let channel = Channel::detect();
    match channel.upgrade_command() {
        Some(command) => {
            println!("  Installed with {} — upgrade with:", channel.label());
            println!("    {command}");
            println!();
            println!("  Or `devp update --install` to let dev-prune do it for you.");
            println!();
            // Named, not printed. The channel above is the answer for this copy; the
            // rest of the table is for the reader who has a second machine, or who does
            // not believe the detection.
            println!("  `devp update --channels` lists the command for every channel.");
        }
        // `Unknown` means the binary sits somewhere no channel owns — a dev build, a
        // hand-copied file, a distro package. There is no manager to name, so this is the
        // one case where the full list is the honest answer.
        None => {
            println!("  This copy is not in a location any install channel owns, so there");
            println!("  is no package manager to name. Replace it in place with:");
            println!("    devp update --install");
            println!();
            println!("  Or install through a channel, which keeps it upgradeable:");
            print_every_upgrade_command();
        }
    }
}

/// `devp update --channels`: the whole table, and which row this copy is on.
///
/// Deliberately offline. The one question it answers — "what do I type to upgrade a
/// dev-prune installed through X" — does not depend on what the latest release is, and
/// making it wait on the network would make it useless on the machine where it is most
/// often needed.
fn run_channels() -> Result<()> {
    output::print_header("dev-prune upgrade commands");
    let current = Channel::detect();
    println!();
    println!("  This copy came from {}.", current.label());
    println!();
    print_every_upgrade_command();
    println!();
    output::print_info(
        "`devp update --install` replaces this copy directly, without the manager. \
         `devp install --channel <name>` moves it to a different one.",
    );
    Ok(())
}

/// Every channel's own upgrade command, one per line, widest label first.
///
/// Printed from the table rather than typed out. The version of this list that was typed
/// out named five channels of the nine that existed, and the copy the user was holding
/// had been installed through one of the four it did not mention.
fn print_every_upgrade_command() {
    let channels = [
        Channel::Installer,
        Channel::Cargo,
        Channel::Npm,
        Channel::Bun,
        Channel::Pnpm,
        Channel::Yarn,
        Channel::UvTool,
        Channel::Pipx,
        Channel::Pip,
        Channel::WinGet,
        Channel::Scoop,
        Channel::Homebrew,
    ];
    let width = channels.iter().map(|c| c.label().len()).max().unwrap_or(0);
    for channel in channels {
        if let Some(command) = channel.upgrade_command() {
            println!("    {:<width$}  {command}", channel.label());
        }
    }
}

/// `devp update --install`: upgrade this installation to the latest release.
///
/// Downloads the release binary from GitHub and replaces the files itself, rather than
/// asking whichever package manager delivered the first copy to do it. That inversion is
/// deliberate. There is exactly one binary that matters — the managed copy under
/// `<config>/bin`, which the git hooks, the scheduler and `PATH` all point at — and it
/// does not live inside `node_modules`, a uv tool directory or `~/.cargo/bin`. Asking
/// `uv` to upgrade a file it has never heard of was never going to work, and asking it to
/// upgrade its *own* copy left the one that actually runs untouched.
///
/// So both are replaced: the managed copy first, because that is what runs unattended,
/// then the running binary if it is a different file, because that is what the user
/// types. The channel's own bookkeeping (what `uv tool list` believes is installed) is
/// left stale on purpose — correcting it means running the channel's installer, which is
/// the one thing this route exists to avoid — and the command to resync it is printed.
///
/// Falls back to the channel's own upgrade command when there is no published binary for
/// this platform or the download fails, so a release-page outage costs the fast path and
/// not the upgrade.
fn run_install() -> Result<()> {
    output::print_header("dev-prune self-update");

    let mut registry = Registry::load()?;

    // Checked before the network is touched: a refusal the configuration already
    // guarantees should cost nothing and say why.
    if registry.settings.version_lock {
        anyhow::bail!("{}", locked_notice(None));
    }

    if crate::setup::offline_requested() {
        anyhow::bail!(
            "{} is set — an install needs the network by definition.",
            constants::ENV_OFFLINE
        );
    }

    // Know before downloading whether there is anything to download. A failed check is
    // fatal here (unlike `devp update`): running an installer blind would "upgrade" to
    // the version already installed.
    let latest = refresh_latest(&mut registry)?;
    let _ = registry.save();
    if compare_versions(constants::VERSION, &latest) != Some(Ordering::Less) {
        output::print_success(&format!(
            "v{} is already the latest release — nothing to install.",
            constants::VERSION
        ));
        // "Nothing to install" is about the console binaries. The scheduler twin can
        // still be behind them (the incident: consoles on the current release, devpw
        // three releases back, every scheduled pass silently running old code), so it
        // is reconciled even when there is nothing else to do.
        #[cfg(windows)]
        {
            let dirs = default_twin_dirs();
            let refs: Vec<&Path> = dirs.iter().map(|p| p.as_path()).collect();
            reconcile_windowless_twins(constants::VERSION, &refs);
        }
        return Ok(());
    }
    install_latest(&latest)
}

/// Replace the running binary with release `latest`, already known to be newer.
///
/// Shared by `--install` and by the `[y/N]` prompt at the end of plain `devp update`,
/// which has already fetched `latest` and checked the pin — this does not ask again.
fn install_latest(latest: &str) -> Result<()> {
    output::print_info(&format!("Upgrading v{} -> v{latest} …", constants::VERSION));

    let exe = std::env::current_exe().context("could not locate the running binary")?;
    let managed = crate::setup::managed_exe_path().ok();
    let channel = Channel::detect_at(&exe, managed.as_deref());

    match install_directly(latest, &exe, managed.as_deref(), channel) {
        Ok(()) => {
            output::print_success(&format!("dev-prune v{latest} installed."));
            report_channel_bookkeeping(channel);
            output::print_info(
                "The scheduled pass was not interrupted: it runs the managed copy, which \
                 was replaced by atomic rename, so a pass already in flight keeps the \
                 image it loaded and the next one picks up the new binary.",
            );
            return Ok(());
        }
        Err(e) => output::print_warning(&format!(
            "Direct download did not work ({e:#}).\nFalling back to the channel that \
             installed this copy."
        )),
    }

    // On Windows a running executable's file is locked against replacement but not
    // against rename. Moving it aside first lets the channel write a fresh file at the
    // real path; the `.old` left behind is swept up by the *next* run, when nothing is
    // executing it any more.
    #[cfg(windows)]
    let aside = {
        let aside = exe.with_extension("exe.old");
        let _ = fs::remove_file(&aside);
        fs::rename(&exe, &aside).ok().map(|_| aside)
    };

    let result = spawn_channel_upgrade(channel);

    #[cfg(windows)]
    if let Some(aside) = aside {
        if result.is_ok() {
            // Best effort: the file is still our running image, so Windows may refuse
            // the delete. The sweep at the top of the next `--install` gets it then.
            let _ = fs::remove_file(&aside);
        } else if !exe.exists() {
            // The upgrade never wrote a new binary — put the old one back so the
            // command the user has on PATH still exists.
            let _ = fs::rename(&aside, &exe);
        }
    }
    result?;

    output::print_success(&format!("dev-prune v{latest} installed."));
    output::print_info(
        "The scheduled pass was not interrupted: it runs the managed copy, which \
         refreshes itself from the new binary on its next run.",
    );
    Ok(())
}

/// Replace every copy of the binary this installation actually runs, from one download.
///
/// The managed copy is done first and is the only one whose failure aborts the upgrade:
/// it is what the scheduler and the git hooks invoke, so a machine with a fresh managed
/// copy is upgraded even if nothing else could be written.
///
/// Every other path is then written from the same verified bytes, and each is written
/// with the same rename-aside dance rather than through `ensure_alias`. That matters on
/// Windows: `ensure_alias` deletes the twin before relinking, and the delete fails when
/// the twin is the running image — which is exactly the case when the user typed `devp
/// update --install`. Renaming a running executable is allowed where deleting it is not,
/// so this route leaves no copy behind on the previous release.
fn install_directly(
    latest: &str,
    exe: &Path,
    managed: Option<&Path>,
    channel: Channel,
) -> Result<()> {
    let bytes = fetch_release_binary(latest)?;
    let primary = managed.unwrap_or(exe);
    install_bytes_at(&bytes, primary)?;

    // …except when a package manager owns the directory the running copy sits in and
    // replaces that directory wholesale on upgrade. Writing new bytes there leaves WinGet,
    // Scoop or Homebrew certain they still have the old version installed, and the next
    // `winget upgrade` puts the old binary back over the top. Their copy is left exactly
    // as the manager wrote it; `report_channel_bookkeeping` names the command that
    // actually moves it forward. A foreign tree — Volta, mise, Nix, the system package
    // manager — is the same ownership situation without a resync command to print:
    // overwriting a shim breaks the shim manager, and writing into `/nix/store` or
    // `/usr/bin` desyncs a store this tool cannot correct. Its copy is left alone too.
    let replace_exe_dir = primary != exe && exe.is_file() && !manager_owns_exe_dir(channel);
    for path in companion_copies(primary, managed.is_some(), exe, replace_exe_dir) {
        if let Err(e) = install_bytes_at(&bytes, &path) {
            output::print_warning(&format!(
                "The managed copy is now v{latest}, but {} could not be replaced ({e:#}). Until it \
                 is, that copy runs the previous version whenever it is the one invoked.",
                path.display()
            ));
        }
    }

    // The console binaries are now on `latest`; the scheduler twin must not be left
    // behind them. It is a separate `[[bin]]` image, so it cannot be written from the
    // bytes above: it gets its own verified download, and only where a twin already
    // exists.
    #[cfg(windows)]
    {
        let mut dirs: Vec<&Path> = Vec::new();
        if let Some(dir) = primary.parent() {
            dirs.push(dir);
        }
        if replace_exe_dir && let Some(dir) = exe.parent() {
            dirs.push(dir);
        }
        reconcile_windowless_twins(latest, &dirs);
    }

    // Still worth running for the copy `get_exe_path` resolves when that is neither
    // the managed directory nor the running one. `place_windowless_twin` never
    // regresses a twin past what sits beside the running binary, so after the
    // reconcile above this can only move a stale copy forward.
    crate::daemon::refresh_windowless_twin();

    // The receipt beside the managed copy now names the version that was there a minute
    // ago. Only ever updated, never created: this path also upgrades a managed copy some
    // other manager installed, and writing a fresh receipt there would claim one of our
    // installers ran when none did.
    crate::receipt::refresh_after_upgrade(latest);
    Ok(())
}

/// True when a package manager owns the running copy's directory outright, so no file
/// in it may be rewritten: the versioned-directory trio, which swaps the whole
/// directory on upgrade, and a foreign manager's tree — a shim, a Nix store path, a
/// system package — whose contents dev-prune has no command to resync afterwards.
fn manager_owns_exe_dir(channel: Channel) -> bool {
    channel.replaces_its_directory() || matches!(channel, Channel::Foreign(_))
}

/// Every other file that is a copy of the binary being replaced — both public names,
/// in both directories that hold one.
///
/// Left alone, a copy keeps running the previous release silently, because the
/// scheduler and the hooks both discard their own output by design. `devp` is a full
/// second executable rather than a link, so a directory that holds one name usually
/// holds the other. The managed directory owns both names outright and gets both
/// written whether they exist yet or not; the running copy's directory belongs to
/// whatever put the binary there, so only files already present are touched.
///
/// Both names, deliberately: through 1.12.0 this list held only the primary's `devp`
/// twin plus the running file itself, so `devp update --install` typed at a
/// cargo-installed `devp` upgraded everything except the `dev-prune` sitting beside
/// it — the exact silent staleness the list exists to prevent.
fn companion_copies(
    primary: &Path,
    primary_is_managed: bool,
    exe: &Path,
    replace_exe_dir: bool,
) -> Vec<PathBuf> {
    let names: [&str; 2] = if cfg!(windows) {
        ["dev-prune.exe", "devp.exe"]
    } else {
        ["dev-prune", "devp"]
    };
    let mut also: Vec<PathBuf> = Vec::new();
    if let Some(dir) = primary.parent() {
        for name in names {
            let twin = dir.join(name);
            if twin != primary && (primary_is_managed || twin.is_file()) {
                also.push(twin);
            }
        }
    }
    if replace_exe_dir {
        if !also.contains(&exe.to_path_buf()) {
            also.push(exe.to_path_buf());
        }
        if let Some(dir) = exe.parent() {
            for name in names {
                let twin = dir.join(name);
                if twin != *exe && twin != primary && twin.is_file() && !also.contains(&twin) {
                    also.push(twin);
                }
            }
        }
    }
    also
}

/// Name the channel's own upgrade command after a direct install, for the one thing the
/// direct route deliberately leaves untouched: the manager's record of what it installed.
fn report_channel_bookkeeping(channel: Channel) {
    // A foreign manager's copy was left alone the same way the trio's is, but there is
    // no resync command to name — dev-prune does not know how to drive Volta, mise or
    // Nix. Saying nothing here read as "everything was replaced", which is exactly what
    // did not happen to that copy.
    if let Channel::Foreign(manager) = channel {
        output::print_info(&format!(
            "The managed copy is now v{}. The copy that {manager} installed was left \
             exactly as it wrote it — replacing a file inside a manager-owned tree only \
             makes {manager} and the disk disagree. Upgrade that copy through {manager} \
             itself.",
            constants::VERSION
        ));
        return;
    }
    // The installer's copy *is* the managed one, and an unrecognised copy has no manager
    // keeping a version record that could disagree with the binary.
    let Some(resync) = channel
        .owns_its_files()
        .then(|| channel.upgrade_command())
        .flatten()
    else {
        return;
    };
    if channel.replaces_its_directory() {
        output::print_info(&format!(
            "The managed copy is now v{}. The copy {} installed was left exactly as it \
             wrote it — replacing a file inside a versioned package directory only makes \
             the manager and the disk disagree. Run `{resync}` to move that one forward \
             too.",
            constants::VERSION,
            channel.label()
        ));
    } else {
        output::print_info(&format!(
            "The binaries are up to date. `{resync}` also updates that manager's own \
             record of the version, which still reads v{}.",
            constants::VERSION
        ));
    }
}

/// Download release `version`'s binary for this platform and put it at `target`.
///
/// The direct route, and the reason `devp update --install` no longer depends on the
/// package manager that happened to deliver the first copy. Whatever installed it, the
/// binary the hooks, the scheduler and `PATH` all point at is one file in the config
/// directory, and this replaces that file. `uv`, `npm` and `cargo` are delivery
/// channels; they are not the source of truth, and asking one of them to upgrade a file
/// living under another one's directory was never going to work.
///
/// Refuses to install anything whose SHA-256 does not match the sidecar published beside
/// it. That check is the entire safety story for this path: the bytes are about to
/// become the binary the machine runs on a schedule.
fn fetch_release_binary(version: &str) -> Result<Vec<u8>> {
    let asset = constants::release_asset_name(version).with_context(|| {
        format!(
            "no published binary for {}-{}; upgrade through the channel that installed \
             this copy instead",
            std::env::consts::OS,
            std::env::consts::ARCH
        )
    })?;
    fetch_verified_asset(version, &asset)
}

/// Download release `version`'s windowless scheduler binary, verified the same way.
///
/// Separate from [`fetch_release_binary`] because it is a different asset with its own
/// sidecar, not a different verification story: the scheduled task runs these bytes
/// unattended, which is exactly why they get the same checksum gate as the console
/// binary.
#[cfg(windows)]
fn fetch_windowless_binary(version: &str) -> Result<Vec<u8>> {
    let asset = constants::windowless_release_asset_name(version).with_context(|| {
        format!(
            "no published windowless binary for windows-{}",
            std::env::consts::ARCH
        )
    })?;
    fetch_verified_asset(version, &asset)
}

/// The shared tail of every asset download: fetch the `.sha256` sidecar, fetch the
/// bytes, and refuse them unless the digests match.
fn fetch_verified_asset(version: &str, asset: &str) -> Result<Vec<u8>> {
    let base = format!("{}/v{version}/{asset}", constants::RELEASE_DOWNLOAD_BASE);

    let expected = fetch_expected_hash(&format!("{base}.sha256"))?;
    output::print_info(&format!("Downloading {asset} …"));
    let bytes = fetch_bytes(&base)?;

    let actual = {
        use sha2::{Digest, Sha256};
        use std::fmt::Write as _;
        let mut h = Sha256::new();
        h.update(&bytes);
        // Hex-encoded by hand: sha2 0.11 returns a `hybrid_array::Array`, which has no
        // `LowerHex`, and the sidecar is lower-case hex either way.
        h.finalize().iter().fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        })
    };
    if actual != expected {
        anyhow::bail!(
            "checksum mismatch for {asset}\n  expected {expected}\n  got      {actual}\n\
             The download was corrupted or tampered with; nothing was installed."
        );
    }

    Ok(bytes)
}

/// What one reconcile pass over the windowless twins amounted to.
#[cfg(windows)]
enum TwinReconcile {
    /// Every twin that exists is already on `version`, or none exists at all.
    UpToDate,
    /// At least one stale twin was replaced and none failed.
    Updated,
    /// The download or a write failed; the message has already been printed.
    Failed(String),
}

/// Bring every existing `devpw.exe` in `dirs` up to release `version`.
///
/// The upgrade path used to refresh the twin from the devpw *beside* the running
/// binary, but that copy is the previous delivery's: the console binaries moved forward
/// and the scheduled task kept running the old release, silently, every night. So the
/// twin is reconciled against the release itself: any copy whose build stamp is older
/// than `version`, or missing entirely (built before 1.17.0), is replaced from a
/// checksum-verified download of the published `devpw` asset.
///
/// Only existing files are touched. An installation that never had a windowless twin
/// does not grow one here; `devp daemon install` is what creates one, and the npm
/// family ships its own under a different mechanism.
#[cfg(windows)]
fn reconcile_windowless_twins(version: &str, dirs: &[&Path]) -> TwinReconcile {
    let mut stale: Vec<PathBuf> = Vec::new();
    for dir in dirs {
        let twin = dir.join(constants::WINDOWS_WINDOWLESS_BIN);
        if stale.contains(&twin) || !twin.is_file() {
            continue;
        }
        let stamped = fs::read(&twin)
            .ok()
            .and_then(|b| crate::commands::trust::version_from_stamp(&b));
        // Equal or newer is left alone; the twin never regresses. A copy with no
        // readable stamp predates stamping and is by definition behind.
        let up_to_date = stamped
            .as_deref()
            .and_then(|v| compare_versions(v, version))
            .is_some_and(|o| o != Ordering::Less);
        if !up_to_date {
            stale.push(twin);
        }
    }
    if stale.is_empty() {
        return TwinReconcile::UpToDate;
    }

    let bytes = match fetch_windowless_binary(version) {
        Ok(b) => b,
        Err(e) => {
            let why = format!(
                "The scheduler binary {} could not be downloaded ({e:#}). The scheduled \
                 pass keeps running the version it has until `devp update --install` or \
                 `devp doctor --fix` succeeds.",
                constants::WINDOWS_WINDOWLESS_BIN
            );
            output::print_warning(&why);
            return TwinReconcile::Failed(why);
        }
    };

    let mut failed = None;
    for twin in &stale {
        if let Err(e) = install_bytes_at(&bytes, twin) {
            let why = format!(
                "{} could not be replaced ({e:#}); the scheduled pass keeps running the \
                 previous version from that copy.",
                twin.display()
            );
            output::print_warning(&why);
            failed = Some(why);
        }
    }
    match failed {
        Some(why) => TwinReconcile::Failed(why),
        None => {
            output::print_success(&format!(
                "Scheduler binary {} updated to v{version}.",
                constants::WINDOWS_WINDOWLESS_BIN
            ));
            TwinReconcile::Updated
        }
    }
}

/// The directories whose windowless twin this installation actually runs: the managed
/// directory the scheduler points at, and the directory of the running binary.
#[cfg(windows)]
fn default_twin_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Ok(managed) = crate::setup::managed_exe_path()
        && let Some(dir) = managed.parent()
    {
        dirs.push(dir.to_path_buf());
    }
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        dirs.push(dir.to_path_buf());
    }
    dirs
}

/// The `devp doctor --fix` entry point for a stale scheduler binary: same reconcile,
/// same guardrails, reported through the repair machinery instead of the upgrade
/// transcript.
pub(crate) fn repair_windowless_twins() -> crate::setup::Outcome {
    #[cfg(windows)]
    {
        use crate::setup::Outcome;
        match Registry::load() {
            Ok(r) if r.settings.version_lock => {
                return Outcome::Skipped(
                    "version_lock is set, and nothing dev-prune does replaces a binary \
                     while it is"
                        .to_string(),
                );
            }
            _ => {}
        }
        if crate::setup::offline_requested() {
            return Outcome::Skipped(format!(
                "{} is set and this repair needs a download",
                constants::ENV_OFFLINE
            ));
        }
        // A development build carries whatever version Cargo.toml says next, and the
        // release asset for that version does not exist until the tag is pushed, so
        // reconciling from `target/` would report a spurious download failure once per
        // version bump. The real install heals itself; a dev build stands down.
        if std::env::current_exe().is_ok_and(|exe| crate::commands::uninstall::is_dev_build(&exe)) {
            return Outcome::Skipped(
                "this is a development build, and its version may not be released yet".to_string(),
            );
        }
        let dirs = default_twin_dirs();
        let refs: Vec<&Path> = dirs.iter().map(|p| p.as_path()).collect();
        match reconcile_windowless_twins(constants::VERSION, &refs) {
            TwinReconcile::UpToDate => Outcome::AlreadyPresent,
            TwinReconcile::Updated => Outcome::Installed,
            TwinReconcile::Failed(why) => Outcome::Failed(why),
        }
    }
    #[cfg(not(windows))]
    {
        // The finding this repairs is only ever raised on Windows; this arm exists for
        // the compiler, not for a caller.
        crate::setup::Outcome::AlreadyPresent
    }
}

/// Write already-verified bytes over one binary.
///
/// Separate from the download so a single transfer can serve every copy that has to be
/// replaced — the managed binary, its `devp` twin, and whatever the user is running —
/// instead of fetching the same megabytes once per path.
fn install_bytes_at(bytes: &[u8], target: &Path) -> Result<()> {
    // Staged beside the target and renamed in, so a write that dies half-way leaves the
    // working binary untouched rather than a truncated file where the scheduler expects
    // an executable.
    let staging = target.with_extension("new");
    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent).ok();
    }
    if let Err(e) = fs::write(&staging, bytes) {
        // A write that dies part-way (disk full, permissions revoked mid-stream) leaves
        // a truncated `.new` beside the binary forever — nothing else ever looks at it.
        let _ = fs::remove_file(&staging);
        return Err(e).with_context(|| format!("could not write {}", staging.display()));
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        // Downloaded files are 0644; the scheduler needs to be able to run this.
        let _ = fs::set_permissions(&staging, fs::Permissions::from_mode(0o755));
    }

    replace_binary(&staging, target)
}

/// Read the hash out of a `.sha256` sidecar published beside a release asset.
fn fetch_expected_hash(url: &str) -> Result<String> {
    let body = String::from_utf8(fetch_bytes(url)?).context("the checksum sidecar was not text")?;
    parse_sha256_sidecar(&body)
}

/// The parsing half of [`fetch_expected_hash`], which is `sha256sum` format: the hex
/// digest, two spaces, the file name.
///
/// Validated rather than trusted, because the failure this guards against is not a
/// malformed checksum — it is a 404 page or a proxy error blob arriving where the sidecar
/// should be. Comparing a digest against `<!DOCTYPE html>` would report a checksum
/// mismatch, which reads as "someone tampered with the download" and sends the user
/// somewhere alarming and wrong.
fn parse_sha256_sidecar(body: &str) -> Result<String> {
    let hash = body
        .split_whitespace()
        .next()
        .context("the checksum sidecar was empty")?
        .to_ascii_lowercase();
    if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
        anyhow::bail!("the checksum sidecar did not contain a SHA-256 digest");
    }
    Ok(hash)
}

fn fetch_bytes(url: &str) -> Result<Vec<u8>> {
    let mut body = ureq::get(url)
        .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
        .config()
        .timeout_global(Some(Duration::from_secs(
            constants::UPDATE_DOWNLOAD_TIMEOUT_SECS,
        )))
        .build()
        .call()
        .with_context(|| format!("could not download {url}"))?;
    let mut buf = Vec::new();
    body.body_mut()
        .as_reader()
        .read_to_end(&mut buf)
        .with_context(|| format!("could not read {url}"))?;
    Ok(buf)
}

/// Move `staged` onto `target`, working around the one platform that will not overwrite
/// a file it is executing.
fn replace_binary(staged: &Path, target: &Path) -> Result<()> {
    // On Windows a running image is locked against replacement but not against rename,
    // so the live file steps aside and the new one takes its name. The `.old` is swept
    // by the next run, when nothing holds it open any more.
    #[cfg(windows)]
    let aside = {
        let aside = target.with_extension("exe.old");
        let _ = fs::remove_file(&aside);
        target
            .exists()
            .then(|| fs::rename(target, &aside).ok().map(|_| aside))
            .flatten()
    };

    match fs::rename(staged, target) {
        Ok(()) => {
            #[cfg(windows)]
            if let Some(aside) = aside {
                let _ = fs::remove_file(&aside);
            }
            Ok(())
        }
        Err(e) => {
            let _ = fs::remove_file(staged);
            #[cfg(windows)]
            if let Some(aside) = aside
                && !target.exists()
            {
                // Put the working binary back rather than leaving the machine with no
                // `dev-prune` at all.
                let _ = fs::rename(&aside, target);
            }
            Err(e).with_context(|| format!("could not install {}", target.display()))
        }
    }
}

/// Run one channel's own upgrade command, wired to the terminal so its progress and
/// prompts reach the user directly.
fn spawn_channel_upgrade(channel: Channel) -> Result<()> {
    let Some(argv) = channel.upgrade_argv() else {
        output::print_warning(
            "Could not tell which channel installed this binary, so nothing was \
             changed. Upgrade it yourself with one of:",
        );
        print_upgrade_commands();
        anyhow::bail!("unrecognised install channel");
    };

    output::print_info(&format!("Running: {}", argv.join(" ")));
    let status = crate::spawn::command(crate::adapters::resolve_program(&argv[0]))
        .args(&argv[1..])
        .status()
        .with_context(|| format!("could not start `{}`", argv[0]))?;
    if !status.success() {
        anyhow::bail!("`{}` exited with {status}", argv.join(" "));
    }
    Ok(())
}

/// The end-of-run hook behind `auto_update`: when the setting is on and the last release
/// check already knows a newer version exists, replace the binary without being asked.
///
/// Warn-never-fail, like everything else that runs as a side effect of `devp run` — a
/// broken upgrade path must not turn a successful prune into a failed command.
///
/// Deliberately *not* `run_install`. That function falls back to running the package
/// manager that installed this copy, and this is the path that runs unattended: from the
/// scheduled pass, from a git hook, from `devp run` in the middle of someone else's
/// work. Spawning `winget upgrade` there can raise an elevation prompt and can pull in
/// upgrades nobody asked about. Download-and-replace is safe unattended; handing the
/// machine to a package manager is a decision, and decisions stay with the person.
pub fn maybe_auto_update(registry: &Registry) {
    if !registry.settings.auto_update
        || crate::setup::offline_requested()
        || crate::setup::no_auto_setup_requested()
    {
        return;
    }
    let Some(latest) = registry.latest_known_version.as_deref() else {
        return;
    };
    if compare_versions(constants::VERSION, latest) != Some(Ordering::Less) {
        return;
    }

    // Announced here rather than at the top of the function, so the line appears on
    // exactly the runs where the pin changed the outcome. A pass with nothing to
    // install stays as silent as it has always been.
    if registry.settings.version_lock {
        println!();
        output::print_info(&locked_notice(Some(latest)));
        return;
    }

    let Ok(exe) = std::env::current_exe() else {
        return;
    };
    let managed = crate::setup::managed_exe_path().ok();
    let channel = Channel::detect_at(&exe, managed.as_deref());

    // WinGet, Scoop and Homebrew swap their whole package directory on upgrade, so bytes
    // written there are undone by the next `winget upgrade` — which would still believe
    // the old version is installed. Those channels own the upgrade, and
    // `notify_if_outdated` has already printed the line naming the right command.
    if channel.replaces_its_directory() {
        return;
    }

    // A foreign tree — Volta, mise, Nix, the system package manager — is owned the same
    // way, but there is no resync command to have printed. With a managed copy present
    // the pass below keeps that copy fresh and `install_directly` leaves the manager's
    // file alone; without one, the only writable target *is* the manager's file, and an
    // unattended pass must not desync a tree it has no way to correct.
    if matches!(channel, Channel::Foreign(_)) && managed.is_none() {
        return;
    }

    println!();
    output::print_info(&format!(
        "Updating dev-prune v{} -> v{latest} …",
        constants::VERSION
    ));
    match install_directly(latest, &exe, managed.as_deref(), channel) {
        Ok(()) => {
            output::print_success(&format!("dev-prune v{latest} installed."));
            report_channel_bookkeeping(channel);
        }
        Err(e) => output::print_warning(&format!(
            "Automatic update failed ({e:#}). Run `devp update --install` yourself, or \
             `devp config set auto_update false` to stop trying."
        )),
    }
}

/// Quietly keep the release check current and print a one-line notice when the installed
/// build is behind. Returns `true` when the registry changed and needs saving.
///
/// Called from `devp run` and `devp status`. Never returns an error: a background
/// convenience must not be able to fail the command the user actually asked for.
pub fn notify_if_outdated(registry: &mut Registry) -> bool {
    if !registry.settings.update_check {
        return false;
    }

    let due = check_due(registry);

    if due {
        // The result is deliberately ignored: `refresh_latest` moves the timestamp even
        // when the request fails, and retrying on every command while the machine is
        // offline would put a five-second stall in front of everyday work.
        let _ = refresh_latest(registry);
    }

    if let Some(latest) = registry.latest_known_version.as_deref()
        && compare_versions(constants::VERSION, latest) == Some(Ordering::Less)
    {
        if registry.settings.version_lock {
            output::print_info(&locked_notice(Some(latest)));
        } else {
            output::print_info(&format!(
                "dev-prune v{latest} is out (you have v{}). `devp update` has the commands; \
                 `devp config set update_check false` silences this.",
                constants::VERSION
            ));
        }
    }

    due
}

/// Whether the periodic release check should run now.
///
/// A check that failed gets one day, not the whole interval: the timestamp still
/// advances on failure (so an offline machine is not stalled on every command), but the
/// version it froze is stale, and `maybe_auto_update` trusts nothing else — one
/// timed-out request otherwise silences the auto-update for a week.
fn check_due(registry: &Registry) -> bool {
    let interval = if registry.last_update_check_failed {
        registry.settings.update_check_interval_days.min(1)
    } else {
        registry.settings.update_check_interval_days
    };
    registry
        .last_update_check
        .is_none_or(|last| Utc::now().signed_duration_since(last).num_days() >= interval)
}

/// Ask GitHub for the latest release and record the answer on the registry.
///
/// The caller is responsible for saving; that keeps this usable from both the
/// already-loaded-registry path and the standalone command.
fn refresh_latest(registry: &mut Registry) -> Result<String> {
    let result = latest_release(registry.settings.update_check_timeout_secs);
    registry.last_update_check = Some(Utc::now());
    registry.last_update_check_failed = result.is_err();
    let latest = result?;
    registry.latest_known_version = Some(latest.clone());
    Ok(latest)
}

/// Say whether the installed build is behind, current, or ahead of the latest release.
fn report_comparison(latest: &str) {
    let installed = constants::VERSION;
    match compare_versions(installed, latest) {
        Some(Ordering::Less) => {
            output::print_warning(&format!(
                "Latest release:    v{latest} — an upgrade is available."
            ));
        }
        Some(Ordering::Equal) => {
            output::print_success(&format!(
                "Latest release:    v{latest} — you are up to date."
            ));
        }
        Some(Ordering::Greater) => {
            // Normal when running a local build between releases.
            output::print_info(&format!(
                "Latest release:    v{latest} — your build is newer than the last published one."
            ));
        }
        None => {
            output::print_info(&format!(
                "Latest release:    v{latest} (could not compare it to v{installed})."
            ));
        }
    }
}

/// Fetch the tag name of the most recent published release.
///
/// Returns the version without any leading `v`, so it can be compared to
/// `CARGO_PKG_VERSION` directly.
///
/// The tag comes from the `Location` of the redirect GitHub answers with, not from a
/// page body: `max_redirects(0)` hands the `302` back as an ordinary response, so the
/// release page itself is never downloaded and no API quota is spent (see
/// [`constants::LATEST_RELEASE_URL`]).
fn latest_release(timeout_secs: u64) -> Result<String> {
    if crate::setup::offline_requested() {
        anyhow::bail!("{} is set", constants::ENV_OFFLINE);
    }
    let response = ureq::get(constants::LATEST_RELEASE_URL)
        .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
        .config()
        .timeout_global(Some(Duration::from_secs(timeout_secs.max(1))))
        .max_redirects(0)
        .build()
        .call()
        .context("request failed")?;

    let location = response
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .context("GitHub did not answer with a redirect")?;

    version_from_release_location(location).context("GitHub did not redirect to a release tag")
}

/// Read the version out of the URL GitHub redirects `releases/latest` to.
///
/// A repository with no releases answers with the releases page itself, and a renamed
/// repository answers with the new repository's `releases/latest`; neither carries a tag
/// and neither must be mistaken for one.
fn version_from_release_location(location: &str) -> Option<String> {
    let tag = location
        .split_once("/releases/tag/")?
        .1
        .trim_end_matches('/');
    if tag.is_empty() || tag.contains('/') {
        return None;
    }
    Some(tag.trim_start_matches('v').to_string())
}

/// Compare two dotted numeric versions, ignoring any pre-release suffix.
///
/// Returns `None` when either side is not `major.minor.patch` — better to say "could not
/// compare" than to claim an upgrade exists because `1.0.0` sorts before `1.0.0-rc.1`
/// as a string.
pub(crate) fn compare_versions(a: &str, b: &str) -> Option<Ordering> {
    let parse = |v: &str| -> Option<[u64; 3]> {
        let core = v.split(['-', '+']).next()?;
        let mut parts = core.split('.');
        let out = [
            parts.next()?.parse().ok()?,
            parts.next()?.parse().ok()?,
            parts.next()?.parse().ok()?,
        ];
        // A fourth component means this is not the scheme we release under.
        if parts.next().is_some() {
            return None;
        }
        Some(out)
    };
    Some(parse(a)?.cmp(&parse(b)?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration as ChronoDuration;

    #[test]
    fn the_tag_is_read_out_of_the_redirect_and_its_v_is_dropped() {
        assert_eq!(
            version_from_release_location(
                "https://github.com/Life-Experimentalist/dev-prune/releases/tag/v1.18.0"
            )
            .as_deref(),
            Some("1.18.0")
        );
        assert_eq!(
            version_from_release_location("/Life-Experimentalist/dev-prune/releases/tag/1.2.3/")
                .as_deref(),
            Some("1.2.3")
        );
    }

    #[test]
    fn a_redirect_that_is_not_a_release_tag_is_not_a_version() {
        // No releases yet: GitHub sends the releases page itself.
        assert_eq!(
            version_from_release_location(
                "https://github.com/Life-Experimentalist/dev-prune/releases"
            ),
            None
        );
        // A renamed repository redirects to the new name's `releases/latest`.
        assert_eq!(
            version_from_release_location("https://github.com/other/name/releases/latest"),
            None
        );
        assert_eq!(
            version_from_release_location("https://github.com/o/r/releases/tag/"),
            None
        );
        assert_eq!(
            version_from_release_location("https://github.com/o/r/releases/tag/v1/extra"),
            None
        );
    }

    #[test]
    fn orders_by_component_not_lexically() {
        // "1.10.0" < "1.9.0" as strings, which is the bug this function exists to avoid.
        assert_eq!(compare_versions("1.9.0", "1.10.0"), Some(Ordering::Less));
        assert_eq!(compare_versions("1.0.0", "1.0.0"), Some(Ordering::Equal));
        assert_eq!(
            compare_versions("2.0.0", "1.99.99"),
            Some(Ordering::Greater)
        );
    }

    #[test]
    fn pre_release_suffixes_compare_by_their_core() {
        assert_eq!(
            compare_versions("1.0.0", "1.0.0-rc.1"),
            Some(Ordering::Equal)
        );
        assert_eq!(
            compare_versions("1.0.0+build7", "1.0.1"),
            Some(Ordering::Less)
        );
    }

    #[test]
    fn unparseable_versions_report_no_answer_rather_than_a_wrong_one() {
        assert_eq!(compare_versions("1.0", "1.0.0"), None);
        assert_eq!(compare_versions("1.0.0.1", "1.0.0"), None);
        assert_eq!(compare_versions("nightly", "1.0.0"), None);
    }

    fn bin_names() -> [&'static str; 2] {
        if cfg!(windows) {
            ["dev-prune.exe", "devp.exe"]
        } else {
            ["dev-prune", "devp"]
        }
    }

    #[test]
    fn an_update_reaches_the_twin_beside_the_copy_the_user_typed() {
        // The 1.12.0 bug: `devp update --install` typed at a cargo-installed `devp`
        // upgraded the managed pair and the running file, and left the `dev-prune`
        // beside it on the previous release.
        let [prune, devp] = bin_names();
        let managed_dir = tempfile::tempdir().unwrap();
        let cargo_dir = tempfile::tempdir().unwrap();
        let primary = managed_dir.path().join(prune);
        let exe = cargo_dir.path().join(devp);
        std::fs::write(&exe, b"old").unwrap();
        std::fs::write(cargo_dir.path().join(prune), b"old").unwrap();

        let also = companion_copies(&primary, true, &exe, true);
        assert!(also.contains(&managed_dir.path().join(devp)));
        assert!(also.contains(&exe));
        assert!(also.contains(&cargo_dir.path().join(prune)));
        assert!(!also.contains(&primary));
    }

    #[test]
    fn a_name_that_does_not_exist_outside_the_managed_directory_is_not_invented() {
        // The managed directory owns both names; the running copy's directory belongs
        // to whatever installed it, so a missing twin there stays missing.
        let [prune, devp] = bin_names();
        let managed_dir = tempfile::tempdir().unwrap();
        let solo_dir = tempfile::tempdir().unwrap();
        let primary = managed_dir.path().join(prune);
        let exe = solo_dir.path().join(devp);
        std::fs::write(&exe, b"old").unwrap();

        let also = companion_copies(&primary, true, &exe, true);
        assert!(also.contains(&managed_dir.path().join(devp)));
        assert!(also.contains(&exe));
        assert!(!also.contains(&solo_dir.path().join(prune)));
    }

    #[test]
    fn a_manager_owned_directory_is_left_exactly_as_the_manager_wrote_it() {
        // replace_exe_dir is false for WinGet/Scoop/Homebrew copies; nothing in the
        // running copy's directory may be rewritten, twins included.
        let [prune, devp] = bin_names();
        let managed_dir = tempfile::tempdir().unwrap();
        let store_dir = tempfile::tempdir().unwrap();
        let primary = managed_dir.path().join(prune);
        let exe = store_dir.path().join(devp);
        std::fs::write(&exe, b"old").unwrap();
        std::fs::write(store_dir.path().join(prune), b"old").unwrap();

        let also = companion_copies(&primary, true, &exe, false);
        assert_eq!(also, vec![managed_dir.path().join(devp)]);
    }

    #[test]
    fn exactly_the_manager_owned_channels_keep_their_directory_untouched() {
        // The trio because the next `winget upgrade` would undo the write anyway, and
        // Foreign because overwriting a shim or a store path desyncs a manager this
        // tool has no resync command for. Everything else is a plain file the direct
        // route may replace.
        for owned in [
            Channel::WinGet,
            Channel::Scoop,
            Channel::Homebrew,
            Channel::Foreign("Volta"),
            Channel::Foreign("the system package manager"),
        ] {
            assert!(manager_owns_exe_dir(owned), "{owned:?}");
        }
        for replaceable in [
            Channel::Installer,
            Channel::Cargo,
            Channel::Npm,
            Channel::Bun,
            Channel::Pnpm,
            Channel::Yarn,
            Channel::UvTool,
            Channel::Pipx,
            Channel::Pip,
            Channel::Unknown,
        ] {
            assert!(!manager_owns_exe_dir(replaceable), "{replaceable:?}");
        }
    }

    #[test]
    fn without_a_managed_copy_only_existing_files_beside_the_binary_are_replaced() {
        let [prune, devp] = bin_names();
        let dir = tempfile::tempdir().unwrap();
        let primary = dir.path().join(devp);
        std::fs::write(&primary, b"old").unwrap();

        // Alone, its absent `dev-prune` twin is not created…
        assert!(companion_copies(&primary, false, &primary, false).is_empty());

        // …but a twin that exists is stale the moment the primary is replaced.
        std::fs::write(dir.path().join(prune), b"old").unwrap();
        assert_eq!(
            companion_copies(&primary, false, &primary, false),
            vec![dir.path().join(prune)]
        );
    }

    #[test]
    fn the_check_is_on_unless_the_user_turns_it_off() {
        assert!(Registry::default().settings.update_check);
    }

    #[test]
    fn a_disabled_check_touches_neither_the_network_nor_the_registry() {
        let mut registry = Registry::default();
        registry.settings.update_check = false;
        assert!(!notify_if_outdated(&mut registry));
        assert!(registry.last_update_check.is_none());
    }

    #[test]
    fn auto_update_is_on_by_default_and_silent_with_nothing_to_install() {
        let registry = Registry::default();
        assert!(registry.settings.auto_update);
        // No release check has run, so `latest_known_version` is unset and this must
        // return without touching the network or the terminal. The default being *on* is
        // what makes that early return load-bearing rather than incidental.
        assert!(registry.latest_known_version.is_none());
        maybe_auto_update(&registry);
    }

    #[test]
    fn the_pin_is_off_until_somebody_asks_for_it() {
        // Every other path in this file is written on the assumption that the pin costs
        // nothing when nobody has set it, so the default is the part worth asserting.
        assert!(!Registry::default().settings.version_lock);
    }

    #[test]
    fn the_refusal_names_the_version_it_is_holding_and_the_way_out() {
        // Both halves matter. A refusal that does not say which version it is holding
        // cannot be audited, and one that does not say how to release it is
        // indistinguishable, to the person reading it, from an update path that broke.
        let notice = locked_notice(None);
        assert!(notice.contains(constants::VERSION), "{notice}");
        assert!(
            notice.contains("devp config set version_lock false"),
            "{notice}"
        );
        assert!(!notice.contains("is out"), "{notice}");
    }

    #[test]
    fn a_known_release_is_named_in_the_refusal_that_withholds_it() {
        // "You are pinned" and "there is a 2.0.0 out that you are not getting" are
        // different facts, and the second is the one that makes somebody go and look at
        // the setting.
        let notice = locked_notice(Some("2.0.0"));
        assert!(notice.contains("v2.0.0 is out"), "{notice}");
        assert!(notice.contains(constants::VERSION), "{notice}");
    }

    #[test]
    fn a_failed_check_is_retried_after_a_day_not_a_whole_interval() {
        let mut registry = Registry {
            last_update_check: Some(Utc::now() - ChronoDuration::days(2)),
            last_update_check_failed: true,
            ..Default::default()
        };
        // Two days since a *failed* check: due again, well inside the ordinary
        // interval. This is the incident: a timed-out check froze the known version at
        // 1.14.0, and the next scheduled pass — a day and a half later — trusted it.
        assert!(check_due(&registry));
        registry.last_update_check_failed = false;
        assert!(
            !check_due(&registry),
            "a successful check keeps the interval"
        );
    }

    #[test]
    fn even_a_failed_check_is_not_retried_within_the_day() {
        // The failure backoff must not reintroduce the per-command stall it was
        // written around: offline for an afternoon means one timeout, not one per
        // command.
        let registry = Registry {
            last_update_check: Some(Utc::now() - ChronoDuration::hours(2)),
            last_update_check_failed: true,
            ..Default::default()
        };
        assert!(!check_due(&registry));
    }

    #[test]
    fn a_recent_check_is_not_repeated() {
        let mut registry = Registry::default();
        let stamp = Utc::now() - ChronoDuration::days(constants::UPDATE_CHECK_INTERVAL_DAYS - 1);
        registry.last_update_check = Some(stamp);
        // No network call, so the stamp survives untouched and nothing needs saving.
        assert!(!notify_if_outdated(&mut registry));
        assert_eq!(registry.last_update_check, Some(stamp));
    }

    #[test]
    fn the_asset_name_matches_what_the_release_workflow_builds() {
        // This string is a contract with `.github/workflows/release.yml`. Getting it
        // wrong is not a compile error and not a test failure anywhere else — it is a
        // self-update that 404s for every user on the day of a release.
        let name = constants::release_asset_name("1.4.0");
        let expected = match (std::env::consts::OS, std::env::consts::ARCH) {
            ("windows", "x86_64") => Some("dev-prune-v1.4.0-windows-x64.exe"),
            ("windows", "aarch64") => Some("dev-prune-v1.4.0-windows-arm64.exe"),
            ("windows", "x86") => Some("dev-prune-v1.4.0-windows-x86.exe"),
            ("linux", "x86_64") => Some("dev-prune-v1.4.0-linux-x64"),
            ("linux", "aarch64") => Some("dev-prune-v1.4.0-linux-arm64"),
            ("macos", "x86_64") => Some("dev-prune-v1.4.0-darwin-x64"),
            ("macos", "aarch64") => Some("dev-prune-v1.4.0-darwin-arm64"),
            // A platform the release does not build for must decline the direct route
            // rather than download some other platform's binary.
            _ => None,
        };
        assert_eq!(name.as_deref(), expected);
    }

    #[cfg(windows)]
    #[test]
    fn the_windowless_asset_name_matches_what_the_release_workflow_builds() {
        // Same contract, same failure mode as the console asset above: a wrong name is
        // a scheduler binary that 404s on the day of a release and stays stale.
        let name = constants::windowless_release_asset_name("1.4.0");
        let expected = match std::env::consts::ARCH {
            "x86_64" => Some("devpw-v1.4.0-windows-x64.exe"),
            "aarch64" => Some("devpw-v1.4.0-windows-arm64.exe"),
            "x86" => Some("devpw-v1.4.0-windows-x86.exe"),
            _ => None,
        };
        assert_eq!(name.as_deref(), expected);
    }

    #[test]
    fn only_windows_has_a_32_bit_asset() {
        // The matrix builds `x86` for Windows alone. On a 32-bit Linux there is nothing
        // to download, and guessing `x64` would install a binary that cannot run.
        let name = constants::release_asset_name("9.9.9");
        if std::env::consts::ARCH == "x86" {
            assert_eq!(name.is_some(), std::env::consts::OS == "windows");
        }
    }

    #[test]
    fn a_sidecar_is_read_as_the_first_field_of_sha256sum_format() {
        let digest = "a".repeat(64);
        assert_eq!(
            parse_sha256_sidecar(&format!("{digest}  dev-prune-v1.4.0-linux-x64\n")).unwrap(),
            digest
        );
        // The Windows step writes it with no trailing newline, and GitHub may serve
        // either line ending.
        assert_eq!(
            parse_sha256_sidecar(&format!("{digest}  asset.exe")).unwrap(),
            digest
        );
        assert_eq!(
            parse_sha256_sidecar(&format!("{}  asset\r\n", digest.to_uppercase())).unwrap(),
            digest,
            "an upper-case digest must compare equal to the one we compute"
        );
    }

    #[test]
    fn anything_that_is_not_a_digest_is_refused_before_it_is_compared() {
        // A 404 page, an error blob or a truncated read must fail as "not a digest"
        // rather than as a mismatch — the two send the user to very different places.
        for bad in [
            "",
            "   ",
            "<!DOCTYPE html>",
            "not-a-hash  asset",
            &"a".repeat(63),
            &"a".repeat(65),
            &format!("{}g  asset", "a".repeat(63)),
        ] {
            assert!(
                parse_sha256_sidecar(bad).is_err(),
                "{bad:?} must not be accepted as a digest"
            );
        }
    }
}