dev-prune 1.1.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
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

//! Idempotent installation of dev-prune's integrations.
//!
//! dev-prune is only really installed once the parts that let it work without being
//! thought about are in place: the `devp` alias, the exported `SKILL.md` that AI
//! assistants read, the Git hooks that keep the registry current, and the OS scheduler
//! that runs the passes. Each one here is created **only when it is missing**, which is
//! what makes it safe to run on every install, reinstall and upgrade — and it does run
//! on each of those, through the version stamp written at the end of a completed pass.
//!
//! Nothing in here is fatal. A machine without `git`, a `core.hooksPath` that belongs to
//! husky, a locked-down scheduler: each is reported and stepped over, because none of
//! them should stop `devp init` from registering repositories.

use std::fs;
use std::path::PathBuf;

use anyhow::Result;

use crate::commands::hook::{self, HookState};
use crate::commands::skill::EMBEDDED_SKILL_MD;
use crate::config::Registry;
use crate::constants;
use crate::daemon;
use crate::output;

/// File in the config directory recording the version whose last integration pass
/// completed. A missing or older stamp is what triggers the automatic pass, so a fresh
/// install and an upgrade both self-heal exactly once.
const STAMP_FILE: &str = "setup-stamp";

/// Environment variable that suppresses the automatic pass entirely.
///
/// For images, CI and anyone who wants the binary and nothing else. `devp setup` still
/// works when it is set — this only governs the unattended pass.
pub const ENV_NO_AUTO_SETUP: &str = "DEV_PRUNE_NO_AUTO_SETUP";

/// Whether the suppression variable is set — by presence, so `=1`, `=true` and even an
/// empty value all count.
///
/// The one predicate every consumer must share. The doctor note used to answer only for
/// the literal `=1`, so a machine with `=true` had setup switched off with nothing
/// anywhere saying so.
pub fn no_auto_setup_requested() -> bool {
    std::env::var_os(ENV_NO_AUTO_SETUP).is_some()
}

/// What one integration did during a pass.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// It was missing and is now in place.
    Installed,
    /// It was already in place and was left alone.
    AlreadyPresent,
    /// It could not be installed for a reason that is the user's call, not an error.
    Skipped(String),
    /// It failed. The pass continues; the reason is reported.
    Failed(String),
}

/// The result of one integration pass.
#[derive(Debug, Default)]
pub struct SetupReport {
    items: Vec<(&'static str, Outcome)>,
}

impl SetupReport {
    fn push(&mut self, name: &'static str, outcome: Outcome) {
        self.items.push((name, outcome));
    }

    /// Whether anything at all was created by this pass.
    pub fn changed_anything(&self) -> bool {
        self.items
            .iter()
            .any(|(_, o)| matches!(o, Outcome::Installed))
    }

    /// Whether anything needs the user's attention.
    pub fn needs_attention(&self) -> bool {
        self.items
            .iter()
            .any(|(_, o)| matches!(o, Outcome::Skipped(_) | Outcome::Failed(_)))
    }

    /// Print the report.
    ///
    /// `verbose` is for the explicit `devp setup`, where "already installed" is the
    /// answer the user asked for. The automatic pass passes `false` and stays silent
    /// about everything that was already fine.
    pub fn print(&self, verbose: bool) {
        for (name, outcome) in &self.items {
            match outcome {
                Outcome::Installed => output::print_success(&format!("{name}: installed.")),
                Outcome::AlreadyPresent if verbose => {
                    output::print_info(&format!("{name}: already installed."));
                }
                Outcome::AlreadyPresent => {}
                Outcome::Skipped(why) => {
                    output::print_warning(&format!("{name}: skipped — {why}"));
                }
                Outcome::Failed(why) => {
                    output::print_error(&format!("{name}: failed — {why}"));
                }
            }
        }
    }
}

/// Where the installers put the binary, and the one directory nothing else owns.
fn managed_exe_path() -> Result<PathBuf> {
    let name = if cfg!(windows) {
        "dev-prune.exe"
    } else {
        "dev-prune"
    };
    Ok(Registry::config_dir()?.join("bin").join(name))
}

/// Absolute path to a copy of this binary that will still be there next week.
///
/// Anything that writes a path down for later — the OS scheduler, the git hooks — has to
/// use this instead of [`std::env::current_exe`]. dev-prune ships through npm and PyPI as
/// well as the installers, so the running executable is often somewhere a package manager
/// owns and will delete: npm's `_npx` cache, uv's ephemeral tool environment, or
/// `target/debug` during development. An entry recorded there breaks the moment that
/// directory goes, and neither of these has anywhere to complain — the scheduled task
/// fails silently every interval, and the hook discards its own output by design. The
/// only symptom is that nothing ever happens again.
///
/// `<config>/bin` is where `install.sh` and `install.ps1` put the binary and nothing else
/// deletes, so prefer the copy there. When there is none, put one there: the binary that
/// is running right now is precisely the one that is going to be missing later.
pub fn stable_exe_path() -> PathBuf {
    let current = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("dev-prune"));
    let Ok(managed) = managed_exe_path() else {
        return current;
    };
    if managed == current {
        return managed;
    }
    if managed.is_file() {
        refresh_managed_copy_if_stale(&current, &managed);
        return managed;
    }

