Skip to main content

dev_prune/
setup.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Idempotent installation of dev-prune's integrations.
5//
6// dev-prune is only really installed once the parts that let it work without being
7// thought about are in place: the `devp` alias, the managed pair on the user's PATH,
8// the exported `SKILL.md` that AI assistants read (installed into the agent's own
9// skills directory where one exists), the Git hooks that keep the registry current,
10// and the OS scheduler that runs the passes. Each one here is created **only when it
11// is missing**, which is
12// what makes it safe to run on every install, reinstall and upgrade — and it does run
13// on each of those, through the version stamp written at the end of a completed pass.
14//
15// Nothing in here is fatal. A machine without `git`, a `core.hooksPath` that belongs to
16// husky, a locked-down scheduler: each is reported and stepped over, because none of
17// them should stop `devp init` from registering repositories.
18
19use std::fs;
20use std::path::PathBuf;
21
22use anyhow::Result;
23
24use crate::commands::hook::{self, HookState};
25use crate::commands::skill::EMBEDDED_SKILL_MD;
26use crate::config::Registry;
27use crate::constants;
28use crate::daemon;
29use crate::output;
30
31/// File in the config directory recording the version whose last integration pass
32/// completed. A missing or older stamp is what triggers the automatic pass, so a fresh
33/// install and an upgrade both self-heal exactly once.
34const STAMP_FILE: &str = "setup-stamp";
35
36pub use crate::constants::ENV_NO_AUTO_SETUP;
37
38/// Whether the suppression variable is set — by presence, so `=1`, `=true` and even an
39/// empty value all count.
40///
41/// The one predicate every consumer must share. The doctor note used to answer only for
42/// the literal `=1`, so a machine with `=true` had setup switched off with nothing
43/// anywhere saying so.
44pub fn no_auto_setup_requested() -> bool {
45    std::env::var_os(ENV_NO_AUTO_SETUP).is_some()
46}
47
48/// Whether every network call is switched off for this process — same by-presence rule
49/// as [`no_auto_setup_requested`], and for the same reason.
50pub fn offline_requested() -> bool {
51    std::env::var_os(crate::constants::ENV_OFFLINE).is_some()
52}
53
54/// What one integration did during a pass.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum Outcome {
57    /// It was missing and is now in place.
58    Installed,
59    /// It was already in place and was left alone.
60    AlreadyPresent,
61    /// It could not be installed for a reason that is the user's call, not an error.
62    Skipped(String),
63    /// It failed. The pass continues; the reason is reported.
64    Failed(String),
65}
66
67/// The result of one integration pass.
68#[derive(Debug, Default)]
69pub struct SetupReport {
70    items: Vec<(&'static str, Outcome)>,
71}
72
73impl SetupReport {
74    fn push(&mut self, name: &'static str, outcome: Outcome) {
75        self.items.push((name, outcome));
76    }
77
78    /// Whether anything at all was created by this pass.
79    pub fn changed_anything(&self) -> bool {
80        self.items
81            .iter()
82            .any(|(_, o)| matches!(o, Outcome::Installed))
83    }
84
85    /// Whether anything needs the user's attention.
86    pub fn needs_attention(&self) -> bool {
87        self.items
88            .iter()
89            .any(|(_, o)| matches!(o, Outcome::Skipped(_) | Outcome::Failed(_)))
90    }
91
92    /// Print the report.
93    ///
94    /// `verbose` is for the explicit `devp setup`, where "already installed" is the
95    /// answer the user asked for. The automatic pass passes `false` and stays silent
96    /// about everything that was already fine.
97    pub fn print(&self, verbose: bool) {
98        for (name, outcome) in &self.items {
99            match outcome {
100                Outcome::Installed => output::print_success(&format!("{name}: installed.")),
101                Outcome::AlreadyPresent if verbose => {
102                    output::print_info(&format!("{name}: already installed."));
103                }
104                Outcome::AlreadyPresent => {}
105                Outcome::Skipped(why) => {
106                    output::print_warning(&format!("{name}: skipped — {why}"));
107                }
108                Outcome::Failed(why) => {
109                    output::print_error(&format!("{name}: failed — {why}"));
110                }
111            }
112        }
113    }
114}
115
116/// Where the installers put the binary, and the one directory nothing else owns.
117///
118/// Public because it is also what the PATH step registers and what `uninstall` must
119/// take back out again.
120pub fn managed_bin_dir() -> Result<PathBuf> {
121    Ok(Registry::config_dir()?.join("bin"))
122}
123
124pub(crate) fn managed_exe_path() -> Result<PathBuf> {
125    let name = if cfg!(windows) {
126        "dev-prune.exe"
127    } else {
128        "dev-prune"
129    };
130    Ok(managed_bin_dir()?.join(name))
131}
132
133/// Absolute path to a copy of this binary that will still be there next week.
134///
135/// Anything that writes a path down for later — the OS scheduler, the git hooks — has to
136/// use this instead of [`std::env::current_exe`]. dev-prune ships through npm and PyPI as
137/// well as the installers, so the running executable is often somewhere a package manager
138/// owns and will delete: npm's `_npx` cache, uv's ephemeral tool environment, or
139/// `target/debug` during development. An entry recorded there breaks the moment that
140/// directory goes, and neither of these has anywhere to complain — the scheduled task
141/// fails silently every interval, and the hook discards its own output by design. The
142/// only symptom is that nothing ever happens again.
143///
144/// `<config>/bin` is where `install.sh` and `install.ps1` put the binary and nothing else
145/// deletes, so prefer the copy there. When there is none, put one there: the binary that
146/// is running right now is precisely the one that is going to be missing later.
147pub fn stable_exe_path() -> PathBuf {
148    let current = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("dev-prune"));
149    let Ok(managed) = managed_exe_path() else {
150        return current;
151    };
152    if managed == current {
153        return managed;
154    }
155    if managed.is_file() {
156        refresh_managed_copy_if_stale(&current, &managed);
157        return managed;
158    }
159
160    // Only ever clone something that is actually this CLI. `current_exe()` under `cargo
161    // test` is the test harness, and copying that into the config directory would be both
162    // wrong and slow.
163    if !is_this_cli(&current) {
164        return current;
165    }
166
167    let Some(parent) = managed.parent() else {
168        return current;
169    };
170    if fs::create_dir_all(parent).is_err() {
171        return current;
172    }
173    // Hard link where the filesystem allows it — that also keeps the bytes alive when the
174    // package manager deletes the directory the original came from.
175    if fs::hard_link(&current, &managed).is_ok() {
176        return managed;
177    }
178
179    // The same hazard `ensure_alias` documents, through a narrower window: the check at the
180    // top of this function saw no managed copy, but another process created one — as a hard
181    // link to `current` — before the link above ran. `fs::copy` opens its destination with
182    // O_TRUNC, and truncating a hard link empties the shared inode, so the copy would
183    // destroy the very binary it is copying.
184    if managed.is_file() {
185        return managed;
186    }
187
188    // Stage beside and rename into place. A copy straight onto the final name has a
189    // window where the file exists but is incomplete — and this path is what the
190    // scheduler and hooks get registered against, so a process killed mid-copy would
191    // leave a torn binary that every later pass happily points at.
192    let staging = managed.with_extension("new");
193    if fs::copy(&current, &staging).is_ok() && fs::rename(&staging, &managed).is_ok() {
194        return managed;
195    }
196    let _ = fs::remove_file(&staging);
197    // The rename loses only to a concurrent invocation that installed its own copy,
198    // which serves exactly as well.
199    if managed.is_file() { managed } else { current }
200}
201
202/// Whether this path names one of the CLI's own binaries, by file stem.
203fn is_this_cli(path: &std::path::Path) -> bool {
204    path.file_stem()
205        .and_then(|s| s.to_str())
206        .is_some_and(|stem| stem == "dev-prune" || stem == "devp")
207}
208
209/// Replace the managed copy when it is an older release than the binary running now.
210///
211/// The scheduler and the hooks point at the managed copy precisely because it outlives
212/// package-manager caches — which also means an upgrade through cargo, npm or uv changes
213/// the running binary but not the one the integrations run, and the machine quietly
214/// keeps pruning with the previous version forever.
215///
216/// Staleness is decided by asking the copy its version, not by mtime or content: an
217/// *older* binary running out of a stale npx cache must not overwrite a newer managed
218/// copy, and content inequality cannot say which of the two is the upgrade. A copy that
219/// cannot state a version at all is replaced too — whatever it is, it is not a working
220/// build of this CLI.
221fn refresh_managed_copy_if_stale(current: &std::path::Path, managed: &std::path::Path) {
222    if !is_this_cli(current) || same_contents(managed, current) {
223        return;
224    }
225    match (binary_version(managed), parse_version(constants::VERSION)) {
226        (Some(theirs), Some(ours)) if theirs >= ours => return,
227        _ => {}
228    }
229    // Write beside and rename into place, so a scheduler firing mid-copy never runs a
230    // torn binary. A managed copy that is itself running cannot be renamed over on
231    // Windows; the refresh simply waits for a pass when it is not.
232    let staging = managed.with_extension("new");
233    if fs::copy(current, &staging).is_ok() && fs::rename(&staging, managed).is_err() {
234        let _ = fs::remove_file(&staging);
235    }
236}
237
238/// The `major.minor.patch` a binary reports for itself, if it can.
239pub(crate) fn binary_version(exe: &std::path::Path) -> Option<(u64, u64, u64)> {
240    let output = crate::spawn::command(exe).arg("--version").output().ok()?;
241    if !output.status.success() {
242        return None;
243    }
244    version_in_output(&String::from_utf8_lossy(&output.stdout))
245}
246
247/// The first `x.y.z` in a `--version` output, with or without the `v` this CLI prints.
248///
249/// Split out so it can be tested against real output. It has to accept `v1.7.0` because
250/// that is the only spelling `print_version_info` produces — the banner ends `v1.7.0`
251/// and the line under it reads `dev-prune (devp) v1.7.0`, and a bare `1.7.0` appears
252/// nowhere. Parsing the tokens without stripping that `v` answered `None` for every real
253/// dev-prune on the machine, and `doctor`'s "Other copies" check reads `None` as "not a
254/// dev-prune at all" — so it reported "none on PATH running a different version" however
255/// many stale copies were sitting there.
256fn version_in_output(text: &str) -> Option<(u64, u64, u64)> {
257    text.split_whitespace()
258        .find_map(|token| parse_version(token.strip_prefix('v').unwrap_or(token)))
259}
260
261/// Parse `x.y.z` into an orderable triple. Anything else — including the pre-release
262/// and build suffixes this project never publishes — answers `None`.
263pub(crate) fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
264    let mut parts = text.split('.');
265    let triple = (
266        parts.next()?.parse().ok()?,
267        parts.next()?.parse().ok()?,
268        parts.next()?.parse().ok()?,
269    );
270    parts.next().is_none().then_some(triple)
271}
272
273/// Keep `dev-prune` and `devp` beside each other, whichever of the two is running.
274///
275/// The pair is one binary under two names, and either one can be the survivor. An upgrade
276/// that could not replace a running `devp` leaves a stale alias; an antivirus quarantine,
277/// a half-finished uninstall or a `Remove-Item` aimed at the wrong name leaves only
278/// `devp`. So this restores *the other* name in whichever direction is missing, rather
279/// than only ever creating `devp` — running either one puts the pair back.
280pub fn ensure_alias() -> Outcome {
281    // WinGet, Scoop and Homebrew each install into a directory they version and replace
282    // whole on upgrade, and each ships both names in the package itself — so there is
283    // nothing to create here, and creating it would be actively wrong twice over. The
284    // twin would be orphaned by the next upgrade, still on PATH, still running the old
285    // release; and writing a second executable beside a freshly downloaded unsigned
286    // binary on its first run is a behavioural malware signature. WinGet's own
287    // post-install validation flags exactly that, which is how this was found.
288    if crate::channel::Channel::detect().replaces_its_directory() {
289        return Outcome::AlreadyPresent;
290    }
291    let Ok(current_exe) = std::env::current_exe() else {
292        return Outcome::Failed("could not locate the running executable".to_string());
293    };
294    let Some(parent_dir) = current_exe.parent() else {
295        return Outcome::Failed("the running executable has no parent directory".to_string());
296    };
297
298    ensure_twin_of(&current_exe, parent_dir)
299}
300
301/// The half of [`ensure_alias`] that takes its paths as arguments, so tests can drive both
302/// directions without being the binary they are testing.
303fn ensure_twin_of(current_exe: &std::path::Path, parent_dir: &std::path::Path) -> Outcome {
304    let running_as_alias = current_exe
305        .file_stem()
306        .and_then(|s| s.to_str())
307        .is_some_and(|stem| stem == "devp");
308
309    // `dev-prune` is the canonical name, and only it may overwrite its twin.
310    //
311    // Installers write `dev-prune` first and upgrades replace it first, so it is never the
312    // older of the two — a stale `devp` is worth replacing, because otherwise it silently
313    // runs the previous version. The reverse is not safe: an upgrade that replaced
314    // `dev-prune` and then failed on a running `devp` leaves exactly the state where the
315    // alias is the *older* binary, and refreshing from there would quietly reinstall the
316    // version the user just upgraded away from. So `devp` may only create a `dev-prune`
317    // that is missing outright.
318    let (twin_name, may_refresh) = if running_as_alias {
319        (
320            if cfg!(windows) {
321                "dev-prune.exe"
322            } else {
323                "dev-prune"
324            },
325            false,
326        )
327    } else {
328        (if cfg!(windows) { "devp.exe" } else { "devp" }, true)
329    };
330    let twin_exe = parent_dir.join(twin_name);
331
332    if twin_exe.exists() {
333        if !may_refresh || same_contents(&twin_exe, current_exe) {
334            return Outcome::AlreadyPresent;
335        }
336        // Replacing a running executable fails on Windows; that is fine, the alias is
337        // simply refreshed by the next invocation that is not itself `devp`.
338        if fs::remove_file(&twin_exe).is_err() {
339            return Outcome::Skipped(format!(
340                "`{twin_name}` is in use and could not be refreshed — re-run `devp setup` \
341                 from a terminal that is not running it"
342            ));
343        }
344    }
345
346    if fs::hard_link(current_exe, &twin_exe).is_ok() {
347        return Outcome::Installed;
348    }
349
350    // The copy is the fallback for filesystems without hard links — but it must never
351    // run when the alias already exists, because the reason `hard_link` usually fails is
352    // that another process created it a moment ago, as a hard link to this very
353    // executable. `fs::copy` opens its destination with O_TRUNC, and truncating a hard
354    // link truncates the shared inode: the copy would empty the running binary and then
355    // copy zero bytes from it.
356    //
357    // That is not hypothetical. It is what turned every macOS CI run red. The 28
358    // integration tests launch at once, one wins the link, the losers fall through to
359    // here, and `target/debug/dev-prune` becomes a zero-byte file. macOS `posix_spawn`
360    // answers ENOEXEC by handing the file to `/bin/sh`, so every later invocation
361    // "succeeded" with exit 0 and printed nothing — for two hours the tests looked like
362    // 27 unrelated assertion failures.
363    if twin_exe.exists() {
364        return Outcome::AlreadyPresent;
365    }
366
367    // Stage beside and rename into place: copied straight onto the final name, the
368    // alias would exist-but-be-incomplete for the length of the copy, and a `devp`
369    // typed in that window executes a torn binary.
370    let staging = twin_exe.with_extension("new");
371    if fs::copy(current_exe, &staging).is_ok() && fs::rename(&staging, &twin_exe).is_ok() {
372        return Outcome::Installed;
373    }
374    let _ = fs::remove_file(&staging);
375    if twin_exe.exists() {
376        // A concurrent invocation won the rename; its alias serves exactly as well.
377        return Outcome::AlreadyPresent;
378    }
379    Outcome::Failed(format!(
380        "could not create `{}`",
381        output::clean_path(&twin_exe)
382    ))
383}
384
385/// Sameness test for two executables, cheap in the common case.
386///
387/// A hard link makes size and mtime equal by construction, so the usual layout answers
388/// without reading either file. When only the mtime differs — the alias came from the
389/// copy fallback, which does not preserve timestamps — the bytes themselves decide,
390/// because calling that pair "different" made every single invocation delete and
391/// recreate an alias whose content never changed.
392fn same_contents(a: &std::path::Path, b: &std::path::Path) -> bool {
393    let (Ok(ma), Ok(mb)) = (fs::metadata(a), fs::metadata(b)) else {
394        return false;
395    };
396    if ma.len() != mb.len() {
397        return false;
398    }
399    if ma.modified().ok() == mb.modified().ok() {
400        return true;
401    }
402    match (fs::read(a), fs::read(b)) {
403        (Ok(ca), Ok(cb)) => ca == cb,
404        _ => false,
405    }
406}
407
408/// Path that `devp skill` and this module export `SKILL.md` to.
409pub fn skill_path() -> Result<PathBuf> {
410    Ok(Registry::config_dir()?.join("SKILL.md"))
411}
412
413/// Export the bundled `SKILL.md` so AI assistants have something to read.
414///
415/// Rewritten whenever it differs from the embedded copy, since an upgrade that changes
416/// the skill must not leave the previous version's instructions on disk.
417pub fn ensure_skill_file() -> Outcome {
418    match Registry::config_dir() {
419        Ok(dir) => ensure_skill_file_in(&dir),
420        Err(_) => Outcome::Failed("could not determine the config directory".to_string()),
421    }
422}
423
424fn ensure_skill_file_in(config_dir: &std::path::Path) -> Outcome {
425    let target = config_dir.join("SKILL.md");
426
427    if fs::read_to_string(&target).is_ok_and(|current| current == EMBEDDED_SKILL_MD) {
428        return Outcome::AlreadyPresent;
429    }
430
431    let _ = fs::create_dir_all(config_dir);
432    match fs::write(&target, EMBEDDED_SKILL_MD) {
433        Ok(()) => Outcome::Installed,
434        Err(e) => Outcome::Failed(format!(
435            "could not write {}: {e}",
436            output::clean_path(&target)
437        )),
438    }
439}
440
441/// The per-skill directories of AI coding agents that are installed under `home`.
442///
443/// Detection only — an agent's home directory is created by the agent, never by this
444/// pass. Today that is Claude Code, whose Agent Skills live at
445/// `~/.claude/skills/<name>/SKILL.md`. Assistants without an on-disk skill format get
446/// the onboarding prompt from `devp skill` instead.
447fn agent_skill_roots_under(home: &std::path::Path) -> Vec<PathBuf> {
448    let mut roots = Vec::new();
449    let claude = home.join(constants::CLAUDE_HOME_DIR);
450    if claude.is_dir() {
451        roots.push(
452            claude
453                .join(constants::AGENT_SKILLS_SUBDIR)
454                .join(constants::APP_NAME),
455        );
456    }
457    roots
458}
459
460/// The agent skill directories on this machine. Empty when no agent is installed.
461pub fn agent_skill_roots() -> Vec<PathBuf> {
462    dirs::home_dir()
463        .map(|home| agent_skill_roots_under(&home))
464        .unwrap_or_default()
465}
466
467/// Install the skill into every detected agent's skills directory.
468pub fn ensure_agent_skills() -> Outcome {
469    ensure_agent_skills_at(&agent_skill_roots())
470}
471
472/// Every managed copy of `SKILL.md` that is not the one this binary carries.
473///
474/// The copies are refreshed by [`ensure_integrations`], which runs only while
475/// auto-setup is on. With it off, an upgrade leaves the previous release's instructions
476/// sitting in the agent's skills directory, and the agent goes on describing flags that
477/// no longer exist — confidently, because nothing told it otherwise.
478pub fn stale_skill_copies() -> Vec<PathBuf> {
479    let mut copies: Vec<PathBuf> = skill_path().into_iter().collect();
480    copies.extend(agent_skill_roots().into_iter().map(|r| r.join("SKILL.md")));
481    copies
482        .into_iter()
483        .filter(|p| fs::read_to_string(p).is_ok_and(|current| current != EMBEDDED_SKILL_MD))
484        .collect()
485}
486
487/// Rewrite every managed copy of `SKILL.md` from the embedded one.
488///
489/// Both copies, not just the export: the one an assistant actually reads is the one in
490/// its own skills directory, so repairing the export alone would report success and
491/// leave the stale instructions in the only place that matters.
492pub fn ensure_skill_copies() -> Outcome {
493    let mut installed = false;
494    for outcome in [ensure_skill_file(), ensure_agent_skills()] {
495        match outcome {
496            Outcome::Installed => installed = true,
497            // No agent on this machine is not a failure to repair.
498            Outcome::AlreadyPresent | Outcome::Skipped(_) => {}
499            failed => return failed,
500        }
501    }
502    if installed {
503        Outcome::Installed
504    } else {
505        Outcome::AlreadyPresent
506    }
507}
508
509fn ensure_agent_skills_at(roots: &[PathBuf]) -> Outcome {
510    if roots.is_empty() {
511        return Outcome::Skipped(
512            "no AI agent skills directory was found — `devp skill` prints import prompts instead"
513                .to_string(),
514        );
515    }
516    let mut installed = false;
517    for root in roots {
518        match ensure_skill_file_in(root) {
519            Outcome::Installed => installed = true,
520            Outcome::AlreadyPresent => {}
521            other => return other,
522        }
523    }
524    if installed {
525        Outcome::Installed
526    } else {
527        Outcome::AlreadyPresent
528    }
529}
530
531/// Make the managed pair reachable from a fresh shell.
532///
533/// This is the step that lets `pip install dev-prune` in a virtualenv survive the
534/// virtualenv: the binaries pip placed vanish with the environment, but the managed
535/// copy under `<config>/bin` does not, and after this step it is the one a new
536/// terminal finds. See [`crate::pathenv`] for what "reachable" means per platform.
537pub fn ensure_command_on_path() -> Outcome {
538    let managed = stable_exe_path();
539    let is_managed_copy =
540        managed_exe_path().is_ok_and(|expected| expected == managed) && managed.is_file();
541    if !is_managed_copy {
542        // No managed copy exists and none could be created — under `cargo test` the
543        // running executable is the harness, and cloning that would be wrong. There is
544        // nothing durable to put on PATH.
545        return Outcome::Skipped("no managed copy of the binary exists to put on PATH".to_string());
546    }
547    let Some(bin_dir) = managed.parent() else {
548        return Outcome::Failed("the managed binary has no parent directory".to_string());
549    };
550    // `devp` has to sit beside it, or the PATH entry only ever finds `dev-prune`.
551    if let Outcome::Failed(why) = ensure_twin_of(&managed, bin_dir) {
552        return Outcome::Failed(why);
553    }
554    crate::pathenv::ensure_reachable(bin_dir)
555}
556
557/// Write the icon assets and register `*.devprune.json` with the OS file manager.
558///
559/// Part of the automatic pass rather than a separate errand, because "the config file has
560/// an icon" is not a thing anybody thinks to go and ask for. Everything it writes lives
561/// under the config directory and the user's own XDG data directory, `devp uninstall`
562/// removes all of it, and it touches no editor settings, no PATH and no shell profile —
563/// so there is nothing here that needs to be asked about first.
564///
565/// Unlike the hooks and the scheduler, this has no opt-out switch of its own. Files
566/// dropped into the user's data directory are not a background process and not a change
567/// in behaviour; `auto_setup` already covers "install nothing at all".
568fn ensure_icons() -> Outcome {
569    if crate::commands::icon::is_registered() {
570        return Outcome::AlreadyPresent;
571    }
572    match crate::commands::icon::sync_app_directory() {
573        Ok(()) => Outcome::Installed,
574        Err(e) => Outcome::Failed(format!("{e:#}")),
575    }
576}
577
578/// Install the global Git hooks, unless git is absent or the slot belongs to someone else.
579///
580/// `chain` is `auto_hooks_chain`: with it on, a slot that belongs to husky is not a
581/// reason to skip, because dev-prune can install in front and forward every hook back.
582pub fn ensure_hooks(chain: bool) -> Outcome {
583    if !hook::git_available() {
584        return Outcome::Skipped(format!(
585            "\n    {}",
586            hook::GIT_MISSING_HELP.replace('\n', "\n    ")
587        ));
588    }
589
590    match hook::state() {
591        // "Installed" is not the question — "installed and pointing at a binary that
592        // still exists" is. A hook backgrounds itself and discards its own output, so
593        // one left pointing at a deleted npm cache dies silently on every commit and
594        // nothing ever registers again; this pass is the only thing that ever looks.
595        // Two reasons to rewrite a working install: it names a binary that is gone, or
596        // it predates the passthrough shims and is silently shadowing every repository's
597        // own `.git/hooks`. Neither reports itself — a hook discards its own output by
598        // design — so the upgrade pass is the only thing that will ever notice.
599        Ok(HookState::Active) if hook_target_is_dead() || hook::shims_incomplete() => {
600            match hook::install() {
601                Ok(()) => Outcome::Installed,
602                Err(e) => Outcome::Failed(format!("{e:#}")),
603            }
604        }
605        Ok(HookState::Active) => Outcome::AlreadyPresent,
606        // Drift is repaired here rather than reported: the setup pass already runs on
607        // install, on update and on a schedule, and a chain the user opted into is a
608        // chain they want kept current.
609        Ok(HookState::Chained { drifted, .. }) if !drifted.is_empty() => {
610            match hook::install_with(true) {
611                Ok(()) => Outcome::Installed,
612                Err(e) => Outcome::Failed(format!("{e:#}")),
613            }
614        }
615        Ok(HookState::Chained { .. }) if hook_target_is_dead() => match hook::install_with(true) {
616            Ok(()) => Outcome::Installed,
617            Err(e) => Outcome::Failed(format!("{e:#}")),
618        },
619        Ok(HookState::Chained { .. }) => Outcome::AlreadyPresent,
620        Ok(HookState::Foreign(_)) if chain => match hook::install_with(true) {
621            Ok(()) => Outcome::Installed,
622            Err(e) => Outcome::Failed(format!("{e:#}")),
623        },
624        Ok(HookState::Foreign(existing)) => Outcome::Skipped(format!(
625            "`core.hooksPath` is already set to `{existing}`, which belongs to another tool.\n    \
626             Git allows only one hooks directory, so dev-prune will not take the slot.\n    \
627             `devp hook install --chain` installs in front of it instead — dev-prune registers \
628             the repo, then hands every hook on to `{existing}`, and `devp hook uninstall` puts \
629             the original setting back (`devp config set auto_hooks_chain true` makes that \
630             the standing answer). Or skip it: `devp link .` does the same job by hand."
631        )),
632        Ok(HookState::Absent) => match hook::install() {
633            Ok(()) => Outcome::Installed,
634            Err(e) => Outcome::Failed(format!("{e:#}")),
635        },
636        Err(e) => Outcome::Failed(format!("{e:#}")),
637    }
638}
639
640/// Whether the installed hooks name a binary that no longer exists.
641fn hook_target_is_dead() -> bool {
642    hook::registered_exe_path().is_some_and(|exe| !exe.exists())
643}
644
645/// Install the OS scheduler if it is not already registered.
646pub fn ensure_daemon(interval_days: u64) -> Outcome {
647    match daemon::daemon_status() {
648        // A task whose binary has been deleted keeps reporting itself `Ready` and dies
649        // the instant it fires, every interval, with nowhere to complain. Re-register
650        // it against the stable path instead of counting the corpse as present.
651        Ok(daemon::DaemonStatus::Installed)
652            if daemon::registered_exe_path().is_some_and(|exe| !exe.exists()) =>
653        {
654            match daemon::install_daemon(interval_days) {
655                Ok(()) => Outcome::Installed,
656                Err(e) => Outcome::Failed(format!("{e:#}")),
657            }
658        }
659        // A task registered by a version that only knew the interactive logon flashes a
660        // console window at whoever is logged in every time it fires — the single most
661        // trust-destroying thing a background tool can do. Re-register it hidden; a
662        // machine whose scheduler refuses the hidden logon remembers the refusal and is
663        // not asked again.
664        Ok(daemon::DaemonStatus::Installed) if daemon::wants_hidden_upgrade() => {
665            match daemon::install_daemon(interval_days) {
666                Ok(()) => Outcome::Installed,
667                Err(e) => Outcome::Failed(format!("{e:#}")),
668            }
669        }
670        // A settled, hidden task still needs its windowless twin kept current: the twin
671        // is a copy of the binary, so an upgrade that replaced the binary would otherwise
672        // leave the daemon firing the previous release. No-op on the other platforms, and
673        // when no twin is in use.
674        Ok(daemon::DaemonStatus::Installed) => {
675            daemon::refresh_hidden_twin();
676            Outcome::AlreadyPresent
677        }
678        Ok(daemon::DaemonStatus::NotInstalled) => match daemon::install_daemon(interval_days) {
679            Ok(()) => Outcome::Installed,
680            Err(e) => Outcome::Failed(format!("{e:#}")),
681        },
682        // `Unknown` means the query itself could not be answered — the scheduler may
683        // well be there. Installing over it would fail on every command from now on, so
684        // this reports and steps over instead of guessing. The platform backends are
685        // written to keep this case narrow: anything they can answer definitely, they do.
686        Ok(daemon::DaemonStatus::Unknown(why)) => {
687            Outcome::Skipped(format!("scheduler state could not be read — {why}"))
688        }
689        Err(e) => Outcome::Failed(format!("{e:#}")),
690    }
691}
692
693/// Whether unattended installation is permitted at all.
694///
695/// Both switches exist because these integrations write outside dev-prune's own config
696/// directory — a scheduled task, a global git setting — and there are places that must
697/// never happen unasked: container images, CI, and this project's own test suite.
698pub fn auto_setup_enabled(registry: &Registry) -> bool {
699    !no_auto_setup_requested() && registry.settings.auto_setup && unattended_environment().is_none()
700}
701
702/// The reason this looks like a machine nobody is sitting at, if it does.
703///
704/// `DEV_PRUNE_NO_AUTO_SETUP` and `auto_setup` are both switches you have to set *before*
705/// the first run — which is exactly the run that installs things, so in a container or a
706/// CI job the damage is done by the time there is anywhere to set them. Detecting the
707/// environment is the only opt-out that works on the first run, which is the only run
708/// that matters here.
709///
710/// Deliberately conservative: every signal below is one that CI providers and container
711/// runtimes set themselves, so a developer's own shell will not trip it. Someone who
712/// genuinely wants the integrations in CI can still ask in so many words with
713/// `devp setup`, which never consults this.
714pub fn unattended_environment() -> Option<&'static str> {
715    // Set by GitHub Actions, GitLab CI, CircleCI, Travis, Jenkins (via pipeline), Woodpecker
716    // and most others. `CI=true` is the closest thing this space has to a standard.
717    for var in [
718        "CI",
719        "CONTINUOUS_INTEGRATION",
720        "BUILD_NUMBER",
721        "GITHUB_ACTIONS",
722    ] {
723        if let Some(value) = std::env::var_os(var) {
724            // `CI=false` is set explicitly by some tools to mean "not CI", and honouring
725            // the word rather than the presence is what the user plainly meant.
726            let value = value.to_string_lossy();
727            if !value.is_empty() && !value.eq_ignore_ascii_case("false") {
728                return Some("this looks like a CI runner");
729            }
730        }
731    }
732
733    // Docker writes this marker into every container it builds from a Dockerfile;
734    // Podman and other OCI runtimes write the `container` variable instead.
735    #[cfg(unix)]
736    if std::path::Path::new("/.dockerenv").exists() {
737        return Some("this looks like a container");
738    }
739    if std::env::var_os("container").is_some() {
740        return Some("this looks like a container");
741    }
742
743    None
744}
745
746/// Whether this integration pass was asked for by name.
747///
748/// The only thing it decides is the `devp` twin. Writing a second executable beside the
749/// first is a self-installation, and doing it *unasked*, on the first run of a freshly
750/// downloaded unsigned binary, alongside registering a scheduled task, is a behavioural
751/// malware signature — it is what earned this package a `Validation-Defender-Error` on
752/// microsoft/winget-pkgs#422665. Asked for in so many words, the same write is an
753/// ordinary install step. Nothing else in the pass changes.
754#[derive(Clone, Copy, PartialEq, Eq)]
755pub enum Consent {
756    /// `devp setup`, or `devp doctor --fix`.
757    Explicit,
758    /// The pass that runs on its own when `auto_setup` is on.
759    Unattended,
760}
761
762/// Run an integration pass unless unattended installation is switched off.
763///
764/// Every caller that the user did not name explicitly goes through this. `devp setup`
765/// calls [`ensure_integrations`] with [`Consent::Explicit`]: asking for it in so many
766/// words is consent.
767pub fn ensure_integrations_if_enabled(registry: &Registry) -> Option<SetupReport> {
768    auto_setup_enabled(registry).then(|| ensure_integrations(registry, Consent::Unattended))
769}
770
771/// Run one integration pass, installing whatever is missing.
772///
773/// The two per-integration settings (`auto_daemon`, `auto_hooks`) are honoured here, so
774/// turning one off turns it off for every future pass as well as this one.
775pub fn ensure_integrations(registry: &Registry, consent: Consent) -> SetupReport {
776    let mut report = SetupReport::default();
777
778    // Only when asked. This is the twin *beside the running binary*, which on an
779    // unattended pass means beside whatever the delivery vehicle happened to be: npm's
780    // cache, a venv's `Scripts`, a Downloads folder. Every channel already ships both
781    // names as real files — the archives, the npm and PyPI packages, and two `[[bin]]`
782    // targets for `cargo install` — so there is normally nothing to create, and the one
783    // case left over is a manual install that skipped `dev-prune setup`, which `devp
784    // doctor` reports with a one-command fix.
785    //
786    // The pair that actually matters is not this one. `ensure_command_on_path` below
787    // keeps `dev-prune` and `devp` together in the managed `bin` directory, which is
788    // the directory on the user's PATH and the one `devp uninstall` knows about, and it
789    // runs on every pass.
790    if consent == Consent::Explicit {
791        report.push("dev-prune/devp pair", ensure_alias());
792    }
793    report.push("Command on PATH", ensure_command_on_path());
794    report.push("SKILL.md", ensure_skill_file());
795    // Only reported when an agent is actually installed: a machine without one would
796    // otherwise see a "skipped" warning about software it never had, on every install.
797    if !agent_skill_roots().is_empty() {
798        report.push("AI agent skills", ensure_agent_skills());
799    }
800    report.push("File icons", ensure_icons());
801
802    if registry.settings.auto_hooks {
803        report.push(
804            "Git hooks",
805            ensure_hooks(registry.settings.auto_hooks_chain),
806        );
807    } else {
808        report.push(
809            "Git hooks",
810            Outcome::Skipped("`auto_hooks` is false — enable with `devp hook install`".to_string()),
811        );
812    }
813
814    if registry.settings.auto_daemon {
815        report.push(
816            "Background scheduler",
817            ensure_daemon(registry.settings.check_interval_days),
818        );
819    } else {
820        report.push(
821            "Background scheduler",
822            Outcome::Skipped(
823                "`auto_daemon` is false — enable with `devp daemon install`".to_string(),
824            ),
825        );
826    }
827
828    report
829}
830
831// ── VS Code extension ────────────────────────────────────────────────────────
832
833/// Marker recording that the extension question was asked (or found already answered by
834/// an existing install). One file, no content: the offer is made once ever, whatever
835/// the answer was — a declined install must not be re-litigated on every upgrade.
836const VSCODE_OFFER_STAMP: &str = "vscode-ext-offered";
837
838/// A VS Code-compatible editor found on PATH.
839struct EditorCli {
840    /// The command to invoke — on Windows the `.cmd` launcher, because the entry on
841    /// PATH is a batch file, not an `.exe`, and `Command::new("code")` would miss it.
842    cli: String,
843    /// The editor's name as a person knows it, for the prompt and per-editor results.
844    label: &'static str,
845}
846
847/// Every VS Code-compatible editor on PATH, in the order listed here.
848///
849/// All of these forks keep the upstream CLI protocol (`--version`, `--list-extensions`,
850/// `--install-extension`), so one code path drives them all. What differs is the
851/// registry each one resolves an extension ID against: VS Code uses the Microsoft
852/// Marketplace, VSCodium/Windsurf/Positron/Kiro/Trae use OpenVSX, Cursor and
853/// Antigravity run their own mirrors. An ID install can therefore fail on a fork whose
854/// registry does not carry the extension yet — which is why the installer falls back
855/// to the `.vsix` from the GitHub release, the artifact every registry copy is built
856/// from.
857///
858/// The list is candidate CLI names, not a claim that any of them is installed: each is
859/// asked for its `--version` and dropped if it does not answer. Adding a fork therefore
860/// costs one failed spawn on a machine without it, and is what stops the extension
861/// offer from being a VS Code-only courtesy on an editor that is a VS Code build with a
862/// different name on the window.
863fn detect_vscode_editors() -> Vec<EditorCli> {
864    const CANDIDATES: &[(&str, &str)] = &[
865        ("code", "VS Code"),
866        ("code-insiders", "VS Code Insiders"),
867        ("codium", "VSCodium"),
868        ("codium-insiders", "VSCodium Insiders"),
869        ("cursor", "Cursor"),
870        ("windsurf", "Windsurf"),
871        ("antigravity", "Antigravity"),
872        ("trae", "Trae"),
873        ("positron", "Positron"),
874        ("kiro", "Kiro"),
875    ];
876    CANDIDATES
877        .iter()
878        .filter_map(|(name, label)| {
879            let cli = if cfg!(windows) {
880                format!("{name}.cmd")
881            } else {
882                (*name).to_string()
883            };
884            let responds = crate::spawn::command(&cli)
885                .arg("--version")
886                .stdin(std::process::Stdio::null())
887                .stdout(std::process::Stdio::null())
888                .stderr(std::process::Stdio::null())
889                .status()
890                .map(|s| s.success())
891                .unwrap_or(false);
892            responds.then_some(EditorCli { cli, label })
893        })
894        .collect()
895}
896
897fn vscode_extension_installed(cli: &str) -> bool {
898    crate::spawn::command(cli)
899        .arg("--list-extensions")
900        .stdin(std::process::Stdio::null())
901        .output()
902        .map(|out| {
903            String::from_utf8_lossy(&out.stdout).lines().any(|line| {
904                line.trim()
905                    .eq_ignore_ascii_case(constants::VSCODE_EXTENSION_ID)
906            })
907        })
908        .unwrap_or(false)
909}
910
911/// Download the `.vsix` from the newest extension release into the config directory.
912///
913/// The release asset is the source of truth for the extension — the Marketplace and
914/// OpenVSX listings are published from that exact file — so when an editor's registry
915/// cannot resolve the ID (a fork whose registry does not carry the extension),
916/// installing the release file directly gets the same bits through a channel every fork
917/// supports. Editors update a `.vsix`-installed extension from their registry once a
918/// newer listed version appears, so this install self-heals into the normal update flow.
919///
920/// Deliberately not `releases/latest`. The extension has its own tags and its own
921/// release page, and those releases are marked "not latest" so they cannot displace the
922/// binary release that `devp update` reads. The consequence is that the newest one has
923/// to be found by walking the listing for a [`VSCODE_RELEASE_TAG_PREFIX`] tag.
924///
925/// [`VSCODE_RELEASE_TAG_PREFIX`]: crate::constants::VSCODE_RELEASE_TAG_PREFIX
926fn download_release_vsix() -> Option<std::path::PathBuf> {
927    use std::time::Duration;
928
929    if offline_requested() {
930        return None;
931    }
932
933    let fetch = |url: &str| {
934        ureq::get(url)
935            .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
936            .header("Accept", "application/vnd.github+json")
937            .config()
938            .timeout_global(Some(Duration::from_secs(30)))
939            .build()
940            .call()
941    };
942
943    let body = fetch(constants::RELEASES_LIST_API_URL)
944        .ok()?
945        .body_mut()
946        .read_to_string()
947        .ok()?;
948    let json: serde_json::Value = serde_json::from_str(&body).ok()?;
949    // GitHub returns this listing newest-first, so the first extension release found is
950    // the current one. Draft releases carry no downloadable asset, and a pre-release of
951    // the extension is one deliberately not being offered to people who did not ask.
952    let asset = json.as_array()?.iter().find_map(|release| {
953        let tag = release.get("tag_name")?.as_str()?;
954        if !tag.starts_with(constants::VSCODE_RELEASE_TAG_PREFIX) {
955            return None;
956        }
957        if release.get("draft")?.as_bool()? || release.get("prerelease")?.as_bool()? {
958            return None;
959        }
960        release.get("assets")?.as_array()?.iter().find_map(|asset| {
961            let name = asset.get("name")?.as_str()?;
962            if !name.ends_with(".vsix") {
963                return None;
964            }
965            let url = asset.get("browser_download_url")?.as_str()?;
966            Some((name.to_string(), url.to_string()))
967        })
968    })?;
969
970    let bytes = fetch(&asset.1).ok()?.body_mut().read_to_vec().ok()?;
971    // The config directory, not the shared system temp dir: on a multi-user machine
972    // `%TEMP%`-style paths are predictable and writable by others, and the editor is
973    // about to execute what this file contains. The caller deletes it after installing.
974    let dir = Registry::config_dir().ok()?;
975    fs::create_dir_all(&dir).ok()?;
976    let path = dir.join(&asset.0);
977    fs::write(&path, bytes).ok()?;
978    Some(path)
979}
980
981/// `<cli> --install-extension <arg>`, surfacing the editor's own output.
982fn run_install(cli: &str, arg: &str) -> bool {
983    crate::spawn::command(cli)
984        .args(["--install-extension", arg])
985        .stdin(std::process::Stdio::null())
986        .status()
987        .map(|s| s.success())
988        .unwrap_or(false)
989}
990
991/// Offer to install the editor extension, once ever, when a VS Code-family editor is
992/// present.
993///
994/// This asks rather than installs because the editor is not dev-prune's territory the
995/// way its own config directory is. Every gate below is a way of making sure a person
996/// is actually there to answer: no marker yet, not a CI runner or container, both ends
997/// of the terminal attached. When no editor is found nothing is written, so installing
998/// one later and re-running `devp setup` still gets the one offer.
999pub fn offer_vscode_extension() {
1000    use std::io::{IsTerminal, Write};
1001
1002    let Ok(config_dir) = Registry::config_dir() else {
1003        return;
1004    };
1005    if config_dir.join(VSCODE_OFFER_STAMP).exists() {
1006        return;
1007    }
1008    if no_auto_setup_requested()
1009        || unattended_environment().is_some()
1010        || !std::io::stdin().is_terminal()
1011        || !std::io::stdout().is_terminal()
1012    {
1013        return;
1014    }
1015    let editors = detect_vscode_editors();
1016    if editors.is_empty() {
1017        return;
1018    }
1019
1020    let write_marker = || {
1021        let _ = fs::create_dir_all(&config_dir);
1022        let _ = fs::write(config_dir.join(VSCODE_OFFER_STAMP), "");
1023    };
1024
1025    let missing: Vec<&EditorCli> = editors
1026        .iter()
1027        .filter(|e| !vscode_extension_installed(&e.cli))
1028        .collect();
1029    if missing.is_empty() {
1030        write_marker();
1031        return;
1032    }
1033
1034    let names = missing
1035        .iter()
1036        .map(|e| e.label)
1037        .collect::<Vec<_>>()
1038        .join(", ");
1039    println!();
1040    println!("{names} detected — install the dev-prune extension?");
1041    println!("  It validates .devprune.json and shows reclaimable space in the status bar.");
1042    // The listings and the source, before the question rather than after it. This is
1043    // the one prompt that defaults to yes, so the material someone would need in order
1044    // to say no has to be on screen at the moment they answer — not in a doc they would
1045    // have to go and look for.
1046    println!("    Marketplace: {}", constants::VSCODE_MARKETPLACE_URL);
1047    println!("    Open VSX:    {}", constants::OPENVSX_URL);
1048    println!("    Source:      {}", constants::REPO_URL);
1049    print!("  Install it? [Y/n] ");
1050    let _ = std::io::stdout().flush();
1051    let mut answer = String::new();
1052    if std::io::stdin().read_line(&mut answer).is_err() {
1053        return;
1054    }
1055    write_marker();
1056
1057    // A bare Enter accepts. Unlike the uninstall sweep — which deletes — the worst case
1058    // here is an extension the person removes in two clicks, and the gates above have
1059    // already established that a human with a VS Code-family editor is watching.
1060    if !matches!(answer.trim().to_lowercase().as_str(), "" | "y" | "yes") {
1061        output::print_info(&format!(
1062            "Skipped. Install it any time with `{} --install-extension {}`, or from {}.",
1063            missing[0].cli,
1064            constants::VSCODE_EXTENSION_ID,
1065            constants::VSCODE_MARKETPLACE_URL
1066        ));
1067        return;
1068    }
1069
1070    // Fetched at most once, shared by every editor whose registry install fails.
1071    let mut release_vsix: Option<Option<std::path::PathBuf>> = None;
1072    for editor in &missing {
1073        // The editor's own registry first: that install is the one the editor keeps
1074        // up to date by itself.
1075        if run_install(&editor.cli, constants::VSCODE_EXTENSION_ID) {
1076            output::print_success(&format!("{}: extension installed.", editor.label));
1077            continue;
1078        }
1079        // A fork whose registry does not carry the extension — install the `.vsix`
1080        // from the GitHub release instead.
1081        let vsix = release_vsix.get_or_insert_with(download_release_vsix);
1082        match vsix {
1083            Some(path) if run_install(&editor.cli, &path.to_string_lossy()) => {
1084                output::print_success(&format!(
1085                    "{}: extension installed from the GitHub release .vsix.",
1086                    editor.label
1087                ));
1088            }
1089            _ => {
1090                output::print_warning(&format!(
1091                    "{}: could not install it from here. Search the Extensions view for \"dev-prune\", or run `{} --install-extension {}` yourself.",
1092                    editor.label,
1093                    editor.cli,
1094                    constants::VSCODE_EXTENSION_ID
1095                ));
1096            }
1097        }
1098    }
1099    if let Some(Some(path)) = &release_vsix {
1100        let _ = fs::remove_file(path);
1101    }
1102}
1103
1104/// Record that a pass completed for this version.
1105fn write_stamp_in(config_dir: &std::path::Path) {
1106    let _ = fs::create_dir_all(config_dir);
1107    let _ = fs::write(config_dir.join(STAMP_FILE), constants::VERSION);
1108}
1109
1110fn write_stamp() {
1111    if let Ok(dir) = Registry::config_dir() {
1112        write_stamp_in(&dir);
1113    }
1114}
1115
1116fn setup_is_due_in(config_dir: &std::path::Path) -> bool {
1117    !fs::read_to_string(config_dir.join(STAMP_FILE))
1118        .is_ok_and(|stamp| stamp.trim() == constants::VERSION)
1119}
1120
1121/// Whether the unattended pass is due: a fresh install, or the first run after an upgrade.
1122pub fn setup_is_due() -> bool {
1123    Registry::config_dir()
1124        .map(|dir| setup_is_due_in(&dir))
1125        .unwrap_or(false)
1126}
1127
1128/// Whether there is a human at this invocation who could see what was done and undo it.
1129///
1130/// The one question that gates everything dev-prune installs without being asked. CI
1131/// variables and containers answer it directly; a redirected stdin or stdout answers it
1132/// too, because output nobody reads is the same as no output — and an integration
1133/// installed silently is one nobody knows to remove.
1134fn a_person_is_present() -> bool {
1135    use std::io::IsTerminal;
1136    unattended_environment().is_none()
1137        && std::io::stdin().is_terminal()
1138        && std::io::stdout().is_terminal()
1139}
1140
1141/// The unattended pass, run at most once per installed version.
1142///
1143/// Called at the top of every command that a human typed. It is deliberately not called
1144/// for the Git hook's `link --quiet` or the scheduler's `run --daemon`: those run without
1145/// a terminal, and an integration pass that nobody can see is one nobody can refuse.
1146pub fn auto_setup_if_due() {
1147    if !setup_is_due() {
1148        first_run_config_review();
1149        return;
1150    }
1151    // The same question `first_run_config_review` asks, asked one step earlier. It used
1152    // to be asked only about the *prompt*, never about the pass that installs a PATH
1153    // entry, a scheduled task and a git hook — so a binary run once by an automated
1154    // system, with its output captured, silently acquired persistence on that machine.
1155    // Nothing here is skipped permanently: the stamp is not written, so the first run a
1156    // person can actually see does the pass and reports it.
1157    if !a_person_is_present() {
1158        return;
1159    }
1160
1161    review_project_venv_install();
1162
1163    let Ok(registry) = Registry::load() else {
1164        return;
1165    };
1166    let Some(report) = ensure_integrations_if_enabled(&registry) else {
1167        // Suppressed. Stamp anyway, so a machine that opted out does not re-decide
1168        // this on every single command.
1169        write_stamp();
1170        crate::commands::config::skip_config_review();
1171        return;
1172    };
1173    if report.changed_anything() || report.needs_attention() {
1174        output::print_header("dev-prune setup");
1175        report.print(false);
1176        if report.changed_anything() {
1177            output::print_info(
1178                "Run `devp setup --status` to review these, or `devp uninstall` to remove them.",
1179            );
1180        }
1181        println!();
1182    }
1183    write_stamp();
1184    first_run_config_review();
1185}
1186
1187/// Put the defaults in front of the user on a fresh install, and any setting an upgrade
1188/// added that they have never been shown.
1189///
1190/// Separate from the integration stamp on purpose. The integrations are re-checked after
1191/// every upgrade; the settings are not, except for the ones that did not exist last time
1192/// — being asked to reconfirm `idle_days` on each new version would be a nuisance, and a
1193/// nuisance is something people learn to dismiss without reading.
1194///
1195/// Every condition here is a way of asking "is there a person reading this?", because the
1196/// alternative to asking is a prompt written into a log nobody will read, on a run that
1197/// then blocks forever waiting for an answer.
1198fn first_run_config_review() {
1199    if !crate::commands::config::config_review_is_due() {
1200        return;
1201    }
1202
1203    // Deliberately not stamped here. The stamp records that somebody was *shown* the
1204    // declaration, and a cron run, a CI job or a container has nobody to show it to.
1205    // Writing it anyway meant the first unattended `devp` on a machine silently spent
1206    // the one screen that says what dev-prune will not delete — so the person who
1207    // installed it never saw it, and nothing ever offered again. Left unstamped, the
1208    // walkthrough waits for the first run with a human on the other end of it, which is
1209    // the only run it was ever for.
1210    if !a_person_is_present() {
1211        return;
1212    }
1213
1214    // Any error here is the wizard's own reporting; the command the user actually typed
1215    // still runs. A failed walkthrough must not become a failed `devp status`.
1216    if let Err(e) =
1217        crate::commands::config::run_wizard(false, crate::commands::config::Opened::OnItsOwn)
1218    {
1219        output::print_warning(&format!("Could not run the first-run setup ({e:#})."));
1220    }
1221    // Marked regardless of how it ended, including a deliberate quit. This is the one
1222    // caller that runs uninvited, and an unasked-for walkthrough that reappears on every
1223    // subsequent command is worse than one somebody dismissed once on purpose.
1224    crate::commands::config::skip_config_review();
1225    // Same first run, same person already answering questions — the one moment the
1226    // extension offer is a courtesy rather than an interruption.
1227    offer_vscode_extension();
1228    println!();
1229}
1230
1231/// Invalidate the stamp so the next human-run command performs a pass.
1232///
1233/// `uninstall` calls this in reverse — it writes the current stamp — so that removing the
1234/// integrations is not immediately undone by the next command.
1235pub fn suppress_next_auto_setup() {
1236    write_stamp();
1237}
1238
1239/// Say something, once, when this copy is running from inside a project's virtualenv.
1240///
1241/// This is the remedy at the source. By the time a prune pass refuses the environment,
1242/// the user is several days and one confusing error away from the moment they typed
1243/// `pip install dev-prune` with a project activated; saying it here, on the first run
1244/// after that install, is the only chance to explain it while the cause is still in
1245/// living memory. The refusal in the venv adapter stays as the failsafe, for a copy
1246/// installed before this check existed or by somebody who dismissed it.
1247///
1248/// Silent when `requirements.txt` already lists the tool. That is somebody who meant it,
1249/// and being told about a decision you made on purpose is what teaches people to stop
1250/// reading output.
1251fn review_project_venv_install() {
1252    let Ok(exe) = std::env::current_exe() else {
1253        return;
1254    };
1255    let Some(found) = crate::channel::project_venv_install(&exe) else {
1256        return;
1257    };
1258
1259    let requirements = found.project.join("requirements.txt");
1260    let recorded = crate::adapters::venv::requirement_names(&requirements, &mut Vec::new())
1261        .is_some_and(|names| names.iter().any(|n| crate::adapters::venv::is_dev_prune(n)));
1262    if recorded {
1263        return;
1264    }
1265
1266    output::print_header(&format!(
1267        "{} is installed inside this project's virtual environment",
1268        constants::APP_NAME
1269    ));
1270    println!("  running from  {}", exe.display());
1271    println!("  environment   {}", found.venv.display());
1272    println!("  project       {}", found.project.display());
1273    println!();
1274    output::print_info(
1275        "A tool install belongs outside a project: it outlives the environment, every \
1276         repository shares it, and it never has to appear in an application's \
1277         requirements file to stay out of the way.",
1278    );
1279
1280    if requirements.is_file() {
1281        println!();
1282        output::print_info(
1283            "Until that is fixed, a prune pass will decline this project's environment \
1284             — a package `requirements.txt` does not account for is a package nothing \
1285             can rebuild.",
1286        );
1287        println!();
1288        if record_in_requirements(&requirements) {
1289            return;
1290        }
1291    }
1292
1293    println!();
1294    println!("  Remove this copy and install it as a tool instead:");
1295    println!("    pip uninstall {}", constants::APP_NAME);
1296    println!("    uv tool install {}", constants::APP_NAME);
1297    println!("    # or: pipx install {}", constants::APP_NAME);
1298    report_other_copy(&exe);
1299    println!();
1300}
1301
1302/// Offer the other repair: declare the tool a dependency of this project, on purpose.
1303///
1304/// Default no, for the reason `devp restore` defaults no on a substituted interpreter —
1305/// this is the branch that writes into a file in somebody's repository, so a reflexive
1306/// Enter must not be what agrees to it. Returns whether the file was written, which is
1307/// also whether the removal instructions are still worth printing.
1308fn record_in_requirements(requirements: &std::path::Path) -> bool {
1309    use std::io::{IsTerminal, Write};
1310    if !std::io::stdin().is_terminal() {
1311        return false;
1312    }
1313    eprint!(
1314        "Record {} in requirements.txt instead, as a deliberate dev dependency? [y/N]: ",
1315        constants::APP_NAME
1316    );
1317    if std::io::stderr().flush().is_err() {
1318        return false;
1319    }
1320    let mut input = String::new();
1321    if std::io::stdin().read_line(&mut input).is_err() {
1322        return false;
1323    }
1324    if !matches!(input.trim().to_lowercase().as_str(), "y" | "yes") {
1325        return false;
1326    }
1327
1328    let Ok(existing) = fs::read_to_string(requirements) else {
1329        output::print_warning("Could not read requirements.txt, so nothing was changed.");
1330        return false;
1331    };
1332    // Requirements files without a trailing newline are common, and appending to one
1333    // blind would glue the pin onto the last requirement.
1334    let separator = if existing.is_empty() || existing.ends_with('\n') {
1335        ""
1336    } else {
1337        "\n"
1338    };
1339    let line = format!(
1340        "{separator}{}=={}\n",
1341        constants::APP_NAME,
1342        constants::VERSION
1343    );
1344    match std::fs::OpenOptions::new()
1345        .append(true)
1346        .open(requirements)
1347        .and_then(|mut f| f.write_all(line.as_bytes()))
1348    {
1349        Ok(()) => {
1350            output::print_success(&format!(
1351                "Added `{}=={}` to {}. The environment is prunable now.",
1352                constants::APP_NAME,
1353                constants::VERSION,
1354                requirements.display()
1355            ));
1356            true
1357        }
1358        Err(e) => {
1359            output::print_warning(&format!("Could not write requirements.txt ({e})."));
1360            false
1361        }
1362    }
1363}
1364
1365/// Name the copy that is already installed properly, if there is one.
1366///
1367/// "Uninstall this" reads very differently depending on whether it leaves the user with
1368/// no tool at all or with the one they already had — and on a machine where this mistake
1369/// happens there usually is one, because the working copy is what they were reaching for
1370/// in the first place.
1371fn report_other_copy(exe: &std::path::Path) {
1372    let names: [&str; 2] = if cfg!(windows) {
1373        ["dev-prune.exe", "devp.exe"]
1374    } else {
1375        ["dev-prune", "devp"]
1376    };
1377    let home = dirs::home_dir();
1378    let other = crate::channel::install_dirs(home.as_deref())
1379        .into_iter()
1380        .flat_map(|dir| names.iter().map(move |name| dir.join(name)))
1381        .find(|candidate| candidate.is_file() && candidate != exe);
1382
1383    if let Some(other) = other {
1384        println!();
1385        output::print_info(&format!(
1386            "You already have a copy outside this project, at `{}`, so removing this one \
1387             still leaves you a working `devp`.",
1388            other.display()
1389        ));
1390    }
1391}
1392
1393#[cfg(test)]
1394mod tests {
1395    use super::*;
1396
1397    #[test]
1398    fn a_report_with_only_present_items_is_silent() {
1399        let mut report = SetupReport::default();
1400        report.push("a", Outcome::AlreadyPresent);
1401        assert!(!report.changed_anything());
1402        assert!(!report.needs_attention());
1403    }
1404
1405    #[test]
1406    fn skipped_and_failed_both_ask_for_attention() {
1407        let mut skipped = SetupReport::default();
1408        skipped.push("a", Outcome::Skipped("no git".into()));
1409        assert!(skipped.needs_attention());
1410        assert!(!skipped.changed_anything());
1411
1412        let mut failed = SetupReport::default();
1413        failed.push("a", Outcome::Failed("boom".into()));
1414        assert!(failed.needs_attention());
1415    }
1416
1417    #[test]
1418    fn an_install_counts_as_a_change() {
1419        let mut report = SetupReport::default();
1420        report.push("a", Outcome::Installed);
1421        assert!(report.changed_anything());
1422    }
1423
1424    #[test]
1425    fn the_skill_export_lands_in_the_config_directory() {
1426        let dir = tempfile::TempDir::new().unwrap();
1427        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::Installed);
1428        // A second pass finds byte-identical content and leaves it alone.
1429        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::AlreadyPresent);
1430        let written = fs::read_to_string(dir.path().join("SKILL.md")).unwrap();
1431        assert_eq!(written, EMBEDDED_SKILL_MD);
1432    }
1433
1434    #[test]
1435    fn a_stale_skill_export_is_rewritten() {
1436        // An upgrade must not leave the previous version's instructions on disk.
1437        let dir = tempfile::TempDir::new().unwrap();
1438        fs::write(dir.path().join("SKILL.md"), "# an older version").unwrap();
1439        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::Installed);
1440        let written = fs::read_to_string(dir.path().join("SKILL.md")).unwrap();
1441        assert_eq!(written, EMBEDDED_SKILL_MD);
1442    }
1443
1444    #[test]
1445    fn agent_skills_install_only_into_agent_homes_that_exist() {
1446        let home = tempfile::TempDir::new().unwrap();
1447        assert!(
1448            agent_skill_roots_under(home.path()).is_empty(),
1449            "a machine without an agent must detect nothing"
1450        );
1451
1452        fs::create_dir_all(home.path().join(constants::CLAUDE_HOME_DIR)).unwrap();
1453        let roots = agent_skill_roots_under(home.path());
1454        assert_eq!(roots.len(), 1);
1455
1456        assert_eq!(ensure_agent_skills_at(&roots), Outcome::Installed);
1457        let installed = home
1458            .path()
1459            .join(constants::CLAUDE_HOME_DIR)
1460            .join(constants::AGENT_SKILLS_SUBDIR)
1461            .join(constants::APP_NAME)
1462            .join("SKILL.md");
1463        assert_eq!(fs::read_to_string(&installed).unwrap(), EMBEDDED_SKILL_MD);
1464
1465        // A second pass finds it current and leaves it alone.
1466        assert_eq!(ensure_agent_skills_at(&roots), Outcome::AlreadyPresent);
1467    }
1468
1469    #[test]
1470    fn no_detected_agent_is_a_skip_not_a_failure() {
1471        assert!(matches!(ensure_agent_skills_at(&[]), Outcome::Skipped(_)));
1472    }
1473
1474    #[test]
1475    fn the_stamp_gates_the_unattended_pass() {
1476        let dir = tempfile::TempDir::new().unwrap();
1477        assert!(setup_is_due_in(dir.path()), "a fresh install is due");
1478        write_stamp_in(dir.path());
1479        assert!(
1480            !setup_is_due_in(dir.path()),
1481            "the same version is not due twice"
1482        );
1483        fs::write(dir.path().join(STAMP_FILE), "0.0.1").unwrap();
1484        assert!(setup_is_due_in(dir.path()), "an upgrade is due again");
1485    }
1486
1487    /// The alias must never be written with a copy while it already exists.
1488    ///
1489    /// A hard link and its target share one inode, so `fs::copy` onto the alias empties
1490    /// the binary it was copied from. This reproduces the exact shape of that bug — link
1491    /// first, then ask for the alias again — and asserts the original still has its
1492    /// bytes. The real failure was silent: a zero-byte executable that macOS runs
1493    /// through `/bin/sh`, which exits 0 and prints nothing.
1494    #[test]
1495    fn refreshing_an_alias_that_is_a_hard_link_does_not_empty_the_binary() {
1496        let dir = tempfile::TempDir::new().unwrap();
1497        let binary = dir.path().join("dev-prune");
1498        let alias = dir.path().join("devp");
1499        fs::write(&binary, vec![b'M'; 4096]).unwrap();
1500
1501        if fs::hard_link(&binary, &alias).is_err() {
1502            return; // Filesystem without hard links; the hazard cannot arise.
1503        }
1504
1505        // What `ensure_alias` does when its `hard_link` loses the race: the alias is
1506        // already there, so it must stop rather than fall through to the copy.
1507        assert!(fs::hard_link(&binary, &alias).is_err(), "EEXIST expected");
1508        assert!(alias.exists(), "the guard's condition");
1509
1510        assert_eq!(
1511            fs::metadata(&binary).unwrap().len(),
1512            4096,
1513            "the running binary was truncated by refreshing its own alias"
1514        );
1515    }
1516
1517    /// The on-disk file name for one of the pair, on this platform.
1518    fn exe_name(stem: &str) -> String {
1519        if cfg!(windows) {
1520            format!("{stem}.exe")
1521        } else {
1522            stem.to_string()
1523        }
1524    }
1525
1526    #[test]
1527    fn dev_prune_creates_devp_beside_it() {
1528        let dir = tempfile::TempDir::new().unwrap();
1529        let canonical = dir.path().join(exe_name("dev-prune"));
1530        fs::write(&canonical, "the binary").unwrap();
1531
1532        assert_eq!(ensure_twin_of(&canonical, dir.path()), Outcome::Installed);
1533        let alias = dir.path().join(exe_name("devp"));
1534        assert!(alias.is_file(), "`devp` was not created");
1535        assert_eq!(fs::read_to_string(&alias).unwrap(), "the binary");
1536    }
1537
1538    /// The pair has to be recoverable from either side.
1539    ///
1540    /// Deleting `dev-prune` and leaving `devp` is not hypothetical: an antivirus
1541    /// quarantine, a half-finished uninstall, or a `Remove-Item` aimed at one name all
1542    /// produce it. Before this, `devp setup` reported the alias already present and did
1543    /// nothing, because the only direction it knew how to repair was the other one.
1544    #[test]
1545    fn devp_restores_a_missing_dev_prune() {
1546        let dir = tempfile::TempDir::new().unwrap();
1547        let alias = dir.path().join(exe_name("devp"));
1548        fs::write(&alias, "the binary").unwrap();
1549
1550        assert_eq!(ensure_twin_of(&alias, dir.path()), Outcome::Installed);
1551        let canonical = dir.path().join(exe_name("dev-prune"));
1552        assert!(canonical.is_file(), "`dev-prune` was not put back");
1553        assert_eq!(fs::read_to_string(&canonical).unwrap(), "the binary");
1554    }
1555
1556    /// `devp` may create `dev-prune`, never overwrite it.
1557    ///
1558    /// Repairing in both directions opens a downgrade: an upgrade replaces `dev-prune`
1559    /// first and can then fail on a `devp` that is running, which leaves the alias holding
1560    /// the *older* binary. If the alias were allowed to refresh its twin from there, the
1561    /// next `devp setup` would quietly reinstall the version the user just upgraded away
1562    /// from — and report it as a repair.
1563    #[test]
1564    fn devp_does_not_overwrite_an_existing_dev_prune() {
1565        let dir = tempfile::TempDir::new().unwrap();
1566        let alias = dir.path().join(exe_name("devp"));
1567        let canonical = dir.path().join(exe_name("dev-prune"));
1568        fs::write(&alias, "the previous version").unwrap();
1569        fs::write(&canonical, "the version just upgraded to").unwrap();
1570
1571        assert_eq!(
1572            ensure_twin_of(&alias, dir.path()),
1573            Outcome::AlreadyPresent,
1574            "`devp` must leave an existing `dev-prune` alone"
1575        );
1576        assert_eq!(
1577            fs::read_to_string(&canonical).unwrap(),
1578            "the version just upgraded to",
1579            "`devp` downgraded the binary it was supposed to leave alone"
1580        );
1581    }
1582
1583    #[test]
1584    fn versions_parse_strictly_or_not_at_all() {
1585        assert_eq!(parse_version("1.2.3"), Some((1, 2, 3)));
1586        assert_eq!(parse_version("10.0.0"), Some((10, 0, 0)));
1587        // Anything this project does not publish must answer None, because a None
1588        // means "replace the copy" and a mis-parse would order versions wrongly.
1589        assert_eq!(parse_version("1.2"), None);
1590        assert_eq!(parse_version("1.2.3.4"), None);
1591        assert_eq!(parse_version("1.2.3-rc1"), None);
1592        assert_eq!(parse_version("dev-prune"), None);
1593        // The version this binary was built with has to be parseable, or the refresh
1594        // logic can never decide anything.
1595        assert!(parse_version(constants::VERSION).is_some());
1596    }
1597
1598    #[test]
1599    fn the_version_this_cli_prints_is_one_this_cli_can_read_back() {
1600        // Not synthetic: this is the shape `print_version_info` writes, `v` and all,
1601        // down to the banner line that ends in the same token.
1602        let real = format!(
1603            "|_____|   v{v}
1604
1605dev-prune (devp) v{v}
1606  Compiler:        Rust 1.88+ (edition 2024)
1607",
1608            v = constants::VERSION
1609        );
1610        assert_eq!(
1611            version_in_output(&real),
1612            parse_version(constants::VERSION),
1613            "binary_version could not read this binary's own --version output"
1614        );
1615        // Something that is not this CLI still has to answer None, because doctor uses
1616        // that to mean "leave this file alone".
1617        assert_eq!(version_in_output("git version 2.51.0.windows.1"), None);
1618        assert_eq!(version_in_output("some other tool"), None);
1619    }
1620
1621    #[test]
1622    fn ordering_of_version_triples_matches_semver() {
1623        assert!(parse_version("1.1.0") > parse_version("1.0.9"));
1624        assert!(parse_version("2.0.0") > parse_version("1.99.99"));
1625        assert!(parse_version("1.0.10") > parse_version("1.0.9"));
1626    }
1627
1628    #[test]
1629    fn the_exported_skill_is_the_one_the_binary_was_built_with() {
1630        // `SKILL.md` is embedded, so a doc edit ships only if the binary is rebuilt.
1631        // Guard the two properties every consumer of it depends on.
1632        assert!(EMBEDDED_SKILL_MD.starts_with("---"), "needs frontmatter");
1633        assert!(
1634            !EMBEDDED_SKILL_MD.contains("file:///"),
1635            "SKILL.md is written to every user's machine — it must not contain \
1636             absolute paths from the author's checkout"
1637        );
1638    }
1639}