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_ok() {
234        return;
235    }
236    // Unconditionally, because `fs::copy` creates and truncates its destination before it
237    // writes a byte: a copy that fails partway — disk full, the volume going away, a
238    // permission revoked mid-write — leaves a half-written `dev-prune.new` behind. Nothing
239    // else ever removes it. `uninstall`'s sweep knows `*.exe.old`, the debris an update
240    // leaves, and has never known `*.new`, so the file would sit there until someone
241    // noticed it by hand.
242    let _ = fs::remove_file(&staging);
243}
244
245/// The `major.minor.patch` a binary reports for itself, if it can.
246pub(crate) fn binary_version(exe: &std::path::Path) -> Option<(u64, u64, u64)> {
247    let output = crate::spawn::command(exe).arg("--version").output().ok()?;
248    if !output.status.success() {
249        return None;
250    }
251    version_in_output(&String::from_utf8_lossy(&output.stdout))
252}
253
254/// The first `x.y.z` in a `--version` output, with or without the `v` this CLI prints.
255///
256/// Split out so it can be tested against real output. It has to accept `v1.7.0` because
257/// that is the only spelling `print_version_info` produces — the banner ends `v1.7.0`
258/// and the line under it reads `dev-prune (devp) v1.7.0`, and a bare `1.7.0` appears
259/// nowhere. Parsing the tokens without stripping that `v` answered `None` for every real
260/// dev-prune on the machine, and `doctor`'s "Other copies" check reads `None` as "not a
261/// dev-prune at all" — so it reported "none on PATH running a different version" however
262/// many stale copies were sitting there.
263fn version_in_output(text: &str) -> Option<(u64, u64, u64)> {
264    text.split_whitespace()
265        .find_map(|token| parse_version(token.strip_prefix('v').unwrap_or(token)))
266}
267
268/// Parse `x.y.z` into an orderable triple. Anything else — including the pre-release
269/// and build suffixes this project never publishes — answers `None`.
270pub(crate) fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
271    let mut parts = text.split('.');
272    let triple = (
273        parts.next()?.parse().ok()?,
274        parts.next()?.parse().ok()?,
275        parts.next()?.parse().ok()?,
276    );
277    parts.next().is_none().then_some(triple)
278}
279
280/// Keep `dev-prune` and `devp` beside each other, whichever of the two is running.
281///
282/// The pair is one binary under two names, and either one can be the survivor. An upgrade
283/// that could not replace a running `devp` leaves a stale alias; an antivirus quarantine,
284/// a half-finished uninstall or a `Remove-Item` aimed at the wrong name leaves only
285/// `devp`. So this restores *the other* name in whichever direction is missing, rather
286/// than only ever creating `devp` — running either one puts the pair back.
287pub fn ensure_alias() -> Outcome {
288    // WinGet, Scoop and Homebrew each install into a directory they version and replace
289    // whole on upgrade, and each ships both names in the package itself — so there is
290    // nothing to create here, and creating it would be actively wrong twice over. The
291    // twin would be orphaned by the next upgrade, still on PATH, still running the old
292    // release; and writing a second executable beside a freshly downloaded unsigned
293    // binary on its first run is a behavioural malware signature. WinGet's own
294    // post-install validation flags exactly that, which is how this was found.
295    if crate::channel::Channel::detect().replaces_its_directory() {
296        return Outcome::AlreadyPresent;
297    }
298    let Ok(current_exe) = std::env::current_exe() else {
299        return Outcome::Failed("could not locate the running executable".to_string());
300    };
301    let Some(parent_dir) = current_exe.parent() else {
302        return Outcome::Failed("the running executable has no parent directory".to_string());
303    };
304
305    ensure_twin_of(&current_exe, parent_dir)
306}
307
308/// Whether a twin whose content differs from the running binary is the older of the two,
309/// and so safe to replace.
310///
311/// Content inequality says the pair differ, never which one is the upgrade. `dev-prune` is
312/// *usually* the newer — installers write it first and upgrades replace it first — but
313/// "usually" is not "always", and the direction gate in [`ensure_twin_of`] trusted it
314/// absolutely. An older `dev-prune` restored from a backup, or run out of a
315/// package-manager cache, would delete a newer `devp` and hard-link its own older content
316/// over it: a silent downgrade of the name the documentation tells people to type, reached
317/// through `devp doctor --fix` of all things. So ask the twin its version, exactly as
318/// [`refresh_managed_copy_if_stale`] does, and leave it alone unless it is genuinely
319/// behind. A copy that cannot state a version at all is not a working build of this CLI,
320/// so it is still replaced.
321///
322/// Takes the two versions rather than the two paths so the rule can be tested without a
323/// pair of real binaries that report different versions.
324fn twin_is_stale(theirs: Option<(u64, u64, u64)>, ours: Option<(u64, u64, u64)>) -> bool {
325    !matches!((theirs, ours), (Some(theirs), Some(ours)) if theirs >= ours)
326}
327
328/// The half of [`ensure_alias`] that takes its paths as arguments, so tests can drive both
329/// directions without being the binary they are testing.
330fn ensure_twin_of(current_exe: &std::path::Path, parent_dir: &std::path::Path) -> Outcome {
331    let running_as_alias = current_exe
332        .file_stem()
333        .and_then(|s| s.to_str())
334        .is_some_and(|stem| stem == "devp");
335
336    // `dev-prune` is the canonical name, and only it may overwrite its twin.
337    //
338    // Installers write `dev-prune` first and upgrades replace it first, so a stale `devp`
339    // is worth replacing — otherwise it silently runs the previous version. The reverse is
340    // not safe as a rule: an upgrade that replaced `dev-prune` and then failed on a running
341    // `devp` leaves exactly the state where the alias is the *older* binary, and refreshing
342    // from there would quietly reinstall the version the user just upgraded away from. So
343    // `devp` may only create a `dev-prune` that is missing outright.
344    //
345    // Direction is necessary but not sufficient: see [`twin_is_stale`] for the case where
346    // `dev-prune` itself is the older of the pair.
347    let (twin_name, may_refresh) = if running_as_alias {
348        (
349            if cfg!(windows) {
350                "dev-prune.exe"
351            } else {
352                "dev-prune"
353            },
354            false,
355        )
356    } else {
357        (if cfg!(windows) { "devp.exe" } else { "devp" }, true)
358    };
359    let twin_exe = parent_dir.join(twin_name);
360
361    if twin_exe.exists() {
362        if !may_refresh || same_contents(&twin_exe, current_exe) {
363            return Outcome::AlreadyPresent;
364        }
365        if !twin_is_stale(binary_version(&twin_exe), parse_version(constants::VERSION)) {
366            return Outcome::AlreadyPresent;
367        }
368        // Replacing a running executable fails on Windows; that is fine, the alias is
369        // simply refreshed by the next invocation that is not itself `devp`.
370        if fs::remove_file(&twin_exe).is_err() {
371            return Outcome::Skipped(format!(
372                "`{twin_name}` is in use and could not be refreshed — re-run `devp setup` \
373                 from a terminal that is not running it"
374            ));
375        }
376    }
377
378    if fs::hard_link(current_exe, &twin_exe).is_ok() {
379        return Outcome::Installed;
380    }
381
382    // The copy is the fallback for filesystems without hard links — but it must never
383    // run when the alias already exists, because the reason `hard_link` usually fails is
384    // that another process created it a moment ago, as a hard link to this very
385    // executable. `fs::copy` opens its destination with O_TRUNC, and truncating a hard
386    // link truncates the shared inode: the copy would empty the running binary and then
387    // copy zero bytes from it.
388    //
389    // That is not hypothetical. It is what turned every macOS CI run red. The 28
390    // integration tests launch at once, one wins the link, the losers fall through to
391    // here, and `target/debug/dev-prune` becomes a zero-byte file. macOS `posix_spawn`
392    // answers ENOEXEC by handing the file to `/bin/sh`, so every later invocation
393    // "succeeded" with exit 0 and printed nothing — for two hours the tests looked like
394    // 27 unrelated assertion failures.
395    if twin_exe.exists() {
396        return Outcome::AlreadyPresent;
397    }
398
399    // Stage beside and rename into place: copied straight onto the final name, the
400    // alias would exist-but-be-incomplete for the length of the copy, and a `devp`
401    // typed in that window executes a torn binary.
402    let staging = twin_exe.with_extension("new");
403    if fs::copy(current_exe, &staging).is_ok() && fs::rename(&staging, &twin_exe).is_ok() {
404        return Outcome::Installed;
405    }
406    let _ = fs::remove_file(&staging);
407    if twin_exe.exists() {
408        // A concurrent invocation won the rename; its alias serves exactly as well.
409        return Outcome::AlreadyPresent;
410    }
411    Outcome::Failed(format!(
412        "could not create `{}`",
413        output::clean_path(&twin_exe)
414    ))
415}
416
417/// Sameness test for two executables, cheap in the common case.
418///
419/// A hard link makes size and mtime equal by construction, so the usual layout answers
420/// without reading either file. When only the mtime differs — the alias came from the
421/// copy fallback, which does not preserve timestamps — the bytes themselves decide,
422/// because calling that pair "different" made every single invocation delete and
423/// recreate an alias whose content never changed.
424pub(crate) fn same_contents(a: &std::path::Path, b: &std::path::Path) -> bool {
425    let (Ok(ma), Ok(mb)) = (fs::metadata(a), fs::metadata(b)) else {
426        return false;
427    };
428    if ma.len() != mb.len() {
429        return false;
430    }
431    if ma.modified().ok() == mb.modified().ok() {
432        return true;
433    }
434    match (fs::read(a), fs::read(b)) {
435        (Ok(ca), Ok(cb)) => ca == cb,
436        _ => false,
437    }
438}
439
440/// Path that `devp skill` and this module export `SKILL.md` to.
441pub fn skill_path() -> Result<PathBuf> {
442    Ok(Registry::config_dir()?.join("SKILL.md"))
443}
444
445/// Export the bundled `SKILL.md` so AI assistants have something to read.
446///
447/// Rewritten whenever it differs from the embedded copy, since an upgrade that changes
448/// the skill must not leave the previous version's instructions on disk.
449pub fn ensure_skill_file() -> Outcome {
450    match Registry::config_dir() {
451        Ok(dir) => ensure_skill_file_in(&dir),
452        Err(_) => Outcome::Failed("could not determine the config directory".to_string()),
453    }
454}
455
456fn ensure_skill_file_in(config_dir: &std::path::Path) -> Outcome {
457    let target = config_dir.join("SKILL.md");
458
459    if fs::read_to_string(&target).is_ok_and(|current| current == EMBEDDED_SKILL_MD) {
460        return Outcome::AlreadyPresent;
461    }
462
463    let _ = fs::create_dir_all(config_dir);
464    match fs::write(&target, EMBEDDED_SKILL_MD) {
465        Ok(()) => Outcome::Installed,
466        Err(e) => Outcome::Failed(format!(
467            "could not write {}: {e}",
468            output::clean_path(&target)
469        )),
470    }
471}
472
473/// The per-skill directories of AI coding agents that are installed under `home`.
474///
475/// Detection only — an agent's home directory is created by the agent, never by this
476/// pass. Today that is Claude Code, whose Agent Skills live at
477/// `~/.claude/skills/<name>/SKILL.md`. Assistants without an on-disk skill format get
478/// the onboarding prompt from `devp skill` instead.
479fn agent_skill_roots_under(home: &std::path::Path) -> Vec<PathBuf> {
480    let mut roots = Vec::new();
481    let claude = home.join(constants::CLAUDE_HOME_DIR);
482    if claude.is_dir() {
483        roots.push(
484            claude
485                .join(constants::AGENT_SKILLS_SUBDIR)
486                .join(constants::APP_NAME),
487        );
488    }
489    roots
490}
491
492/// The agent skill directories on this machine. Empty when no agent is installed.
493pub fn agent_skill_roots() -> Vec<PathBuf> {
494    dirs::home_dir()
495        .map(|home| agent_skill_roots_under(&home))
496        .unwrap_or_default()
497}
498
499/// Install the skill into every detected agent's skills directory.
500pub fn ensure_agent_skills() -> Outcome {
501    ensure_agent_skills_at(&agent_skill_roots())
502}
503
504/// Every managed copy of `SKILL.md` that is not the one this binary carries.
505///
506/// The copies are refreshed by [`ensure_integrations`], which runs only while
507/// auto-setup is on. With it off, an upgrade leaves the previous release's instructions
508/// sitting in the agent's skills directory, and the agent goes on describing flags that
509/// no longer exist — confidently, because nothing told it otherwise.
510pub fn stale_skill_copies() -> Vec<PathBuf> {
511    let mut copies: Vec<PathBuf> = skill_path().into_iter().collect();
512    copies.extend(agent_skill_roots().into_iter().map(|r| r.join("SKILL.md")));
513    stale_among(copies)
514}
515
516/// The ones of `copies` that exist and differ from the embedded skill.
517///
518/// A path that is not there is not stale — it is a copy this machine never had, and
519/// nothing that refreshes may create it.
520fn stale_among(copies: Vec<PathBuf>) -> Vec<PathBuf> {
521    copies
522        .into_iter()
523        .filter(|p| fs::read_to_string(p).is_ok_and(|current| current != EMBEDDED_SKILL_MD))
524        .collect()
525}
526
527/// Rewrite copies that are already on disk, and only those.
528///
529/// This is the half of [`ensure_skill_copies`] that is safe to run on a machine which
530/// turned auto-setup off: replacing the contents of a file that machine already
531/// consented to is maintenance, not a new integration.
532fn refresh_stale(stale: Vec<PathBuf>) {
533    for path in stale {
534        let _ = fs::write(path, EMBEDDED_SKILL_MD);
535    }
536}
537
538/// Rewrite every managed copy of `SKILL.md` from the embedded one.
539///
540/// Both copies, not just the export: the one an assistant actually reads is the one in
541/// its own skills directory, so repairing the export alone would report success and
542/// leave the stale instructions in the only place that matters.
543pub fn ensure_skill_copies() -> Outcome {
544    let mut installed = false;
545    for outcome in [ensure_skill_file(), ensure_agent_skills()] {
546        match outcome {
547            Outcome::Installed => installed = true,
548            // No agent on this machine is not a failure to repair.
549            Outcome::AlreadyPresent | Outcome::Skipped(_) => {}
550            failed => return failed,
551        }
552    }
553    if installed {
554        Outcome::Installed
555    } else {
556        Outcome::AlreadyPresent
557    }
558}
559
560fn ensure_agent_skills_at(roots: &[PathBuf]) -> Outcome {
561    if roots.is_empty() {
562        return Outcome::Skipped(
563            "no AI agent skills directory was found — `devp skill` prints import prompts instead"
564                .to_string(),
565        );
566    }
567    let mut installed = false;
568    for root in roots {
569        match ensure_skill_file_in(root) {
570            Outcome::Installed => installed = true,
571            Outcome::AlreadyPresent => {}
572            other => return other,
573        }
574    }
575    if installed {
576        Outcome::Installed
577    } else {
578        Outcome::AlreadyPresent
579    }
580}
581
582/// Make the managed pair reachable from a fresh shell.
583///
584/// This is the step that lets `pip install dev-prune` in a virtualenv survive the
585/// virtualenv: the binaries pip placed vanish with the environment, but the managed
586/// copy under `<config>/bin` does not, and after this step it is the one a new
587/// terminal finds. See [`crate::pathenv`] for what "reachable" means per platform.
588pub fn ensure_command_on_path() -> Outcome {
589    let managed = stable_exe_path();
590    let is_managed_copy =
591        managed_exe_path().is_ok_and(|expected| expected == managed) && managed.is_file();
592    if !is_managed_copy {
593        // No managed copy exists and none could be created — under `cargo test` the
594        // running executable is the harness, and cloning that would be wrong. There is
595        // nothing durable to put on PATH.
596        return Outcome::Skipped("no managed copy of the binary exists to put on PATH".to_string());
597    }
598    let Some(bin_dir) = managed.parent() else {
599        return Outcome::Failed("the managed binary has no parent directory".to_string());
600    };
601    // `devp` has to sit beside it, or the PATH entry only ever finds `dev-prune`.
602    if let Outcome::Failed(why) = ensure_twin_of(&managed, bin_dir) {
603        return Outcome::Failed(why);
604    }
605    crate::pathenv::ensure_reachable(bin_dir)
606}
607
608/// Write the icon assets and register `*.devprune.json` with the OS file manager.
609///
610/// Part of the automatic pass rather than a separate errand, because "the config file has
611/// an icon" is not a thing anybody thinks to go and ask for. Everything it writes lives
612/// under the config directory and the user's own XDG data directory, `devp uninstall`
613/// removes all of it, and it touches no editor settings, no PATH and no shell profile —
614/// so there is nothing here that needs to be asked about first.
615///
616/// Unlike the hooks and the scheduler, this has no opt-out switch of its own. Files
617/// dropped into the user's data directory are not a background process and not a change
618/// in behaviour; `auto_setup` already covers "install nothing at all".
619fn ensure_icons() -> Outcome {
620    if crate::commands::icon::is_registered() {
621        return Outcome::AlreadyPresent;
622    }
623    match crate::commands::icon::sync_app_directory() {
624        Ok(()) => Outcome::Installed,
625        Err(e) => Outcome::Failed(format!("{e:#}")),
626    }
627}
628
629/// Install the global Git hooks, unless git is absent or the slot belongs to someone else.
630///
631/// `chain` is `auto_hooks_chain`: with it on, a slot that belongs to husky is not a
632/// reason to skip, because dev-prune can install in front and forward every hook back.
633pub fn ensure_hooks(chain: bool) -> Outcome {
634    if !hook::git_available() {
635        return Outcome::Skipped(format!(
636            "\n    {}",
637            hook::GIT_MISSING_HELP.replace('\n', "\n    ")
638        ));
639    }
640
641    match hook::state() {
642        // "Installed" is not the question — "installed and pointing at a binary that
643        // still exists" is. A hook backgrounds itself and discards its own output, so
644        // one left pointing at a deleted npm cache dies silently on every commit and
645        // nothing ever registers again; this pass is the only thing that ever looks.
646        // Two reasons to rewrite a working install: it names a binary that is gone, or
647        // it predates the passthrough shims and is silently shadowing every repository's
648        // own `.git/hooks`. Neither reports itself — a hook discards its own output by
649        // design — so the upgrade pass is the only thing that will ever notice.
650        Ok(HookState::Active) if hook_target_is_dead() || hook::shims_incomplete() => {
651            match hook::install() {
652                Ok(()) => Outcome::Installed,
653                Err(e) => Outcome::Failed(format!("{e:#}")),
654            }
655        }
656        Ok(HookState::Active) => Outcome::AlreadyPresent,
657        // Drift is repaired here rather than reported: the setup pass already runs on
658        // install, on update and on a schedule, and a chain the user opted into is a
659        // chain they want kept current.
660        Ok(HookState::Chained { drifted, .. }) if !drifted.is_empty() => {
661            match hook::install_with(true) {
662                Ok(()) => Outcome::Installed,
663                Err(e) => Outcome::Failed(format!("{e:#}")),
664            }
665        }
666        Ok(HookState::Chained { .. }) if hook_target_is_dead() => match hook::install_with(true) {
667            Ok(()) => Outcome::Installed,
668            Err(e) => Outcome::Failed(format!("{e:#}")),
669        },
670        Ok(HookState::Chained { .. }) => Outcome::AlreadyPresent,
671        Ok(HookState::Foreign(_)) if chain => match hook::install_with(true) {
672            Ok(()) => Outcome::Installed,
673            Err(e) => Outcome::Failed(format!("{e:#}")),
674        },
675        Ok(HookState::Foreign(existing)) => Outcome::Skipped(format!(
676            "`core.hooksPath` is already set to `{existing}`, which belongs to another tool.\n    \
677             Git allows only one hooks directory, so dev-prune will not take the slot.\n    \
678             `devp hook install --chain` installs in front of it instead — dev-prune registers \
679             the repo, then hands every hook on to `{existing}`, and `devp hook uninstall` puts \
680             the original setting back (`devp config set auto_hooks_chain true` makes that \
681             the standing answer). Or skip it: `devp link .` does the same job by hand."
682        )),
683        Ok(HookState::Absent) => match hook::install() {
684            Ok(()) => Outcome::Installed,
685            Err(e) => Outcome::Failed(format!("{e:#}")),
686        },
687        Err(e) => Outcome::Failed(format!("{e:#}")),
688    }
689}
690
691/// Whether the installed hooks name a binary that no longer exists.
692fn hook_target_is_dead() -> bool {
693    hook::registered_exe_path().is_some_and(|exe| !exe.exists())
694}
695
696/// Install the OS scheduler if it is not already registered.
697pub fn ensure_daemon(interval_days: u64) -> Outcome {
698    match daemon::daemon_status() {
699        // A task whose binary has been deleted keeps reporting itself `Ready` and dies
700        // the instant it fires, every interval, with nowhere to complain. Re-register
701        // it against the stable path instead of counting the corpse as present.
702        Ok(daemon::DaemonStatus::Installed)
703            if daemon::registered_exe_path().is_some_and(|exe| !exe.exists()) =>
704        {
705            match daemon::install_daemon(interval_days) {
706                Ok(()) => Outcome::Installed,
707                Err(e) => Outcome::Failed(format!("{e:#}")),
708            }
709        }
710        // A task registered by a version that only knew the interactive logon flashes a
711        // console window at whoever is logged in every time it fires — the single most
712        // trust-destroying thing a background tool can do. Re-register it windowless;
713        // a machine whose scheduler refuses the sessionless logon remembers the refusal
714        // and is not asked again.
715        Ok(daemon::DaemonStatus::Installed) if daemon::wants_windowless_upgrade() => {
716            match daemon::install_daemon(interval_days) {
717                Ok(()) => Outcome::Installed,
718                Err(e) => Outcome::Failed(format!("{e:#}")),
719            }
720        }
721        // A task registered by a version that took Windows' power defaults never runs
722        // on a laptop that lives on battery, and a missed trigger is skipped rather
723        // than caught up. Patch the settings in place — an XML round-trip, not a
724        // reinstall, so the trigger time the user already has stays put. A scheduler
725        // that refuses remembers the refusal and is not asked again.
726        Ok(daemon::DaemonStatus::Installed) if daemon::wants_power_upgrade() => {
727            match daemon::apply_power_settings() {
728                Ok(()) => Outcome::Installed,
729                Err(e) => Outcome::Failed(format!("{e:#}")),
730            }
731        }
732        // A settled task still needs its windowless twin kept current: the twin
733        // is a copy of the binary, so an upgrade that replaced the binary would otherwise
734        // leave the daemon firing the previous release. No-op on the other platforms, and
735        // when no twin is in use.
736        Ok(daemon::DaemonStatus::Installed) => {
737            daemon::refresh_windowless_twin();
738            Outcome::AlreadyPresent
739        }
740        Ok(daemon::DaemonStatus::NotInstalled) => match daemon::install_daemon(interval_days) {
741            Ok(()) => Outcome::Installed,
742            Err(e) => Outcome::Failed(format!("{e:#}")),
743        },
744        // `Unknown` means the query itself could not be answered — the scheduler may
745        // well be there. Installing over it would fail on every command from now on, so
746        // this reports and steps over instead of guessing. The platform backends are
747        // written to keep this case narrow: anything they can answer definitely, they do.
748        Ok(daemon::DaemonStatus::Unknown(why)) => {
749            Outcome::Skipped(format!("scheduler state could not be read — {why}"))
750        }
751        Err(e) => Outcome::Failed(format!("{e:#}")),
752    }
753}
754
755/// Whether unattended installation is permitted at all.
756///
757/// Both switches exist because these integrations write outside dev-prune's own config
758/// directory — a scheduled task, a global git setting — and there are places that must
759/// never happen unasked: container images, CI, and this project's own test suite.
760pub fn auto_setup_enabled(registry: &Registry) -> bool {
761    !no_auto_setup_requested() && registry.settings.auto_setup && unattended_environment().is_none()
762}
763
764/// The reason this looks like a machine nobody is sitting at, if it does.
765///
766/// `DEV_PRUNE_NO_AUTO_SETUP` and `auto_setup` are both switches you have to set *before*
767/// the first run — which is exactly the run that installs things, so in a container or a
768/// CI job the damage is done by the time there is anywhere to set them. Detecting the
769/// environment is the only opt-out that works on the first run, which is the only run
770/// that matters here.
771///
772/// Deliberately conservative: every signal below is one that CI providers and container
773/// runtimes set themselves, so a developer's own shell will not trip it. Someone who
774/// genuinely wants the integrations in CI can still ask in so many words with
775/// `devp setup`, which never consults this.
776pub fn unattended_environment() -> Option<&'static str> {
777    // Set by GitHub Actions, GitLab CI, CircleCI, Travis, Jenkins (via pipeline), Woodpecker
778    // and most others. `CI=true` is the closest thing this space has to a standard.
779    for var in [
780        "CI",
781        "CONTINUOUS_INTEGRATION",
782        "BUILD_NUMBER",
783        "GITHUB_ACTIONS",
784    ] {
785        if let Some(value) = std::env::var_os(var) {
786            // `CI=false` is set explicitly by some tools to mean "not CI", and honouring
787            // the word rather than the presence is what the user plainly meant.
788            let value = value.to_string_lossy();
789            if !value.is_empty() && !value.eq_ignore_ascii_case("false") {
790                return Some("this looks like a CI runner");
791            }
792        }
793    }
794
795    // Docker writes this marker into every container it builds from a Dockerfile;
796    // Podman and other OCI runtimes write the `container` variable instead.
797    #[cfg(unix)]
798    if std::path::Path::new("/.dockerenv").exists() {
799        return Some("this looks like a container");
800    }
801    if std::env::var_os("container").is_some() {
802        return Some("this looks like a container");
803    }
804
805    None
806}
807
808/// Whether this integration pass was asked for by name.
809///
810/// The only thing it decides is the `devp` twin. Writing a second executable beside the
811/// first is a self-installation, and doing it *unasked*, on the first run of a freshly
812/// downloaded unsigned binary, alongside registering a scheduled task, is a behavioural
813/// malware signature — it is what earned this package a `Validation-Defender-Error` on
814/// microsoft/winget-pkgs#422665. Asked for in so many words, the same write is an
815/// ordinary install step. Nothing else in the pass changes.
816#[derive(Clone, Copy, PartialEq, Eq)]
817pub enum Consent {
818    /// `devp setup`, or `devp doctor --fix`.
819    Explicit,
820    /// The pass that runs on its own when `auto_setup` is on.
821    Unattended,
822}
823
824/// Run an integration pass unless unattended installation is switched off.
825///
826/// Every caller that the user did not name explicitly goes through this. `devp setup`
827/// calls [`ensure_integrations`] with [`Consent::Explicit`]: asking for it in so many
828/// words is consent.
829pub fn ensure_integrations_if_enabled(registry: &Registry) -> Option<SetupReport> {
830    auto_setup_enabled(registry).then(|| ensure_integrations(registry, Consent::Unattended))
831}
832
833/// Run one integration pass, installing whatever is missing.
834///
835/// The two per-integration settings (`auto_daemon`, `auto_hooks`) are honoured here, so
836/// turning one off turns it off for every future pass as well as this one.
837pub fn ensure_integrations(registry: &Registry, consent: Consent) -> SetupReport {
838    let mut report = SetupReport::default();
839
840    // Only when asked. This is the twin *beside the running binary*, which on an
841    // unattended pass means beside whatever the delivery vehicle happened to be: npm's
842    // cache, a venv's `Scripts`, a Downloads folder. Every channel already ships both
843    // names as real files — the archives, the npm and PyPI packages, and two `[[bin]]`
844    // targets for `cargo install` — so there is normally nothing to create, and the one
845    // case left over is a manual install that skipped `dev-prune setup`, which `devp
846    // doctor` reports with a one-command fix.
847    //
848    // The pair that actually matters is not this one. `ensure_command_on_path` below
849    // keeps `dev-prune` and `devp` together in the managed `bin` directory, which is
850    // the directory on the user's PATH and the one `devp uninstall` knows about, and it
851    // runs on every pass.
852    if consent == Consent::Explicit {
853        report.push("dev-prune/devp pair", ensure_alias());
854    }
855    report.push("Command on PATH", ensure_command_on_path());
856    report.push("SKILL.md", ensure_skill_file());
857    // Only reported when an agent is actually installed: a machine without one would
858    // otherwise see a "skipped" warning about software it never had, on every install.
859    if !agent_skill_roots().is_empty() {
860        report.push("AI agent skills", ensure_agent_skills());
861    }
862    report.push("File icons", ensure_icons());
863
864    if registry.settings.auto_hooks {
865        report.push(
866            "Git hooks",
867            ensure_hooks(registry.settings.auto_hooks_chain),
868        );
869    } else {
870        report.push(
871            "Git hooks",
872            Outcome::Skipped("`auto_hooks` is false — enable with `devp hook install`".to_string()),
873        );
874    }
875
876    if registry.settings.auto_daemon {
877        report.push(
878            "Background scheduler",
879            ensure_daemon(registry.settings.check_interval_days),
880        );
881    } else {
882        report.push(
883            "Background scheduler",
884            Outcome::Skipped(
885                "`auto_daemon` is false — enable with `devp daemon install`".to_string(),
886            ),
887        );
888    }
889
890    report
891}
892
893// ── VS Code extension ────────────────────────────────────────────────────────
894
895/// Marker recording that the extension question was asked (or found already answered by
896/// an existing install). One file, no content: the offer is made once ever, whatever
897/// the answer was — a declined install must not be re-litigated on every upgrade.
898const VSCODE_OFFER_STAMP: &str = "vscode-ext-offered";
899
900/// A VS Code-compatible editor found on PATH.
901struct EditorCli {
902    /// The command to invoke — on Windows the `.cmd` launcher, because the entry on
903    /// PATH is a batch file, not an `.exe`, and `Command::new("code")` would miss it.
904    cli: String,
905    /// The editor's name as a person knows it, for the prompt and per-editor results.
906    label: &'static str,
907}
908
909/// Every VS Code-compatible editor on PATH, in the order listed here.
910///
911/// All of these forks keep the upstream CLI protocol (`--version`, `--list-extensions`,
912/// `--install-extension`), so one code path drives them all. What differs is the
913/// registry each one resolves an extension ID against: VS Code uses the Microsoft
914/// Marketplace, VSCodium/Windsurf/Positron/Kiro/Trae use OpenVSX, Cursor and
915/// Antigravity run their own mirrors. An ID install can therefore fail on a fork whose
916/// registry does not carry the extension yet — which is why the installer falls back
917/// to the `.vsix` from the GitHub release, the artifact every registry copy is built
918/// from.
919///
920/// The list is candidate CLI names, not a claim that any of them is installed: each is
921/// asked for its `--version` and dropped if it does not answer. Adding a fork therefore
922/// costs one failed spawn on a machine without it, and is what stops the extension
923/// offer from being a VS Code-only courtesy on an editor that is a VS Code build with a
924/// different name on the window.
925fn detect_vscode_editors() -> Vec<EditorCli> {
926    const CANDIDATES: &[(&str, &str)] = &[
927        ("code", "VS Code"),
928        ("code-insiders", "VS Code Insiders"),
929        ("codium", "VSCodium"),
930        ("codium-insiders", "VSCodium Insiders"),
931        ("cursor", "Cursor"),
932        ("windsurf", "Windsurf"),
933        ("antigravity", "Antigravity"),
934        ("trae", "Trae"),
935        ("positron", "Positron"),
936        ("kiro", "Kiro"),
937    ];
938    CANDIDATES
939        .iter()
940        .filter_map(|(name, label)| {
941            let cli = if cfg!(windows) {
942                format!("{name}.cmd")
943            } else {
944                (*name).to_string()
945            };
946            let responds = crate::spawn::command(&cli)
947                .arg("--version")
948                .stdin(std::process::Stdio::null())
949                .stdout(std::process::Stdio::null())
950                .stderr(std::process::Stdio::null())
951                .status()
952                .map(|s| s.success())
953                .unwrap_or(false);
954            responds.then_some(EditorCli { cli, label })
955        })
956        .collect()
957}
958
959fn vscode_extension_installed(cli: &str) -> bool {
960    crate::spawn::command(cli)
961        .arg("--list-extensions")
962        .stdin(std::process::Stdio::null())
963        .output()
964        .map(|out| {
965            String::from_utf8_lossy(&out.stdout).lines().any(|line| {
966                line.trim()
967                    .eq_ignore_ascii_case(constants::VSCODE_EXTENSION_ID)
968            })
969        })
970        .unwrap_or(false)
971}
972
973/// Download the `.vsix` from the newest extension release into the config directory.
974///
975/// The release asset is the source of truth for the extension — the Marketplace and
976/// OpenVSX listings are published from that exact file — so when an editor's registry
977/// cannot resolve the ID (a fork whose registry does not carry the extension),
978/// installing the release file directly gets the same bits through a channel every fork
979/// supports. Editors update a `.vsix`-installed extension from their registry once a
980/// newer listed version appears, so this install self-heals into the normal update flow.
981///
982/// Deliberately not `releases/latest`. The extension has its own tags and its own
983/// release page, and those releases are marked "not latest" so they cannot displace the
984/// binary release that `devp update` reads. The consequence is that the newest one has
985/// to be found by walking the listing for a [`VSCODE_RELEASE_TAG_PREFIX`] tag.
986///
987/// [`VSCODE_RELEASE_TAG_PREFIX`]: crate::constants::VSCODE_RELEASE_TAG_PREFIX
988fn download_release_vsix() -> Option<std::path::PathBuf> {
989    use std::time::Duration;
990
991    if offline_requested() {
992        return None;
993    }
994
995    let fetch = |url: &str| {
996        ureq::get(url)
997            .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
998            .header("Accept", "application/vnd.github+json")
999            .config()
1000            .timeout_global(Some(Duration::from_secs(30)))
1001            .build()
1002            .call()
1003    };
1004
1005    let body = fetch(constants::RELEASES_LIST_API_URL)
1006        .ok()?
1007        .body_mut()
1008        .read_to_string()
1009        .ok()?;
1010    let json: serde_json::Value = serde_json::from_str(&body).ok()?;
1011    // GitHub returns this listing newest-first, so the first extension release found is
1012    // the current one. Draft releases carry no downloadable asset, and a pre-release of
1013    // the extension is one deliberately not being offered to people who did not ask.
1014    let asset = json.as_array()?.iter().find_map(|release| {
1015        let tag = release.get("tag_name")?.as_str()?;
1016        if !tag.starts_with(constants::VSCODE_RELEASE_TAG_PREFIX) {
1017            return None;
1018        }
1019        if release.get("draft")?.as_bool()? || release.get("prerelease")?.as_bool()? {
1020            return None;
1021        }
1022        release.get("assets")?.as_array()?.iter().find_map(|asset| {
1023            let name = asset.get("name")?.as_str()?;
1024            if !name.ends_with(".vsix") {
1025                return None;
1026            }
1027            let url = asset.get("browser_download_url")?.as_str()?;
1028            Some((name.to_string(), url.to_string()))
1029        })
1030    })?;
1031
1032    let bytes = fetch(&asset.1).ok()?.body_mut().read_to_vec().ok()?;
1033    // The config directory, not the shared system temp dir: on a multi-user machine
1034    // `%TEMP%`-style paths are predictable and writable by others, and the editor is
1035    // about to execute what this file contains. The caller deletes it after installing.
1036    let dir = Registry::config_dir().ok()?;
1037    fs::create_dir_all(&dir).ok()?;
1038    let path = dir.join(&asset.0);
1039    fs::write(&path, bytes).ok()?;
1040    Some(path)
1041}
1042
1043/// `<cli> --install-extension <arg>`, surfacing the editor's own output.
1044fn run_install(cli: &str, arg: &str) -> bool {
1045    crate::spawn::command(cli)
1046        .args(["--install-extension", arg])
1047        .stdin(std::process::Stdio::null())
1048        .status()
1049        .map(|s| s.success())
1050        .unwrap_or(false)
1051}
1052
1053/// Offer to install the editor extension, once ever, when a VS Code-family editor is
1054/// present.
1055///
1056/// This asks rather than installs because the editor is not dev-prune's territory the
1057/// way its own config directory is. Every gate below is a way of making sure a person
1058/// is actually there to answer: no marker yet, not a CI runner or container, both ends
1059/// of the terminal attached. When no editor is found nothing is written, so installing
1060/// one later and re-running `devp setup` still gets the one offer.
1061pub fn offer_vscode_extension() {
1062    use std::io::{IsTerminal, Write};
1063
1064    let Ok(config_dir) = Registry::config_dir() else {
1065        return;
1066    };
1067    if config_dir.join(VSCODE_OFFER_STAMP).exists() {
1068        return;
1069    }
1070    if no_auto_setup_requested()
1071        || unattended_environment().is_some()
1072        || !std::io::stdin().is_terminal()
1073        || !std::io::stdout().is_terminal()
1074    {
1075        return;
1076    }
1077    let editors = detect_vscode_editors();
1078    if editors.is_empty() {
1079        return;
1080    }
1081
1082    let write_marker = || {
1083        let _ = fs::create_dir_all(&config_dir);
1084        let _ = fs::write(config_dir.join(VSCODE_OFFER_STAMP), "");
1085    };
1086
1087    let missing: Vec<&EditorCli> = editors
1088        .iter()
1089        .filter(|e| !vscode_extension_installed(&e.cli))
1090        .collect();
1091    if missing.is_empty() {
1092        write_marker();
1093        return;
1094    }
1095
1096    let names = missing
1097        .iter()
1098        .map(|e| e.label)
1099        .collect::<Vec<_>>()
1100        .join(", ");
1101    println!();
1102    println!("{names} detected — install the dev-prune extension?");
1103    println!("  It validates .devprune.json and shows reclaimable space in the status bar.");
1104    // The listings and the source, before the question rather than after it. This is
1105    // the one prompt that defaults to yes, so the material someone would need in order
1106    // to say no has to be on screen at the moment they answer — not in a doc they would
1107    // have to go and look for.
1108    println!("    Marketplace: {}", constants::VSCODE_MARKETPLACE_URL);
1109    println!("    Open VSX:    {}", constants::OPENVSX_URL);
1110    println!("    Source:      {}", constants::REPO_URL);
1111    print!("  Install it? [Y/n] ");
1112    let _ = std::io::stdout().flush();
1113    let mut answer = String::new();
1114    if std::io::stdin().read_line(&mut answer).is_err() {
1115        return;
1116    }
1117    write_marker();
1118
1119    // A bare Enter accepts. Unlike the uninstall sweep — which deletes — the worst case
1120    // here is an extension the person removes in two clicks, and the gates above have
1121    // already established that a human with a VS Code-family editor is watching.
1122    if !matches!(answer.trim().to_lowercase().as_str(), "" | "y" | "yes") {
1123        output::print_info(&format!(
1124            "Skipped. Install it any time with `{} --install-extension {}`, or from {}.",
1125            missing[0].cli,
1126            constants::VSCODE_EXTENSION_ID,
1127            constants::VSCODE_MARKETPLACE_URL
1128        ));
1129        return;
1130    }
1131
1132    // Fetched at most once, shared by every editor whose registry install fails.
1133    let mut release_vsix: Option<Option<std::path::PathBuf>> = None;
1134    for editor in &missing {
1135        // The editor's own registry first: that install is the one the editor keeps
1136        // up to date by itself.
1137        if run_install(&editor.cli, constants::VSCODE_EXTENSION_ID) {
1138            output::print_success(&format!("{}: extension installed.", editor.label));
1139            continue;
1140        }
1141        // A fork whose registry does not carry the extension — install the `.vsix`
1142        // from the GitHub release instead.
1143        let vsix = release_vsix.get_or_insert_with(download_release_vsix);
1144        match vsix {
1145            Some(path) if run_install(&editor.cli, &path.to_string_lossy()) => {
1146                output::print_success(&format!(
1147                    "{}: extension installed from the GitHub release .vsix.",
1148                    editor.label
1149                ));
1150            }
1151            _ => {
1152                output::print_warning(&format!(
1153                    "{}: could not install it from here. Search the Extensions view for \"dev-prune\", or run `{} --install-extension {}` yourself.",
1154                    editor.label,
1155                    editor.cli,
1156                    constants::VSCODE_EXTENSION_ID
1157                ));
1158            }
1159        }
1160    }
1161    if let Some(Some(path)) = &release_vsix {
1162        let _ = fs::remove_file(path);
1163    }
1164}
1165
1166/// Record that a pass completed for this version.
1167fn write_stamp_in(config_dir: &std::path::Path) {
1168    let _ = fs::create_dir_all(config_dir);
1169    let _ = fs::write(config_dir.join(STAMP_FILE), constants::VERSION);
1170}
1171
1172fn write_stamp() {
1173    if let Ok(dir) = Registry::config_dir() {
1174        write_stamp_in(&dir);
1175    }
1176}
1177
1178fn setup_is_due_in(config_dir: &std::path::Path) -> bool {
1179    !fs::read_to_string(config_dir.join(STAMP_FILE))
1180        .is_ok_and(|stamp| stamp.trim() == constants::VERSION)
1181}
1182
1183/// What this machine has said about dev-prune installing things for itself.
1184///
1185/// Three answers, not two: "never asked" is the state a question can still be put in,
1186/// and collapsing it into either answer is how tools end up installing on a silence or
1187/// nagging on a refusal.
1188#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1189pub enum SetupConsent {
1190    Granted,
1191    Declined,
1192    NeverAsked,
1193}
1194
1195const CONSENT_GRANTED: &str = "granted";
1196const CONSENT_DECLINED: &str = "declined";
1197
1198/// The release that introduced the consent question. A stamp older than this could
1199/// only have been written by a pass that had already installed the integrations; a
1200/// newer one is also written by the opted-out path, and so proves nothing.
1201const FIRST_CONSENT_VERSION: &str = "1.18.0";
1202
1203fn consent_state_in(config_dir: &std::path::Path) -> SetupConsent {
1204    match fs::read_to_string(config_dir.join(constants::SETUP_CONSENT_FILE)) {
1205        Ok(answer) if answer.trim() == CONSENT_GRANTED => return SetupConsent::Granted,
1206        Ok(answer) if answer.trim() == CONSENT_DECLINED => return SetupConsent::Declined,
1207        _ => {}
1208    }
1209    // A pre-1.18 stamp means the old flow already installed the integrations and the
1210    // person kept them — consent in deed if not in word, and re-asking would prompt
1211    // every existing user once for something they already have.
1212    match fs::read_to_string(config_dir.join(STAMP_FILE)) {
1213        Ok(stamp)
1214            if crate::commands::update::compare_versions(stamp.trim(), FIRST_CONSENT_VERSION)
1215                == Some(std::cmp::Ordering::Less) =>
1216        {
1217            SetupConsent::Granted
1218        }
1219        _ => SetupConsent::NeverAsked,
1220    }
1221}
1222
1223pub fn consent_state() -> SetupConsent {
1224    Registry::config_dir()
1225        .map(|dir| consent_state_in(&dir))
1226        .unwrap_or(SetupConsent::NeverAsked)
1227}
1228
1229fn record_consent_in(config_dir: &std::path::Path, answer: &str) {
1230    let _ = fs::create_dir_all(config_dir);
1231    let _ = fs::write(config_dir.join(constants::SETUP_CONSENT_FILE), answer);
1232}
1233
1234/// `devp setup` records this too: asking for the pass in so many words is also the
1235/// durable answer to the question the first run would otherwise ask.
1236pub fn record_consent_granted() {
1237    if let Ok(dir) = Registry::config_dir() {
1238        record_consent_in(&dir, CONSENT_GRANTED);
1239    }
1240}
1241
1242fn record_consent_declined() {
1243    if let Ok(dir) = Registry::config_dir() {
1244        record_consent_in(&dir, CONSENT_DECLINED);
1245    }
1246}
1247
1248/// Put the question back the way a fresh machine has it. `devp uninstall` calls this:
1249/// keeping a "granted" that outlives the things it granted would make the next upgrade
1250/// reinstall everything the uninstall just removed.
1251pub fn clear_setup_consent() {
1252    if let Ok(dir) = Registry::config_dir() {
1253        let _ = fs::remove_file(dir.join(constants::SETUP_CONSENT_FILE));
1254    }
1255}
1256
1257/// Whether the unattended pass is due: a fresh install, or the first run after an upgrade.
1258pub fn setup_is_due() -> bool {
1259    Registry::config_dir()
1260        .map(|dir| setup_is_due_in(&dir))
1261        .unwrap_or(false)
1262}
1263
1264/// Whether there is a human at this invocation who could see what was done and undo it.
1265///
1266/// The one question that gates everything dev-prune installs without being asked. CI
1267/// variables and containers answer it directly; a redirected stdin or stdout answers it
1268/// too, because output nobody reads is the same as no output — and an integration
1269/// installed silently is one nobody knows to remove.
1270fn a_person_is_present() -> bool {
1271    use std::io::IsTerminal;
1272    unattended_environment().is_none()
1273        && std::io::stdin().is_terminal()
1274        && std::io::stdout().is_terminal()
1275}
1276
1277/// The per-version pass — and, since 1.18.0, never before this machine has said yes.
1278///
1279/// Called at the top of every command that a human typed. It is deliberately not called
1280/// for the Git hook's `link --quiet` or the scheduler's `run --daemon`: those run without
1281/// a terminal, and an integration pass that nobody can see is one nobody can refuse.
1282pub fn auto_setup_if_due() {
1283    if !setup_is_due() {
1284        first_run_config_review();
1285        return;
1286    }
1287    // The same question `first_run_config_review` asks, asked one step earlier. It used
1288    // to be asked only about the *prompt*, never about the pass that installs a PATH
1289    // entry, a scheduled task and a git hook — so a binary run once by an automated
1290    // system, with its output captured, silently acquired persistence on that machine.
1291    // Nothing here is skipped permanently: the stamp is not written, so the first run a
1292    // person can actually see does the pass and reports it.
1293    if !a_person_is_present() {
1294        return;
1295    }
1296
1297    review_project_venv_install();
1298
1299    let Ok(registry) = Registry::load() else {
1300        return;
1301    };
1302    match consent_state() {
1303        SetupConsent::Granted => {
1304            // Made durable even when it was inferred from a pre-1.18 stamp, so the
1305            // inference runs once rather than on every later upgrade.
1306            record_consent_granted();
1307            run_consented_pass(&registry);
1308            first_run_config_review();
1309        }
1310        SetupConsent::Declined => {
1311            // The answer was no, and staying no costs nothing to honour: stamp so this
1312            // version's pass is settled, install nothing, and leave `devp setup` as
1313            // the standing way to change the answer. The settings review is still owed
1314            // when an upgrade adds a setting — declining the integrations was never a
1315            // vote on config defaults.
1316            write_stamp();
1317            first_run_config_review();
1318        }
1319        SetupConsent::NeverAsked => {
1320            if !auto_setup_enabled(&registry) {
1321                // Suppressed. Stamp anyway, so a machine that opted out does not
1322                // re-decide this on every single command; the consent marker stays
1323                // unwritten, so lifting the opt-out later asks rather than installs.
1324                //
1325                // The one thing opting out must not do is freeze the instructions AI
1326                // agents read at whichever version installed them, so any existing
1327                // copies are still brought up to date. See `run_consented_pass` for
1328                // the fuller reasoning.
1329                refresh_stale(stale_skill_copies());
1330                write_stamp();
1331                crate::commands::config::skip_config_review();
1332                return;
1333            }
1334            ask_first_run_consent();
1335        }
1336    }
1337}
1338
1339/// One integration pass for a machine that has already said yes, reported if it did
1340/// anything.
1341fn run_consented_pass(registry: &Registry) {
1342    let Some(report) = ensure_integrations_if_enabled(registry) else {
1343        // Suppressed. Stamp anyway, so a machine that opted out does not re-decide
1344        // this on every single command.
1345        //
1346        // The one thing opting out must not do is freeze the instructions AI agents
1347        // read at whichever version installed them. The stamp below is what would
1348        // freeze them: it is rewritten for every new version without a pass ever
1349        // running, so an existing `SKILL.md` here would never be reconsidered again,
1350        // and the agent would go on describing flags that were removed two releases
1351        // ago — confidently, because nothing told it otherwise.
1352        refresh_stale(stale_skill_copies());
1353        write_stamp();
1354        crate::commands::config::skip_config_review();
1355        return;
1356    };
1357    if report.changed_anything() || report.needs_attention() {
1358        output::print_header("dev-prune setup");
1359        report.print(false);
1360        if report.changed_anything() {
1361            output::print_info(
1362                "Run `devp setup --status` to review these, or `devp uninstall` to remove them.",
1363            );
1364        }
1365        println!();
1366    }
1367    write_stamp();
1368}
1369
1370/// Ask, on the first attended run, before installing anything at all.
1371///
1372/// The old order — install, then open the walkthrough — put this binary's fingerprint
1373/// (an unasked self-copy into a managed `bin`, plus a scheduled task, on the first run
1374/// of an unsigned download) squarely on the behaviour ML malware classifiers key on;
1375/// the 1.17.0 release exe was flagged as Trojan:Win32/Wacatac.B!ml for exactly that.
1376/// Asked first, the same installs are the answer to a question — and a sandbox that
1377/// runs the binary bare now sits at a prompt instead of recording persistence.
1378fn ask_first_run_consent() {
1379    use crate::commands::config::FirstRunDecision;
1380    match crate::commands::config::first_run_wizard() {
1381        Err(e) => {
1382            // The wizard's own failure must not decide the question either way:
1383            // nothing recorded, nothing stamped, asked again on the next command.
1384            output::print_warning(&format!("Could not run the first-run setup ({e:#})."));
1385        }
1386        Ok(FirstRunDecision::Accepted) => {
1387            record_consent_granted();
1388            // Reloaded, not reused: the walkthrough that just closed may have flipped
1389            // `auto_daemon` or `auto_hooks`, and this pass exists to honour that.
1390            let Ok(registry) = Registry::load() else {
1391                return;
1392            };
1393            run_consented_pass(&registry);
1394            crate::commands::config::skip_config_review();
1395            offer_vscode_extension();
1396            println!();
1397        }
1398        Ok(FirstRunDecision::Declined) => {
1399            record_consent_declined();
1400            write_stamp();
1401            crate::commands::config::skip_config_review();
1402            output::print_info(
1403                "Nothing was installed. `devp setup` installs the integrations whenever \
1404                 you want them; `devp config wizard` reopens the settings.",
1405            );
1406            println!();
1407        }
1408        Ok(FirstRunDecision::NoAnswer) => {
1409            // EOF is not an answer — it is nobody there after all. Every marker stays
1410            // unwritten, so the first run with a person on the other end is asked.
1411        }
1412    }
1413}
1414
1415/// Put the defaults in front of the user on a fresh install, and any setting an upgrade
1416/// added that they have never been shown.
1417///
1418/// Separate from the integration stamp on purpose. The integrations are re-checked after
1419/// every upgrade; the settings are not, except for the ones that did not exist last time
1420/// — being asked to reconfirm `idle_days` on each new version would be a nuisance, and a
1421/// nuisance is something people learn to dismiss without reading.
1422///
1423/// Every condition here is a way of asking "is there a person reading this?", because the
1424/// alternative to asking is a prompt written into a log nobody will read, on a run that
1425/// then blocks forever waiting for an answer.
1426fn first_run_config_review() {
1427    if !crate::commands::config::config_review_is_due() {
1428        return;
1429    }
1430
1431    // Deliberately not stamped here. The stamp records that somebody was *shown* the
1432    // declaration, and a cron run, a CI job or a container has nobody to show it to.
1433    // Writing it anyway meant the first unattended `devp` on a machine silently spent
1434    // the one screen that says what dev-prune will not delete — so the person who
1435    // installed it never saw it, and nothing ever offered again. Left unstamped, the
1436    // walkthrough waits for the first run with a human on the other end of it, which is
1437    // the only run it was ever for.
1438    if !a_person_is_present() {
1439        return;
1440    }
1441
1442    // Any error here is the wizard's own reporting; the command the user actually typed
1443    // still runs. A failed walkthrough must not become a failed `devp status`.
1444    if let Err(e) =
1445        crate::commands::config::run_wizard(false, crate::commands::config::Opened::OnItsOwn)
1446    {
1447        output::print_warning(&format!("Could not run the first-run setup ({e:#})."));
1448    }
1449    // Marked regardless of how it ended, including a deliberate quit. This is the one
1450    // caller that runs uninvited, and an unasked-for walkthrough that reappears on every
1451    // subsequent command is worse than one somebody dismissed once on purpose.
1452    crate::commands::config::skip_config_review();
1453    // Same first run, same person already answering questions — the one moment the
1454    // extension offer is a courtesy rather than an interruption.
1455    offer_vscode_extension();
1456    println!();
1457}
1458
1459/// Invalidate the stamp so the next human-run command performs a pass.
1460///
1461/// `uninstall` calls this in reverse — it writes the current stamp — so that removing the
1462/// integrations is not immediately undone by the next command.
1463pub fn suppress_next_auto_setup() {
1464    write_stamp();
1465}
1466
1467/// Say something, once, when this copy is running from inside a project's virtualenv.
1468///
1469/// This is the remedy at the source. By the time a prune pass refuses the environment,
1470/// the user is several days and one confusing error away from the moment they typed
1471/// `pip install dev-prune` with a project activated; saying it here, on the first run
1472/// after that install, is the only chance to explain it while the cause is still in
1473/// living memory. The refusal in the venv adapter stays as the failsafe, for a copy
1474/// installed before this check existed or by somebody who dismissed it.
1475///
1476/// Silent when `requirements.txt` already lists the tool. That is somebody who meant it,
1477/// and being told about a decision you made on purpose is what teaches people to stop
1478/// reading output.
1479fn review_project_venv_install() {
1480    let Ok(exe) = std::env::current_exe() else {
1481        return;
1482    };
1483    let Some(found) = crate::channel::project_venv_install(&exe) else {
1484        return;
1485    };
1486
1487    let requirements = found.project.join("requirements.txt");
1488    let recorded = crate::adapters::venv::requirement_names(&requirements, &mut Vec::new())
1489        .is_some_and(|names| names.iter().any(|n| crate::adapters::venv::is_dev_prune(n)));
1490    if recorded {
1491        return;
1492    }
1493
1494    output::print_header(&format!(
1495        "{} is installed inside this project's virtual environment",
1496        constants::APP_NAME
1497    ));
1498    println!("  running from  {}", exe.display());
1499    println!("  environment   {}", found.venv.display());
1500    println!("  project       {}", found.project.display());
1501    println!();
1502    output::print_info(
1503        "A tool install belongs outside a project: it outlives the environment, every \
1504         repository shares it, and it never has to appear in an application's \
1505         requirements file to stay out of the way.",
1506    );
1507
1508    if requirements.is_file() {
1509        println!();
1510        output::print_info(
1511            "Until that is fixed, a prune pass will decline this project's environment \
1512             — a package `requirements.txt` does not account for is a package nothing \
1513             can rebuild.",
1514        );
1515        println!();
1516        if record_in_requirements(&requirements) {
1517            return;
1518        }
1519    }
1520
1521    println!();
1522    println!("  Remove this copy and install it as a tool instead:");
1523    println!("    pip uninstall {}", constants::APP_NAME);
1524    println!("    uv tool install {}", constants::APP_NAME);
1525    println!("    # or: pipx install {}", constants::APP_NAME);
1526    report_other_copy(&exe);
1527    println!();
1528}
1529
1530/// Offer the other repair: declare the tool a dependency of this project, on purpose.
1531///
1532/// Default no, for the reason `devp restore` defaults no on a substituted interpreter —
1533/// this is the branch that writes into a file in somebody's repository, so a reflexive
1534/// Enter must not be what agrees to it. Returns whether the file was written, which is
1535/// also whether the removal instructions are still worth printing.
1536fn record_in_requirements(requirements: &std::path::Path) -> bool {
1537    use std::io::{IsTerminal, Write};
1538    if !std::io::stdin().is_terminal() {
1539        return false;
1540    }
1541    eprint!(
1542        "Record {} in requirements.txt instead, as a deliberate dev dependency? [y/N]: ",
1543        constants::APP_NAME
1544    );
1545    if std::io::stderr().flush().is_err() {
1546        return false;
1547    }
1548    let mut input = String::new();
1549    if std::io::stdin().read_line(&mut input).is_err() {
1550        return false;
1551    }
1552    if !matches!(input.trim().to_lowercase().as_str(), "y" | "yes") {
1553        return false;
1554    }
1555
1556    let Ok(existing) = fs::read_to_string(requirements) else {
1557        output::print_warning("Could not read requirements.txt, so nothing was changed.");
1558        return false;
1559    };
1560    // Requirements files without a trailing newline are common, and appending to one
1561    // blind would glue the pin onto the last requirement.
1562    let separator = if existing.is_empty() || existing.ends_with('\n') {
1563        ""
1564    } else {
1565        "\n"
1566    };
1567    let line = format!(
1568        "{separator}{}=={}\n",
1569        constants::APP_NAME,
1570        constants::VERSION
1571    );
1572    match std::fs::OpenOptions::new()
1573        .append(true)
1574        .open(requirements)
1575        .and_then(|mut f| f.write_all(line.as_bytes()))
1576    {
1577        Ok(()) => {
1578            output::print_success(&format!(
1579                "Added `{}=={}` to {}. The environment is prunable now.",
1580                constants::APP_NAME,
1581                constants::VERSION,
1582                requirements.display()
1583            ));
1584            true
1585        }
1586        Err(e) => {
1587            output::print_warning(&format!("Could not write requirements.txt ({e})."));
1588            false
1589        }
1590    }
1591}
1592
1593/// Name the copy that is already installed properly, if there is one.
1594///
1595/// "Uninstall this" reads very differently depending on whether it leaves the user with
1596/// no tool at all or with the one they already had — and on a machine where this mistake
1597/// happens there usually is one, because the working copy is what they were reaching for
1598/// in the first place.
1599fn report_other_copy(exe: &std::path::Path) {
1600    let names: [&str; 2] = if cfg!(windows) {
1601        ["dev-prune.exe", "devp.exe"]
1602    } else {
1603        ["dev-prune", "devp"]
1604    };
1605    let home = dirs::home_dir();
1606    let other = crate::channel::install_dirs(home.as_deref())
1607        .into_iter()
1608        .flat_map(|dir| names.iter().map(move |name| dir.join(name)))
1609        .find(|candidate| candidate.is_file() && candidate != exe);
1610
1611    if let Some(other) = other {
1612        println!();
1613        output::print_info(&format!(
1614            "You already have a copy outside this project, at `{}`, so removing this one \
1615             still leaves you a working `devp`.",
1616            other.display()
1617        ));
1618    }
1619}
1620
1621#[cfg(test)]
1622mod tests {
1623    use super::*;
1624
1625    #[test]
1626    fn a_report_with_only_present_items_is_silent() {
1627        let mut report = SetupReport::default();
1628        report.push("a", Outcome::AlreadyPresent);
1629        assert!(!report.changed_anything());
1630        assert!(!report.needs_attention());
1631    }
1632
1633    #[test]
1634    fn skipped_and_failed_both_ask_for_attention() {
1635        let mut skipped = SetupReport::default();
1636        skipped.push("a", Outcome::Skipped("no git".into()));
1637        assert!(skipped.needs_attention());
1638        assert!(!skipped.changed_anything());
1639
1640        let mut failed = SetupReport::default();
1641        failed.push("a", Outcome::Failed("boom".into()));
1642        assert!(failed.needs_attention());
1643    }
1644
1645    #[test]
1646    fn an_install_counts_as_a_change() {
1647        let mut report = SetupReport::default();
1648        report.push("a", Outcome::Installed);
1649        assert!(report.changed_anything());
1650    }
1651
1652    #[test]
1653    fn the_skill_export_lands_in_the_config_directory() {
1654        let dir = tempfile::TempDir::new().unwrap();
1655        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::Installed);
1656        // A second pass finds byte-identical content and leaves it alone.
1657        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::AlreadyPresent);
1658        let written = fs::read_to_string(dir.path().join("SKILL.md")).unwrap();
1659        assert_eq!(written, EMBEDDED_SKILL_MD);
1660    }
1661
1662    #[test]
1663    fn a_stale_skill_export_is_rewritten() {
1664        // An upgrade must not leave the previous version's instructions on disk.
1665        let dir = tempfile::TempDir::new().unwrap();
1666        fs::write(dir.path().join("SKILL.md"), "# an older version").unwrap();
1667        assert_eq!(ensure_skill_file_in(dir.path()), Outcome::Installed);
1668        let written = fs::read_to_string(dir.path().join("SKILL.md")).unwrap();
1669        assert_eq!(written, EMBEDDED_SKILL_MD);
1670    }
1671
1672    #[test]
1673    fn agent_skills_install_only_into_agent_homes_that_exist() {
1674        let home = tempfile::TempDir::new().unwrap();
1675        assert!(
1676            agent_skill_roots_under(home.path()).is_empty(),
1677            "a machine without an agent must detect nothing"
1678        );
1679
1680        fs::create_dir_all(home.path().join(constants::CLAUDE_HOME_DIR)).unwrap();
1681        let roots = agent_skill_roots_under(home.path());
1682        assert_eq!(roots.len(), 1);
1683
1684        assert_eq!(ensure_agent_skills_at(&roots), Outcome::Installed);
1685        let installed = home
1686            .path()
1687            .join(constants::CLAUDE_HOME_DIR)
1688            .join(constants::AGENT_SKILLS_SUBDIR)
1689            .join(constants::APP_NAME)
1690            .join("SKILL.md");
1691        assert_eq!(fs::read_to_string(&installed).unwrap(), EMBEDDED_SKILL_MD);
1692
1693        // A second pass finds it current and leaves it alone.
1694        assert_eq!(ensure_agent_skills_at(&roots), Outcome::AlreadyPresent);
1695    }
1696
1697    #[test]
1698    fn refreshing_rewrites_the_copies_that_exist_and_creates_none() {
1699        let dir = tempfile::TempDir::new().unwrap();
1700        let present = dir.path().join("SKILL.md");
1701        fs::write(&present, "# the instructions from two releases ago").unwrap();
1702        let never_installed = dir.path().join("no-agent-here").join("SKILL.md");
1703
1704        let stale = stale_among(vec![present.clone(), never_installed.clone()]);
1705        assert_eq!(stale, vec![present.clone()]);
1706
1707        refresh_stale(stale);
1708        assert_eq!(fs::read_to_string(&present).unwrap(), EMBEDDED_SKILL_MD);
1709        assert!(
1710            !never_installed.exists(),
1711            "a machine that never had a copy must not acquire one from a refresh"
1712        );
1713    }
1714
1715    #[test]
1716    fn no_detected_agent_is_a_skip_not_a_failure() {
1717        assert!(matches!(ensure_agent_skills_at(&[]), Outcome::Skipped(_)));
1718    }
1719
1720    #[test]
1721    fn the_stamp_gates_the_unattended_pass() {
1722        let dir = tempfile::TempDir::new().unwrap();
1723        assert!(setup_is_due_in(dir.path()), "a fresh install is due");
1724        write_stamp_in(dir.path());
1725        assert!(
1726            !setup_is_due_in(dir.path()),
1727            "the same version is not due twice"
1728        );
1729        fs::write(dir.path().join(STAMP_FILE), "0.0.1").unwrap();
1730        assert!(setup_is_due_in(dir.path()), "an upgrade is due again");
1731    }
1732
1733    /// The alias must never be written with a copy while it already exists.
1734    ///
1735    /// A hard link and its target share one inode, so `fs::copy` onto the alias empties
1736    /// the binary it was copied from. This reproduces the exact shape of that bug — link
1737    /// first, then ask for the alias again — and asserts the original still has its
1738    /// bytes. The real failure was silent: a zero-byte executable that macOS runs
1739    /// through `/bin/sh`, which exits 0 and prints nothing.
1740    #[test]
1741    fn refreshing_an_alias_that_is_a_hard_link_does_not_empty_the_binary() {
1742        let dir = tempfile::TempDir::new().unwrap();
1743        let binary = dir.path().join("dev-prune");
1744        let alias = dir.path().join("devp");
1745        fs::write(&binary, vec![b'M'; 4096]).unwrap();
1746
1747        if fs::hard_link(&binary, &alias).is_err() {
1748            return; // Filesystem without hard links; the hazard cannot arise.
1749        }
1750
1751        // What `ensure_alias` does when its `hard_link` loses the race: the alias is
1752        // already there, so it must stop rather than fall through to the copy.
1753        assert!(fs::hard_link(&binary, &alias).is_err(), "EEXIST expected");
1754        assert!(alias.exists(), "the guard's condition");
1755
1756        assert_eq!(
1757            fs::metadata(&binary).unwrap().len(),
1758            4096,
1759            "the running binary was truncated by refreshing its own alias"
1760        );
1761    }
1762
1763    /// The on-disk file name for one of the pair, on this platform.
1764    fn exe_name(stem: &str) -> String {
1765        if cfg!(windows) {
1766            format!("{stem}.exe")
1767        } else {
1768            stem.to_string()
1769        }
1770    }
1771
1772    #[test]
1773    fn dev_prune_creates_devp_beside_it() {
1774        let dir = tempfile::TempDir::new().unwrap();
1775        let canonical = dir.path().join(exe_name("dev-prune"));
1776        fs::write(&canonical, "the binary").unwrap();
1777
1778        assert_eq!(ensure_twin_of(&canonical, dir.path()), Outcome::Installed);
1779        let alias = dir.path().join(exe_name("devp"));
1780        assert!(alias.is_file(), "`devp` was not created");
1781        assert_eq!(fs::read_to_string(&alias).unwrap(), "the binary");
1782    }
1783
1784    /// The pair has to be recoverable from either side.
1785    ///
1786    /// Deleting `dev-prune` and leaving `devp` is not hypothetical: an antivirus
1787    /// quarantine, a half-finished uninstall, or a `Remove-Item` aimed at one name all
1788    /// produce it. Before this, `devp setup` reported the alias already present and did
1789    /// nothing, because the only direction it knew how to repair was the other one.
1790    #[test]
1791    fn devp_restores_a_missing_dev_prune() {
1792        let dir = tempfile::TempDir::new().unwrap();
1793        let alias = dir.path().join(exe_name("devp"));
1794        fs::write(&alias, "the binary").unwrap();
1795
1796        assert_eq!(ensure_twin_of(&alias, dir.path()), Outcome::Installed);
1797        let canonical = dir.path().join(exe_name("dev-prune"));
1798        assert!(canonical.is_file(), "`dev-prune` was not put back");
1799        assert_eq!(fs::read_to_string(&canonical).unwrap(), "the binary");
1800    }
1801
1802    /// `devp` may create `dev-prune`, never overwrite it.
1803    ///
1804    /// Repairing in both directions opens a downgrade: an upgrade replaces `dev-prune`
1805    /// first and can then fail on a `devp` that is running, which leaves the alias holding
1806    /// the *older* binary. If the alias were allowed to refresh its twin from there, the
1807    /// next `devp setup` would quietly reinstall the version the user just upgraded away
1808    /// from — and report it as a repair.
1809    #[test]
1810    fn devp_does_not_overwrite_an_existing_dev_prune() {
1811        let dir = tempfile::TempDir::new().unwrap();
1812        let alias = dir.path().join(exe_name("devp"));
1813        let canonical = dir.path().join(exe_name("dev-prune"));
1814        fs::write(&alias, "the previous version").unwrap();
1815        fs::write(&canonical, "the version just upgraded to").unwrap();
1816
1817        assert_eq!(
1818            ensure_twin_of(&alias, dir.path()),
1819            Outcome::AlreadyPresent,
1820            "`devp` must leave an existing `dev-prune` alone"
1821        );
1822        assert_eq!(
1823            fs::read_to_string(&canonical).unwrap(),
1824            "the version just upgraded to",
1825            "`devp` downgraded the binary it was supposed to leave alone"
1826        );
1827    }
1828
1829    /// The same downgrade, coming the other way — the direction the gate above lets
1830    /// through.
1831    ///
1832    /// `devp` is blocked from refreshing `dev-prune` outright, but `dev-prune` refreshing
1833    /// `devp` was gated on nothing but the two files differing, on the assumption that the
1834    /// canonical name is always the newer one. Restore a `dev-prune` from a backup, or run
1835    /// one out of a package-manager cache, and it is not — and `devp doctor --fix` runs
1836    /// `ensure_alias` from whichever binary is executing, so an older `dev-prune` would
1837    /// delete a newer `devp` and link its own content over it while reporting a repair.
1838    #[test]
1839    fn a_twin_that_is_not_behind_is_left_alone() {
1840        assert!(
1841            !twin_is_stale(Some((1, 12, 0)), Some((1, 11, 0))),
1842            "a newer twin must not be overwritten"
1843        );
1844        assert!(
1845            !twin_is_stale(Some((1, 11, 0)), Some((1, 11, 0))),
1846            "an equal twin has nothing to refresh"
1847        );
1848        assert!(
1849            twin_is_stale(Some((1, 10, 0)), Some((1, 11, 0))),
1850            "a genuinely older twin is what this refresh is for"
1851        );
1852        // Neither side able to state a version leaves the old content-only rule, which is
1853        // the only answer available: whatever the file is, it is not a working build of
1854        // this CLI, and leaving it would keep a broken `devp` on PATH forever.
1855        assert!(twin_is_stale(None, Some((1, 11, 0))));
1856        assert!(twin_is_stale(Some((1, 11, 0)), None));
1857    }
1858
1859    #[test]
1860    fn versions_parse_strictly_or_not_at_all() {
1861        assert_eq!(parse_version("1.2.3"), Some((1, 2, 3)));
1862        assert_eq!(parse_version("10.0.0"), Some((10, 0, 0)));
1863        // Anything this project does not publish must answer None, because a None
1864        // means "replace the copy" and a mis-parse would order versions wrongly.
1865        assert_eq!(parse_version("1.2"), None);
1866        assert_eq!(parse_version("1.2.3.4"), None);
1867        assert_eq!(parse_version("1.2.3-rc1"), None);
1868        assert_eq!(parse_version("dev-prune"), None);
1869        // The version this binary was built with has to be parseable, or the refresh
1870        // logic can never decide anything.
1871        assert!(parse_version(constants::VERSION).is_some());
1872    }
1873
1874    #[test]
1875    fn the_version_this_cli_prints_is_one_this_cli_can_read_back() {
1876        // Not synthetic: this is the shape `print_version_info` writes, `v` and all,
1877        // down to the banner line that ends in the same token.
1878        let real = format!(
1879            "|_____|   v{v}
1880
1881dev-prune (devp) v{v}
1882  Compiler:        Rust 1.88+ (edition 2024)
1883",
1884            v = constants::VERSION
1885        );
1886        assert_eq!(
1887            version_in_output(&real),
1888            parse_version(constants::VERSION),
1889            "binary_version could not read this binary's own --version output"
1890        );
1891        // Something that is not this CLI still has to answer None, because doctor uses
1892        // that to mean "leave this file alone".
1893        assert_eq!(version_in_output("git version 2.51.0.windows.1"), None);
1894        assert_eq!(version_in_output("some other tool"), None);
1895    }
1896
1897    #[test]
1898    fn ordering_of_version_triples_matches_semver() {
1899        assert!(parse_version("1.1.0") > parse_version("1.0.9"));
1900        assert!(parse_version("2.0.0") > parse_version("1.99.99"));
1901        assert!(parse_version("1.0.10") > parse_version("1.0.9"));
1902    }
1903
1904    #[test]
1905    fn the_exported_skill_is_the_one_the_binary_was_built_with() {
1906        // `SKILL.md` is embedded, so a doc edit ships only if the binary is rebuilt.
1907        // Guard the two properties every consumer of it depends on.
1908        assert!(EMBEDDED_SKILL_MD.starts_with("---"), "needs frontmatter");
1909        assert!(
1910            !EMBEDDED_SKILL_MD.contains("file:///"),
1911            "SKILL.md is written to every user's machine — it must not contain \
1912             absolute paths from the author's checkout"
1913        );
1914    }
1915
1916    #[test]
1917    fn a_fresh_machine_has_never_been_asked() {
1918        let dir = tempfile::TempDir::new().unwrap();
1919        assert_eq!(consent_state_in(dir.path()), SetupConsent::NeverAsked);
1920    }
1921
1922    #[test]
1923    fn a_recorded_answer_is_read_back() {
1924        let dir = tempfile::TempDir::new().unwrap();
1925        record_consent_in(dir.path(), CONSENT_GRANTED);
1926        assert_eq!(consent_state_in(dir.path()), SetupConsent::Granted);
1927        record_consent_in(dir.path(), CONSENT_DECLINED);
1928        assert_eq!(consent_state_in(dir.path()), SetupConsent::Declined);
1929    }
1930
1931    #[test]
1932    fn a_garbled_marker_means_the_question_is_still_open() {
1933        // Better to ask twice than to install on the strength of a corrupt file.
1934        let dir = tempfile::TempDir::new().unwrap();
1935        record_consent_in(dir.path(), "maybe?");
1936        assert_eq!(consent_state_in(dir.path()), SetupConsent::NeverAsked);
1937    }
1938
1939    #[test]
1940    fn a_pre_consent_stamp_counts_as_granted() {
1941        // The old flow only ever stamped after installing, so a 1.17 stamp is proof
1942        // the integrations are already on this machine.
1943        let dir = tempfile::TempDir::new().unwrap();
1944        fs::write(dir.path().join(STAMP_FILE), "1.17.0\n").unwrap();
1945        assert_eq!(consent_state_in(dir.path()), SetupConsent::Granted);
1946    }
1947
1948    #[test]
1949    fn a_post_consent_stamp_proves_nothing() {
1950        // From 1.18.0 on, the opted-out path writes the stamp too — treating it as a
1951        // yes would silently grant consent on the exact machines that withheld it.
1952        let dir = tempfile::TempDir::new().unwrap();
1953        // Not `constants::VERSION`: until the release that ships this bumps it past
1954        // FIRST_CONSENT_VERSION, the current version is itself a pre-consent one.
1955        for stamp in [FIRST_CONSENT_VERSION, "1.18.1", "2.0.0", "garbage"] {
1956            fs::write(dir.path().join(STAMP_FILE), stamp).unwrap();
1957            assert_eq!(
1958                consent_state_in(dir.path()),
1959                SetupConsent::NeverAsked,
1960                "stamp {stamp:?} must not imply consent"
1961            );
1962        }
1963    }
1964
1965    #[test]
1966    fn an_explicit_answer_outranks_the_stamp() {
1967        let dir = tempfile::TempDir::new().unwrap();
1968        fs::write(dir.path().join(STAMP_FILE), "1.17.0").unwrap();
1969        record_consent_in(dir.path(), CONSENT_DECLINED);
1970        assert_eq!(consent_state_in(dir.path()), SetupConsent::Declined);
1971    }
1972
1973    #[test]
1974    fn clearing_consent_reopens_the_question() {
1975        let dir = tempfile::TempDir::new().unwrap();
1976        record_consent_in(dir.path(), CONSENT_GRANTED);
1977        fs::remove_file(dir.path().join(constants::SETUP_CONSENT_FILE)).unwrap();
1978        assert_eq!(consent_state_in(dir.path()), SetupConsent::NeverAsked);
1979    }
1980}