    // Only ever clone something that is actually this CLI. `current_exe()` under `cargo
    // test` is the test harness, and copying that into the config directory would be both
    // wrong and slow.
    if !is_this_cli(&current) {
        return current;
    }

    let Some(parent) = managed.parent() else {
        return current;
    };
    if fs::create_dir_all(parent).is_err() {
        return current;
    }
    // Hard link where the filesystem allows it — that also keeps the bytes alive when the
    // package manager deletes the directory the original came from.
    if fs::hard_link(&current, &managed).is_ok() {
        return managed;
    }

    // The same hazard `ensure_alias` documents, through a narrower window: the check at the
    // top of this function saw no managed copy, but another process created one — as a hard
    // link to `current` — before the link above ran. `fs::copy` opens its destination with
    // O_TRUNC, and truncating a hard link empties the shared inode, so the copy would
    // destroy the very binary it is copying.
    if managed.is_file() {
        return managed;
    }

    // Stage beside and rename into place. A copy straight onto the final name has a
    // window where the file exists but is incomplete — and this path is what the
    // scheduler and hooks get registered against, so a process killed mid-copy would
    // leave a torn binary that every later pass happily points at.
    let staging = managed.with_extension("new");
    if fs::copy(&current, &staging).is_ok() && fs::rename(&staging, &managed).is_ok() {
        return managed;
    }
    let _ = fs::remove_file(&staging);
    // The rename loses only to a concurrent invocation that installed its own copy,
    // which serves exactly as well.
    if managed.is_file() { managed } else { current }
}

/// Whether this path names one of the CLI's own binaries, by file stem.
fn is_this_cli(path: &std::path::Path) -> bool {
    path.file_stem()
        .and_then(|s| s.to_str())
        .is_some_and(|stem| stem == "dev-prune" || stem == "devp")
}

/// Replace the managed copy when it is an older release than the binary running now.
///
/// The scheduler and the hooks point at the managed copy precisely because it outlives
/// package-manager caches — which also means an upgrade through cargo, npm or uv changes
/// the running binary but not the one the integrations run, and the machine quietly
/// keeps pruning with the previous version forever.
///
/// Staleness is decided by asking the copy its version, not by mtime or content: an
/// *older* binary running out of a stale npx cache must not overwrite a newer managed
/// copy, and content inequality cannot say which of the two is the upgrade. A copy that
/// cannot state a version at all is replaced too — whatever it is, it is not a working
/// build of this CLI.
fn refresh_managed_copy_if_stale(current: &std::path::Path, managed: &std::path::Path) {
    if !is_this_cli(current) || same_contents(managed, current) {
        return;
    }
    match (binary_version(managed), parse_version(constants::VERSION)) {
        (Some(theirs), Some(ours)) if theirs >= ours => return,
        _ => {}
    }
    // Write beside and rename into place, so a scheduler firing mid-copy never runs a
    // torn binary. A managed copy that is itself running cannot be renamed over on
    // Windows; the refresh simply waits for a pass when it is not.
    let staging = managed.with_extension("new");
    if fs::copy(current, &staging).is_ok() && fs::rename(&staging, managed).is_err() {
        let _ = fs::remove_file(&staging);
    }
}

/// The `major.minor.patch` a binary reports for itself, if it can.
fn binary_version(exe: &std::path::Path) -> Option<(u64, u64, u64)> {
    let output = std::process::Command::new(exe)
        .arg("--version")
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    String::from_utf8_lossy(&output.stdout)
        .split_whitespace()
        .find_map(parse_version)
}

/// Parse `x.y.z` into an orderable triple. Anything else — including the pre-release
/// and build suffixes this project never publishes — answers `None`.
fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
    let mut parts = text.split('.');
    let triple = (
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
    );
    parts.next().is_none().then_some(triple)
}

/// Keep `dev-prune` and `devp` beside each other, whichever of the two is running.
///
/// The pair is one binary under two names, and either one can be the survivor. An upgrade
/// that could not replace a running `devp` leaves a stale alias; an antivirus quarantine,
/// a half-finished uninstall or a `Remove-Item` aimed at the wrong name leaves only
/// `devp`. So this restores *the other* name in whichever direction is missing, rather
/// than only ever creating `devp` — running either one puts the pair back.
pub fn ensure_alias() -> Outcome {
    let Ok(current_exe) = std::env::current_exe() else {
        return Outcome::Failed("could not locate the running executable".to_string());
    };
    let Some(parent_dir) = current_exe.parent() else {
        return Outcome::Failed("the running executable has no parent directory".to_string());
    };

    ensure_twin_of(&current_exe, parent_dir)
}

/// The half of [`ensure_alias`] that takes its paths as arguments, so tests can drive both
/// directions without being the binary they are testing.
fn ensure_twin_of(current_exe: &std::path::Path, parent_dir: &std::path::Path) -> Outcome {
    let running_as_alias = current_exe
        .file_stem()
        .and_then(|s| s.to_str())
        .is_some_and(|stem| stem == "devp");

    // `dev-prune` is the canonical name, and only it may overwrite its twin.
    //
    // Installers write `dev-prune` first and upgrades replace it first, so it is never the
    // older of the two — a stale `devp` is worth replacing, because otherwise it silently
    // runs the previous version. The reverse is not safe: an upgrade that replaced
    // `dev-prune` and then failed on a running `devp` leaves exactly the state where the
    // alias is the *older* binary, and refreshing from there would quietly reinstall the
    // version the user just upgraded away from. So `devp` may only create a `dev-prune`
    // that is missing outright.
    let (twin_name, may_refresh) = if running_as_alias {
        (
            if cfg!(windows) {
                "dev-prune.exe"
            } else {
                "dev-prune"
            },
            false,
        )
    } else {
        (if cfg!(windows) { "devp.exe" } else { "devp" }, true)
    };
    let twin_exe = parent_dir.join(twin_name);

    if twin_exe.exists() {
        if !may_refresh || same_contents(&twin_exe, current_exe) {
            return Outcome::AlreadyPresent;
        }
        // Replacing a running executable fails on Windows; that is fine, the alias is
        // simply refreshed by the next invocation that is not itself `devp`.
        if fs::remove_file(&twin_exe).is_err() {
            return Outcome::Skipped(format!(
                "`{twin_name}` is in use and could not be refreshed — re-run `devp setup` \
                 from a terminal that is not running it"
            ));
        }
    }

    if fs::hard_link(current_exe, &twin_exe).is_ok() {
        return Outcome::Installed;
    }

    // The copy is the fallback for filesystems without hard links — but it must never
    // run when the alias already exists, because the reason `hard_link` usually fails is
    // that another process created it a moment ago, as a hard link to this very
    // executable. `fs::copy` opens its destination with O_TRUNC, and truncating a hard
    // link truncates the shared inode: the copy would empty the running binary and then
    // copy zero bytes from it.
    //
    // That is not hypothetical. It is what turned every macOS CI run red. The 28
    // integration tests launch at once, one wins the link, the losers fall through to
    // here, and `target/debug/dev-prune` becomes a zero-byte file. macOS `posix_spawn`
    // answers ENOEXEC by handing the file to `/bin/sh`, so every later invocation
    // "succeeded" with exit 0 and printed nothing — for two hours the tests looked like
    // 27 unrelated assertion failures.
    if twin_exe.exists() {
        return Outcome::AlreadyPresent;
    }

    // Stage beside and rename into place: copied straight onto the final name, the
    // alias would exist-but-be-incomplete for the length of the copy, and a `devp`
    // typed in that window executes a torn binary.
    let staging = twin_exe.with_extension("new");
    if fs::copy(current_exe, &staging).is_ok() && fs::rename(&staging, &twin_exe).is_ok() {
        return Outcome::Installed;
    }
    let _ = fs::remove_file(&staging);
    if twin_exe.exists() {
        // A concurrent invocation won the rename; its alias serves exactly as well.
        return Outcome::AlreadyPresent;
    }
    Outcome::Failed(format!(
        "could not create `{}`",
        output::clean_path(&twin_exe)
    ))
}

/// Sameness test for two executables, cheap in the common case.
///
/// A hard link makes size and mtime equal by construction, so the usual layout answers
/// without reading either file. When only the mtime differs — the alias came from the
/// copy fallback, which does not preserve timestamps — the bytes themselves decide,
/// because calling that pair "different" made every single invocation delete and
/// recreate an alias whose content never changed.
fn same_contents(a: &std::path::Path, b: &std::path::Path) -> bool {
    let (Ok(ma), Ok(mb)) = (fs::metadata(a), fs::metadata(b)) else {
        return false;
    };
    if ma.len() != mb.len() {
        return false;
    }
    if ma.modified().ok() == mb.modified().ok() {
        return true;
    }
    match (fs::read(a), fs::read(b)) {
        (Ok(ca), Ok(cb)) => ca == cb,
        _ => false,
    }
}

/// Path that `devp skill` and this module export `SKILL.md` to.
pub fn skill_path() -> Result<PathBuf> {
    Ok(Registry::config_dir()?.join("SKILL.md"))
}

/// Export the bundled `SKILL.md` so AI assistants have something to read.
///
/// Rewritten whenever it differs from the embedded copy, since an upgrade that changes
/// the skill must not leave the previous version's instructions on disk.
pub fn ensure_skill_file() -> Outcome {
    match Registry::config_dir() {
        Ok(dir) => ensure_skill_file_in(&dir),
        Err(_) => Outcome::Failed("could not determine the config directory".to_string()),
    }
}

fn ensure_skill_file_in(config_dir: &std::path::Path) -> Outcome {
    let target = config_dir.join("SKILL.md");

    if fs::read_to_string(&target).is_ok_and(|current| current == EMBEDDED_SKILL_MD) {
        return Outcome::AlreadyPresent;
    }

    let _ = fs::create_dir_all(config_dir);
    match fs::write(&target, EMBEDDED_SKILL_MD) {
        Ok(()) => Outcome::Installed,
        Err(e) => Outcome::Failed(format!(
            "could not write {}: {e}",
            output::clean_path(&target)
        )),
    }
}

/// Write the icon assets and register `*.devprune.json` with the OS file manager.
///
/// Part of the automatic pass rather than a separate errand, because "the config file has
/// an icon" is not a thing anybody thinks to go and ask for. Everything it writes lives
/// under the config directory and the user's own XDG data directory, `devp uninstall`
/// removes all of it, and it touches no editor settings, no PATH and no shell profile —
/// so there is nothing here that needs to be asked about first.
///
/// Unlike the hooks and the scheduler, this has no opt-out switch of its own. Files
/// dropped into the user's data directory are not a background process and not a change
/// in behaviour; `auto_setup` already covers "install nothing at all".
fn ensure_icons() -> Outcome {
    if crate::commands::icon::is_registered() {
        return Outcome::AlreadyPresent;
    }
    match crate::commands::icon::sync_app_directory() {
        Ok(()) => Outcome::Installed,
        Err(e) => Outcome::Failed(format!("{e:#}")),
    }
}

/// Install the global Git hooks, unless git is absent or the slot belongs to someone else.
///
/// `chain` is `auto_hooks_chain`: with it on, a slot that belongs to husky is not a
/// reason to skip, because dev-prune can install in front and forward every hook back.
pub fn ensure_hooks(chain: bool) -> Outcome {
    if !hook::git_available() {
        return Outcome::Skipped(format!(
            "\n    {}",
            hook::GIT_MISSING_HELP.replace('\n', "\n    ")
        ));
    }

    match hook::state() {
        // "Installed" is not the question — "installed and pointing at a binary that
        // still exists" is. A hook backgrounds itself and discards its own output, so
        // one left pointing at a deleted npm cache dies silently on every commit and
        // nothing ever registers again; this pass is the only thing that ever looks.
        Ok(HookState::Active) if hook_target_is_dead() => match hook::install() {
            Ok(()) => Outcome::Installed,
            Err(e) => Outcome::Failed(format!("{e:#}")),
        },
        Ok(HookState::Active) => Outcome::AlreadyPresent,
        // Drift is repaired here rather than reported: the setup pass already runs on
        // install, on update and on a schedule, and a chain the user opted into is a
        // chain they want kept current.
        Ok(HookState::Chained { drifted, .. }) if !drifted.is_empty() => {
            match hook::install_with(true) {
                Ok(()) => Outcome::Installed,
                Err(e) => Outcome::Failed(format!("{e:#}")),
            }
        }
        Ok(HookState::Chained { .. }) if hook_target_is_dead() => match hook::install_with(true) {
            Ok(()) => Outcome::Installed,
            Err(e) => Outcome::Failed(format!("{e:#}")),
        },
        Ok(HookState::Chained { .. }) => Outcome::AlreadyPresent,
        Ok(HookState::Foreign(_)) if chain => match hook::install_with(true) {
            Ok(()) => Outcome::Installed,
            Err(e) => Outcome::Failed(format!("{e:#}")),
        },
        Ok(HookState::Foreign(existing)) => Outcome::Skipped(format!(
            "`core.hooksPath` is already set to `{existing}`, which belongs to another tool.\n    \
             Git allows only one hooks directory, so dev-prune will not take the slot.\n    \
             `devp hook install --chain` installs in front of it instead — dev-prune registers \
             the repo, then hands every hook on to `{existing}`, and `devp hook uninstall` puts \
             the original setting back (`devp config set auto_hooks_chain true` makes that \
             the standing answer). Or skip it: `devp link .` does the same job by hand."
        )),
        Ok(HookState::Absent) => match hook::install() {
            Ok(()) => Outcome::Installed,
            Err(e) => Outcome::Failed(format!("{e:#}")),
        },
        Err(e) => Outcome::Failed(format!("{e:#}")),
    }
}

/// Whether the installed hooks name a binary that no longer exists.
fn hook_target_is_dead() -> bool {
    hook::registered_exe_path().is_some_and(|exe| !exe.exists())
}

/// Install the OS scheduler if it is not already registered.
pub fn ensure_daemon(interval_days: u64) -> Outcome {
    match daemon::daemon_status() {
        // A task whose binary has been deleted keeps reporting itself `Ready` and dies
        // the instant it fires, every interval, with nowhere to complain. Re-register
        // it against the stable path instead of counting the corpse as present.
        Ok(daemon::DaemonStatus::Installed)
            if daemon::registered_exe_path().is_some_and(|exe| !exe.exists()) =>
        {
            match daemon::install_daemon(interval_days) {
                Ok(()) => Outcome::Installed,
                Err(e) => Outcome::Failed(format!("{e:#}")),
            }
        }
        Ok(daemon::DaemonStatus::Installed) => Outcome::AlreadyPresent,
        Ok(daemon::DaemonStatus::NotInstalled) => match daemon::install_daemon(interval_days) {
            Ok(()) => Outcome::Installed,
            Err(e) => Outcome::Failed(format!("{e:#}")),
        },
        // `Unknown` means the query itself could not be answered — the scheduler may
        // well be there. Installing over it would fail on every command from now on, so
        // this reports and steps over instead of guessing. The platform backends are
        // written to keep this case narrow: anything they can answer definitely, they do.
        Ok(daemon::DaemonStatus::Unknown(why)) => {
            Outcome::Skipped(format!("scheduler state could not be read — {why}"))
        }
        Err(e) => Outcome::Failed(format!("{e:#}")),
    }
}

/// Whether unattended installation is permitted at all.
///
/// Both switches exist because these integrations write outside dev-prune's own config
/// directory — a scheduled task, a global git setting — and there are places that must
/// never happen unasked: container images, CI, and this project's own test suite.
pub fn auto_setup_enabled(registry: &Registry) -> bool {
    !no_auto_setup_requested() && registry.settings.auto_setup && unattended_environment().is_none()
}

/// The reason this looks like a machine nobody is sitting at, if it does.
///
/// `DEV_PRUNE_NO_AUTO_SETUP` and `auto_setup` are both switches you have to set *before*
/// the first run — which is exactly the run that installs things, so in a container or a
/// CI job the damage is done by the time there is anywhere to set them. Detecting the
/// environment is the only opt-out that works on the first run, which is the only run
/// that matters here.
///
/// Deliberately conservative: every signal below is one that CI providers and container
/// runtimes set themselves, so a developer's own shell will not trip it. Someone who
/// genuinely wants the integrations in CI can still ask in so many words with
/// `devp setup`, which never consults this.
pub fn unattended_environment() -> Option<&'static str> {
    // Set by GitHub Actions, GitLab CI, CircleCI, Travis, Jenkins (via pipeline), Woodpecker
    // and most others. `CI=true` is the closest thing this space has to a standard.
    for var in [
        "CI",
        "CONTINUOUS_INTEGRATION",
        "BUILD_NUMBER",
        "GITHUB_ACTIONS",
    ] {
        if let Some(value) = std::env::var_os(var) {
            // `CI=false` is set explicitly by some tools to mean "not CI", and honouring
            // the word rather than the presence is what the user plainly meant.
            let value = value.to_string_lossy();
            if !value.is_empty() && !value.eq_ignore_ascii_case("false") {
                return Some("this looks like a CI runner");
            }
        }
    }

    // Docker writes this marker into every container it builds from a Dockerfile;
    // Podman and other OCI runtimes write the `container` variable instead.
    #[cfg(unix)]
    if std::path::Path::new("/.dockerenv").exists() {
        return Some("this looks like a container");
    }
    if std::env::var_os("container").is_some() {
        return Some("this looks like a container");
    }

    None
}

/// Run an integration pass unless unattended installation is switched off.
///
/// Every caller that the user did not name explicitly goes through this. `devp setup`
/// calls [`ensure_integrations`] directly: asking for it in so many words is consent.
pub fn ensure_integrations_if_enabled(registry: &Registry) -> Option<SetupReport> {
    auto_setup_enabled(registry).then(|| ensure_integrations(registry))
}

/// Run one integration pass, installing whatever is missing.
///
/// The two per-integration settings (`auto_daemon`, `auto_hooks`) are honoured here, so
/// turning one off turns it off for every future pass as well as this one.
pub fn ensure_integrations(registry: &Registry) -> SetupReport {
    let mut report = SetupReport::default();

    report.push("dev-prune/devp pair", ensure_alias());
    report.push("SKILL.md", ensure_skill_file());
    report.push("File icons", ensure_icons());

    if registry.settings.auto_hooks {
        report.push(
            "Git hooks",
            ensure_hooks(registry.settings.auto_hooks_chain),
        );
    } else {
        report.push(
            "Git hooks",
            Outcome::Skipped("`auto_hooks` is false — enable with `devp hook install`".to_string()),
        );
    }

    if registry.settings.auto_daemon {
        report.push(
            "Background scheduler",
            ensure_daemon(registry.settings.check_interval_days),
        );
    } else {
        report.push(
            "Background scheduler",
            Outcome::Skipped(
                "`auto_daemon` is false — enable with `devp daemon install`".to_string(),
            ),
        );
    }

    report
}

/// Record that a pass completed for this version.
fn write_stamp_in(config_dir: &std::path::Path) {
    let _ = fs::create_dir_all(config_dir);
    let _ = fs::write(config_dir.join(STAMP_FILE), constants::VERSION);
}

fn write_stamp() {
    if let Ok(dir) = Registry::config_dir() {
        write_stamp_in(&dir);
    }
}

fn setup_is_due_in(config_dir: &std::path::Path) -> bool {
    !fs::read_to_string(config_dir.join(STAMP_FILE))
        .is_ok_and(|stamp| stamp.trim() == constants::VERSION)
}

/// Whether the unattended pass is due: a fresh install, or the first run after an upgrade.
pub fn setup_is_due() -> bool {
    Registry::config_dir()
        .map(|dir| setup_is_due_in(&dir))
        .unwrap_or(false)
}

/// The unattended pass, run at most once per installed version.
///
/// Called at the top of every command that a human typed. It is deliberately not called
/// for the Git hook's `link --quiet` or the scheduler's `run --daemon`: those run without
/// a terminal, and an integration pass that nobody can see is one nobody can refuse.
pub fn auto_setup_if_due() {
    if !setup_is_due() {
        first_run_config_review();
        return;
    }

    let Ok(registry) = Registry::load() else {
        return;
    };
    let Some(report) = ensure_integrations_if_enabled(&registry) else {
        // Suppressed. Stamp anyway, so a machine that opted out does not re-decide
        // this on every single command.
        write_stamp();
        crate::commands::config::skip_config_review();
        return;
    };
    if report.changed_anything() || report.needs_attention() {
        output::print_header("dev-prune setup");
        report.print(false);
        if report.changed_anything() {
            output::print_info(
                "Run `devp setup --status` to review these, or `devp uninstall` to remove them.",
            );
        }
        println!();
    }
    write_stamp();
    first_run_config_review();
}

/// Put the defaults in front of the user, once, on a fresh install.
///
/// Separate from the integration stamp on purpose. The integrations are re-checked after
/// every upgrade; the settings are not — being asked to reconfirm `idle_days` on each new
/// version would be a nuisance, and the marker only disappears when the config directory
/// does.
///
/// Every condition here is a way of asking "is there a person reading this?", because the
/// alternative to asking is a prompt written into a log nobody will read, on a run that
/// then blocks forever waiting for an answer.
fn first_run_config_review() {
    if !crate::commands::config::config_review_is_due() {
        return;
    }

    use std::io::IsTerminal;
    if unattended_environment().is_some()
        || !std::io::stdin().is_terminal()
        || !std::io::stdout().is_terminal()
    {
        crate::commands::config::skip_config_review();
        return;
    }

    // Any error here is the wizard's own reporting; the command the user actually typed
    // still runs. A failed walkthrough must not become a failed `devp status`.
    if let Err(e) = crate::commands::config::run_wizard() {
        output::print_warning(&format!("Could not run the first-run setup ({e:#})."));
        crate::commands::config::skip_config_review();
    }
    println!();
}

/// Invalidate the stamp so the next human-run command performs a pass.
///
/// `uninstall` calls this in reverse — it writes the current stamp — so that removing the
/// integrations is not immediately undone by the next command.
pub fn suppress_next_auto_setup() {
    write_stamp();
}

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

    #[test]
    fn a_report_with_only_present_items_is_silent() {
        let mut report = SetupReport::default();
        report.push("a", Outcome::AlreadyPresent);
        assert!(!report.changed_anything());
        assert!(!report.needs_attention());
    }

    #[test]
    fn skipped_and_failed_both_ask_for_attention() {
        let mut skipped = SetupReport::default();
        skipped.push("a", Outcome::Skipped("no git".into()));
        assert!(skipped.needs_attention());
        assert!(!skipped.changed_anything());

        let mut failed = SetupReport::default();
        failed.push("a", Outcome::Failed("boom".into()));
        assert!(failed.needs_attention());
    }

    #[test]
    fn an_install_counts_as_a_change() {
        let mut report = SetupReport::default();
        report.push("a", Outcome::Installed);
        assert!(report.changed_anything());
    }

    #[test]
    fn the_skill_export_lands_in_the_config_directory() {
        let dir = tempfile::TempDir::new().unwrap();
        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::Installed);
        // A second pass finds byte-identical content and leaves it alone.
        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::AlreadyPresent);
        let written = fs::read_to_string(dir.path().join("SKILL.md")).unwrap();
        assert_eq!(written, EMBEDDED_SKILL_MD);
    }

    #[test]
    fn a_stale_skill_export_is_rewritten() {
        // An upgrade must not leave the previous version's instructions on disk.
        let dir = tempfile::TempDir::new().unwrap();
        fs::write(dir.path().join("SKILL.md"), "# an older version").unwrap();
        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::Installed);
        let written = fs::read_to_string(dir.path().join("SKILL.md")).unwrap();
        assert_eq!(written, EMBEDDED_SKILL_MD);
    }

    #[test]
    fn the_stamp_gates_the_unattended_pass() {
        let dir = tempfile::TempDir::new().unwrap();
        assert!(setup_is_due_in(dir.path()), "a fresh install is due");
        write_stamp_in(dir.path());
        assert!(
            !setup_is_due_in(dir.path()),
            "the same version is not due twice"
        );
        fs::write(dir.path().join(STAMP_FILE), "0.0.1").unwrap();
        assert!(setup_is_due_in(dir.path()), "an upgrade is due again");
    }

    /// The alias must never be written with a copy while it already exists.
    ///
    /// A hard link and its target share one inode, so `fs::copy` onto the alias empties
    /// the binary it was copied from. This reproduces the exact shape of that bug — link
    /// first, then ask for the alias again — and asserts the original still has its
    /// bytes. The real failure was silent: a zero-byte executable that macOS runs
    /// through `/bin/sh`, which exits 0 and prints nothing.
    #[test]
    fn refreshing_an_alias_that_is_a_hard_link_does_not_empty_the_binary() {
        let dir = tempfile::TempDir::new().unwrap();
        let binary = dir.path().join("dev-prune");
        let alias = dir.path().join("devp");
        fs::write(&binary, vec![b'M'; 4096]).unwrap();

        if fs::hard_link(&binary, &alias).is_err() {
            return; // Filesystem without hard links; the hazard cannot arise.
        }

        // What `ensure_alias` does when its `hard_link` loses the race: the alias is
        // already there, so it must stop rather than fall through to the copy.
        assert!(fs::hard_link(&binary, &alias).is_err(), "EEXIST expected");
        assert!(alias.exists(), "the guard's condition");

        assert_eq!(
            fs::metadata(&binary).unwrap().len(),
            4096,
            "the running binary was truncated by refreshing its own alias"
        );
    }

    /// The on-disk file name for one of the pair, on this platform.
    fn exe_name(stem: &str) -> String {
        if cfg!(windows) {
            format!("{stem}.exe")
        } else {
            stem.to_string()
        }
    }

    #[test]
    fn dev_prune_creates_devp_beside_it() {
        let dir = tempfile::TempDir::new().unwrap();
        let canonical = dir.path().join(exe_name("dev-prune"));
        fs::write(&canonical, "the binary").unwrap();

        assert_eq!(ensure_twin_of(&canonical, dir.path()), Outcome::Installed);
        let alias = dir.path().join(exe_name("devp"));
        assert!(alias.is_file(), "`devp` was not created");
        assert_eq!(fs::read_to_string(&alias).unwrap(), "the binary");
    }

    /// The pair has to be recoverable from either side.
    ///
    /// Deleting `dev-prune` and leaving `devp` is not hypothetical: an antivirus
    /// quarantine, a half-finished uninstall, or a `Remove-Item` aimed at one name all
    /// produce it. Before this, `devp setup` reported the alias already present and did
    /// nothing, because the only direction it knew how to repair was the other one.
    #[test]
    fn devp_restores_a_missing_dev_prune() {
        let dir = tempfile::TempDir::new().unwrap();
        let alias = dir.path().join(exe_name("devp"));
        fs::write(&alias, "the binary").unwrap();

        assert_eq!(ensure_twin_of(&alias, dir.path()), Outcome::Installed);
        let canonical = dir.path().join(exe_name("dev-prune"));
        assert!(canonical.is_file(), "`dev-prune` was not put back");
        assert_eq!(fs::read_to_string(&canonical).unwrap(), "the binary");
    }

    /// `devp` may create `dev-prune`, never overwrite it.
    ///
    /// Repairing in both directions opens a downgrade: an upgrade replaces `dev-prune`
    /// first and can then fail on a `devp` that is running, which leaves the alias holding
    /// the *older* binary. If the alias were allowed to refresh its twin from there, the
    /// next `devp setup` would quietly reinstall the version the user just upgraded away
    /// from — and report it as a repair.
    #[test]
    fn devp_does_not_overwrite_an_existing_dev_prune() {
        let dir = tempfile::TempDir::new().unwrap();
        let alias = dir.path().join(exe_name("devp"));
        let canonical = dir.path().join(exe_name("dev-prune"));
        fs::write(&alias, "the previous version").unwrap();
        fs::write(&canonical, "the version just upgraded to").unwrap();

        assert_eq!(
            ensure_twin_of(&alias, dir.path()),
            Outcome::AlreadyPresent,
            "`devp` must leave an existing `dev-prune` alone"
        );
        assert_eq!(
            fs::read_to_string(&canonical).unwrap(),
            "the version just upgraded to",
            "`devp` downgraded the binary it was supposed to leave alone"
        );
    }

    #[test]
    fn versions_parse_strictly_or_not_at_all() {
        assert_eq!(parse_version("1.2.3"), Some((1, 2, 3)));
        assert_eq!(parse_version("10.0.0"), Some((10, 0, 0)));
        // Anything this project does not publish must answer None, because a None
        // means "replace the copy" and a mis-parse would order versions wrongly.
        assert_eq!(parse_version("1.2"), None);
        assert_eq!(parse_version("1.2.3.4"), None);
        assert_eq!(parse_version("1.2.3-rc1"), None);
        assert_eq!(parse_version("dev-prune"), None);
        // The version this binary was built with has to be parseable, or the refresh
        // logic can never decide anything.
        assert!(parse_version(constants::VERSION).is_some());
    }

    #[test]
    fn ordering_of_version_triples_matches_semver() {
        assert!(parse_version("1.1.0") > parse_version("1.0.9"));
        assert!(parse_version("2.0.0") > parse_version("1.99.99"));
        assert!(parse_version("1.0.10") > parse_version("1.0.9"));
    }

    #[test]
    fn the_exported_skill_is_the_one_the_binary_was_built_with() {
        // `SKILL.md` is embedded, so a doc edit ships only if the binary is rebuilt.
        // Guard the two properties every consumer of it depends on.
        assert!(EMBEDDED_SKILL_MD.starts_with("---"), "needs frontmatter");
        assert!(
            !EMBEDDED_SKILL_MD.contains("file:///"),
            "SKILL.md is written to every user's machine — it must not contain \
             absolute paths from the author's checkout"
        );
    }
}