Skip to main content

dev_prune/
engine.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Pruning engine — orchestrates the full prune pass.
5//
6// This module is the "brain" of dev-prune. It coordinates:
7// 1. Git repo validation
8// 2. Activity/idle checking
9// 3. Adapter detection
10// 4. Lockfile enforcement
11// 5. Safe bloat directory deletion
12//
13// The engine enforces all safety invariants described in the project spec.
14
15use std::collections::BTreeMap;
16use std::fs;
17use std::path::{Path, PathBuf};
18use std::time::SystemTime;
19
20use anyhow::Result;
21use chrono::{DateTime, Utc};
22
23use crate::adapters::BloatDir;
24use crate::config::{Registry, RepoEntry};
25use crate::constants;
26use crate::scanner;
27use crate::scanner::git;
28use crate::workspace;
29
30/// The outcome of pruning a single bloat directory.
31#[derive(Debug, Clone)]
32pub enum PruneStatus {
33    /// Successfully deleted the bloat directory.
34    Pruned,
35    /// Skipped because the repo is still active (not idle).
36    SkippedActive,
37    /// Skipped because it's a dry run.
38    SkippedDryRun,
39    /// Skipped because lockfile enforcement failed.
40    LockfileError(String),
41    /// Skipped because the repository's last activity could not be determined.
42    ///
43    /// Not a `LockfileError`: that tag carries a `fix_command` an agent is told it can
44    /// run, and "git failed to answer" has no such mechanical fix.
45    ActivityCheckError(String),
46    /// The registered path no longer exists on disk.
47    PathMissing,
48    /// The registered path still exists on disk but no longer holds a `.git`.
49    ///
50    /// A standing state, not an error: the clone was deleted and recreated by hand, or
51    /// it was a worktree `git worktree prune` has since removed — and reporting it as
52    /// a failure made every scheduled pass exit non-zero forever, for a directory
53    /// nothing could ever have been touched in. Same reasoning as
54    /// [`Self::PathMissing`], but its own variant because the fix is different:
55    /// `devp unlink --missing` only clears entries whose directory has gone, and this
56    /// one is still there.
57    NotARepo,
58    /// An adapter that waits for a longer idle window than the repository's own
59    /// threshold was not examined, because the repository has not been idle that long
60    /// yet. Carries the window, in days.
61    ///
62    /// This was a bare `continue` with no row behind it, and every surface downstream
63    /// then disagreed about the repository: `--explain` said "idle, but no known bloat
64    /// directories were found", `status` said Candidate, `doctor` said Yes — and a run
65    /// touched nothing. Worded as "not examined" rather than "skipped bloat"
66    /// deliberately: the gate fires before the adapter is asked for its directories,
67    /// so there may be nothing behind it at all.
68    SkippedAdapterWindow(u64),
69    /// Skipped because the bloat directory doesn't exist.
70    NoBloat,
71    /// Repo is disabled in the registry.
72    Disabled,
73    /// Repo has a `ignore.devprune.json` file — opted out.
74    SkippedIgnored,
75    /// Error during deletion.
76    DeleteError(String),
77    /// The bloat directory is a symlink or junction, so it was deliberately left alone.
78    ///
79    /// A skip, not an error: the storage it points at is not this repository's to
80    /// delete, and the situation is permanent — reporting it as a failure made every
81    /// scheduled pass over such a repo exit non-zero forever.
82    SkippedSymlink(String),
83    /// `.devprune.json` exists but could not be parsed, so the repo was left alone.
84    ConfigError(String),
85    /// A directory the project declared prunable did not survive its checks.
86    ///
87    /// Not a `LockfileError` even though it is the same kind of refusal: that tag
88    /// carries a `fix_command` in `--json`, and there is no command that fixes "your
89    /// repository declares its own source directory".
90    SkippedDeclaration(String),
91    /// The directory holds a git repository of its own, so it was deliberately left
92    /// alone.
93    ///
94    /// A skip, not a `DeleteError`: a vendored checkout — a pip `-e git+…` install
95    /// under `.venv/src/`, a `file:` dependency — is a permanent fact of the
96    /// repository, and reporting it as a failure made every scheduled pass over such
97    /// a repo exit non-zero forever while `--dry-run` over the same repo exited 0.
98    SkippedNestedRepo(String),
99}
100
101impl std::fmt::Display for PruneStatus {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            PruneStatus::Pruned => write!(f, "Pruned"),
105            PruneStatus::SkippedActive => write!(f, "Skipped (active)"),
106            PruneStatus::SkippedDryRun => write!(f, "Skipped (dry run)"),
107            PruneStatus::LockfileError(e) => write!(f, "Lockfile error: {e}"),
108            PruneStatus::ActivityCheckError(e) => write!(f, "Activity check failed: {e}"),
109            PruneStatus::PathMissing => {
110                write!(
111                    f,
112                    "Path no longer exists (`devp unlink --missing` clears it)"
113                )
114            }
115            PruneStatus::NotARepo => {
116                write!(
117                    f,
118                    "No longer a git repository (`devp unlink` removes the entry)"
119                )
120            }
121            PruneStatus::SkippedAdapterWindow(days) => {
122                write!(f, "Not examined (adapter idle window: {days} days)")
123            }
124            PruneStatus::NoBloat => write!(f, "No bloat found"),
125            PruneStatus::Disabled => write!(f, "Disabled"),
126            PruneStatus::SkippedIgnored => write!(
127                f,
128                "Ignored (ignore.devprune.json or ignore config in .devprune.json)"
129            ),
130            PruneStatus::DeleteError(e) => write!(f, "Delete error: {e}"),
131            PruneStatus::SkippedSymlink(e) => write!(f, "Skipped (symlink): {e}"),
132            PruneStatus::ConfigError(e) => write!(f, "Unreadable .devprune.json: {e}"),
133            PruneStatus::SkippedDeclaration(e) => write!(f, "Skipped (declaration): {e}"),
134            PruneStatus::SkippedNestedRepo(e) => write!(f, "Skipped (nested repository): {e}"),
135        }
136    }
137}
138
139/// Bytes in one mebibyte. The size floor is configured in MiB because that is the unit
140/// `format_bytes` prints, so a user who sets `10` sees the same number they typed.
141pub const BYTES_PER_MIB: u64 = 1024 * 1024;
142
143/// Which package managers a pass is allowed to act on.
144///
145/// The default allows everything. Built through [`AdapterFilter::new`], which rejects
146/// names no adapter answers to — a typo like `--only pmpm` silently matching nothing
147/// looks exactly like "there was no bloat", and that is the wrong thing to believe about
148/// a tool that deletes directories.
149#[derive(Debug, Clone, Default, PartialEq)]
150pub struct AdapterFilter {
151    only: Option<Vec<String>>,
152    skip: Vec<String>,
153}
154
155impl AdapterFilter {
156    /// Build a filter from comma-separated `--only` / `--skip` values.
157    ///
158    /// Names are matched case-insensitively. Listing the same adapter in both lists is
159    /// a contradiction rather than a precedence puzzle, so it is rejected outright.
160    pub fn new(only: Option<&str>, skip: Option<&str>) -> Result<Self> {
161        // `declared` is not a package manager and has no adapter, but it fills the
162        // same column of the same report, and a user who can see `declared` in
163        // `devp status` will reasonably try to `--only` it.
164        let known: Vec<&'static str> = crate::adapters::get_all_adapters()
165            .iter()
166            .map(|a| a.name())
167            .chain(std::iter::once(constants::DECLARED_ADAPTER_NAME))
168            .collect();
169
170        let parse = |raw: &str, flag: &str| -> Result<Vec<String>> {
171            let mut out = Vec::new();
172            for token in raw.split(',') {
173                let name = token.trim().to_lowercase();
174                if name.is_empty() {
175                    continue;
176                }
177                if !known.contains(&name.as_str()) {
178                    anyhow::bail!(
179                        "`--{flag} {name}` names no known package manager. Available: {}.",
180                        known.join(", ")
181                    );
182                }
183                if !out.contains(&name) {
184                    out.push(name);
185                }
186            }
187            if out.is_empty() {
188                anyhow::bail!("`--{flag}` was given no adapter names.");
189            }
190            Ok(out)
191        };
192
193        let only = only.map(|raw| parse(raw, "only")).transpose()?;
194        let skip = skip
195            .map(|raw| parse(raw, "skip"))
196            .transpose()?
197            .unwrap_or_default();
198
199        if let Some(only) = &only
200            && let Some(clash) = only.iter().find(|n| skip.contains(n))
201        {
202            anyhow::bail!("`{clash}` is in both --only and --skip; pick one.");
203        }
204
205        Ok(Self { only, skip })
206    }
207
208    /// Whether this filter would let `name` through.
209    pub fn allows(&self, name: &str) -> bool {
210        if self.skip.iter().any(|s| s == name) {
211            return false;
212        }
213        match &self.only {
214            Some(only) => only.iter().any(|o| o == name),
215            None => true,
216        }
217    }
218
219    /// Whether the filter restricts anything at all.
220    pub fn is_unrestricted(&self) -> bool {
221        self.only.is_none() && self.skip.is_empty()
222    }
223
224    /// Human-readable summary for the run header, or `None` when nothing is filtered.
225    pub fn describe(&self) -> Option<String> {
226        if self.is_unrestricted() {
227            return None;
228        }
229        let mut parts = Vec::new();
230        if let Some(only) = &self.only {
231            parts.push(format!("only {}", only.join(", ")));
232        }
233        if !self.skip.is_empty() {
234            parts.push(format!("skipping {}", self.skip.join(", ")));
235        }
236        Some(parts.join("; "))
237    }
238}
239
240/// Everything that shapes a prune pass beyond the repository itself.
241///
242/// `Default` is written out rather than derived: `scan_depth` has a real default that is
243/// not zero, and a derived one would have made every `..Default::default()` call site
244/// quietly walk a single level and report a monorepo as empty.
245#[derive(Debug, Clone)]
246pub struct PruneOptions {
247    /// Days of inactivity required before the repository is eligible.
248    pub idle_days: u64,
249    /// Report sizes and stop. Nothing is verified and nothing is deleted.
250    pub dry_run: bool,
251    /// Bypass the idle check. Lockfile verification still applies.
252    pub force: bool,
253    /// Restrict the pass to these repository-relative bloat directory labels.
254    ///
255    /// `Some` means a caller has already chosen — the interactive selector, or the
256    /// second phase of `devp run`. The size floor is not applied on top of an explicit
257    /// choice, because the caller has already decided these directories are wanted.
258    pub only_dirs: Option<Vec<String>>,
259    /// Which package managers may act.
260    pub adapters: AdapterFilter,
261    /// Smallest directory worth deleting. `0` disables the floor.
262    pub min_size_bytes: u64,
263    /// How deep to walk each repository looking for projects.
264    ///
265    /// The global setting. A repository's own `.devprune.json` may raise or lower it —
266    /// see [`workspace::resolve_depth`], which this is fed into.
267    pub scan_depth: usize,
268    /// Whether an adapter may run the sync command that rewrites its tracked lockfile.
269    pub allow_manifest_rewrite: bool,
270    /// Ceiling on any one package-manager command, in seconds.
271    ///
272    /// The user's `command_timeout_secs`. It was settable, displayed by `devp status`
273    /// and named in the timeout message long before anything actually read it here.
274    pub command_timeout_secs: u64,
275    /// Idle days required before *build-tree* directories are touched.
276    ///
277    /// Applied as `max(build_idle_days, idle_days)`, only to adapters that answer
278    /// [`crate::adapters::PackageManager::opt_in`]. A recompile costs more than a
279    /// reinstall, so those directories wait longer.
280    pub build_idle_days: u64,
281    /// Per-adapter idle windows, keyed by adapter name; the user's `adapter_idle_days`.
282    ///
283    /// A floor on top of everything else, never a bypass — see
284    /// [`PruneOptions::idle_threshold_for`].
285    pub adapter_idle_days: BTreeMap<String, u64>,
286}
287
288impl Default for PruneOptions {
289    fn default() -> Self {
290        Self {
291            idle_days: 0,
292            dry_run: false,
293            force: false,
294            only_dirs: None,
295            adapters: AdapterFilter::default(),
296            min_size_bytes: 0,
297            scan_depth: crate::constants::DEFAULT_SCAN_DEPTH,
298            allow_manifest_rewrite: crate::constants::DEFAULT_ALLOW_MANIFEST_REWRITE,
299            command_timeout_secs: crate::constants::DEFAULT_COMMAND_TIMEOUT_SECS,
300            build_idle_days: crate::constants::DEFAULT_BUILD_IDLE_DAYS,
301            adapter_idle_days: BTreeMap::new(),
302        }
303    }
304}
305
306impl PruneOptions {
307    /// How many idle days this adapter needs before its directories may be deleted.
308    ///
309    /// Three rules, applied in order and each one only ever able to raise the bar:
310    ///
311    /// 1. the repository-level window (`idle_days`, or the repo's own override), which
312    ///    every adapter has already had to clear before this is asked;
313    /// 2. `build_idle_days` for an adapter holding compiler output;
314    /// 3. this adapter's own entry in `adapter_idle_days`, if there is one.
315    ///
316    /// Only ever raise, because the repository-level check runs once for the whole
317    /// repository and is the gate that makes "active work is never touched" true. An
318    /// adapter that could lower it would be a bypass of that gate wearing a
319    /// preference's clothes, so a smaller number is accepted and does nothing.
320    fn idle_threshold_for(&self, name: &str, opt_in: bool, base: u64) -> u64 {
321        adapter_idle_threshold(
322            name,
323            opt_in,
324            base,
325            self.build_idle_days,
326            &self.adapter_idle_days,
327        )
328    }
329
330    /// The common case: prune everything eligible in this repository.
331    pub fn new(idle_days: u64, dry_run: bool, force: bool) -> Self {
332        Self {
333            idle_days,
334            dry_run,
335            force,
336            ..Self::default()
337        }
338    }
339}
340
341/// The idle threshold one adapter is held to, in days.
342///
343/// The one place the merge lives: the prune gate, `status_for_repo` and `devp doctor`
344/// all answer "how long must this repository be idle before this adapter is touched?"
345/// through this function. Each used to compute its own answer — the gate correctly,
346/// the other two not at all — which is how a window-held repository was a Candidate
347/// on the dashboard and a "Yes" in doctor while every pass left it alone.
348pub(crate) fn adapter_idle_threshold(
349    name: &str,
350    opt_in: bool,
351    base: u64,
352    build_idle_days: u64,
353    adapter_idle_days: &BTreeMap<String, u64>,
354) -> u64 {
355    let mut days = base;
356    if opt_in {
357        days = days.max(build_idle_days);
358    }
359    if let Some(&explicit) = adapter_idle_days.get(name) {
360        days = days.max(explicit);
361    }
362    days
363}
364
365/// Result of pruning a single bloat directory in a single repo.
366#[derive(Debug, Clone)]
367pub struct PruneResult {
368    /// Path to the repository.
369    pub repo_path: PathBuf,
370    /// Name of the adapter that handled this.
371    pub adapter_name: String,
372    /// The bloat directory that was (or would be) pruned.
373    pub bloat_dir: String,
374    /// Bytes freed (0 if not pruned).
375    pub size_freed: u64,
376    /// Bytes hardlinked into a package-manager store outside the pruned directory.
377    /// The store keeps them, so they are excluded from `size_freed` — this carries
378    /// them separately so reports can say why the number is smaller than `du` says.
379    pub shared_bytes: u64,
380    /// The language runtime the directory was built against, captured before the delete.
381    /// Only the Python managers set it; see [`crate::config::PrunedDir::runtime`].
382    pub runtime: Option<String>,
383    /// What happened.
384    pub status: PruneStatus,
385}
386
387impl PruneResult {
388    /// The directory a fix command has to be run from.
389    ///
390    /// `bloat_dir` is the label relative to the repository root, so in a monorepo it is
391    /// `backend/.venv`, not `.venv` — and `uv lock` run at the repository root would
392    /// rebuild a different project, or find nothing at all. Its parent is the project
393    /// directory the adapter actually detected. A fix command you can only run after
394    /// working out which directory it meant is not a fix command.
395    pub fn project_dir(&self) -> PathBuf {
396        self.repo_path
397            .join(&self.bloat_dir)
398            .parent()
399            .map(Path::to_path_buf)
400            .unwrap_or_else(|| self.repo_path.clone())
401    }
402}
403
404/// Prune a single repository. Returns results for each bloat directory found.
405///
406/// # Safety Invariants
407/// 1. The path MUST contain a valid `.git` directory
408/// 2. The repo must be idle (unless `force` is true)
409/// 3. Lockfile enforcement MUST succeed before any deletion
410pub fn prune_repo(
411    repo_path: &Path,
412    idle_days: u64,
413    dry_run: bool,
414    force: bool,
415) -> Vec<PruneResult> {
416    prune_repo_with(repo_path, &PruneOptions::new(idle_days, dry_run, force))
417}
418
419/// Prune a repository, optionally restricted to a specific set of bloat directories.
420///
421/// `only` is a list of `BloatDir::name` values. When `Some`, any bloat directory whose
422/// name is not in the list is left untouched and produces no result — this is what makes
423/// the interactive selector's per-directory choices meaningful. When `None`, every
424/// detected bloat directory is pruned.
425///
426/// Same safety invariants as [`prune_repo`].
427pub fn prune_repo_selected(
428    repo_path: &Path,
429    idle_days: u64,
430    dry_run: bool,
431    force: bool,
432    only: Option<&[String]>,
433) -> Vec<PruneResult> {
434    prune_repo_with(
435        repo_path,
436        &PruneOptions {
437            only_dirs: only.map(<[String]>::to_vec),
438            ..PruneOptions::new(idle_days, dry_run, force)
439        },
440    )
441}
442
443/// Prune a repository under a full set of [`PruneOptions`].
444///
445/// This is the single implementation; [`prune_repo`] and [`prune_repo_selected`] are
446/// thin wrappers for the two common shapes.
447pub fn prune_repo_with(repo_path: &Path, opts: &PruneOptions) -> Vec<PruneResult> {
448    let idle_days = opts.idle_days;
449    let dry_run = opts.dry_run;
450    let force = opts.force;
451    let only = opts.only_dirs.as_deref();
452    let mut results = Vec::new();
453
454    // A registered path that is gone gets a visible line, not silence. Returning empty
455    // results made the repository vanish from the run report entirely, which reads as
456    // "handled" when the truth is "not found".
457    if !repo_path.exists() {
458        results.push(PruneResult {
459            repo_path: repo_path.to_path_buf(),
460            adapter_name: "-".to_string(),
461            bloat_dir: "-".to_string(),
462            size_freed: 0,
463            shared_bytes: 0,
464            runtime: None,
465            status: PruneStatus::PathMissing,
466        });
467        return results;
468    }
469
470    // A registered path whose `.git` has gone (deleted by hand, or a worktree pruned
471    // by `git worktree prune`) must not vanish from the report the way it once did —
472    // same reasoning as the PathMissing line above: silence reads as "handled". It was
473    // an `ActivityCheckError` for a while, which read fine but counted as a blocking
474    // failure — so one dead registry entry turned every scheduled pass red until the
475    // user happened to look at why.
476    if !scanner::is_git_repo(repo_path) {
477        results.push(PruneResult {
478            repo_path: repo_path.to_path_buf(),
479            adapter_name: "-".to_string(),
480            bloat_dir: "-".to_string(),
481            size_freed: 0,
482            shared_bytes: 0,
483            runtime: None,
484            status: PruneStatus::NotARepo,
485        });
486        return results;
487    }
488
489    // Instant 0ms Check: if `ignore.devprune.json` exists in repo root, skip immediately without parsing any JSON files!
490    if repo_path.join(constants::DEVPRUNE_IGNORE_FILE).exists() {
491        results.push(PruneResult {
492            repo_path: repo_path.to_path_buf(),
493            adapter_name: "-".to_string(),
494            bloat_dir: "-".to_string(),
495            size_freed: 0,
496            shared_bytes: 0,
497            runtime: None,
498            status: PruneStatus::SkippedIgnored,
499        });
500        return results;
501    }
502
503    // A `.devprune.json` that does not parse is a refusal to guess, not a missing file.
504    // Falling back to defaults would drop `"ignore": true` and prune a repository the
505    // user explicitly opted out of, so an unreadable config skips the repo entirely.
506    let per_repo_config = match crate::config::PerRepoConfig::load_with_diagnostics(repo_path) {
507        Ok(cfg) => cfg,
508        Err(e) => {
509            results.push(PruneResult {
510                repo_path: repo_path.to_path_buf(),
511                adapter_name: "-".to_string(),
512                bloat_dir: "-".to_string(),
513                size_freed: 0,
514                shared_bytes: 0,
515                runtime: None,
516                status: PruneStatus::ConfigError(e),
517            });
518            return results;
519        }
520    };
521    if per_repo_config.as_ref().map(|c| c.ignore).unwrap_or(false) {
522        results.push(PruneResult {
523            repo_path: repo_path.to_path_buf(),
524            adapter_name: "-".to_string(),
525            bloat_dir: "-".to_string(),
526            size_freed: 0,
527            shared_bytes: 0,
528            runtime: None,
529            status: PruneStatus::SkippedIgnored,
530        });
531        return results;
532    }
533
534    // Effective idle days from per-repo config or parameter
535    let effective_idle_days = per_repo_config
536        .as_ref()
537        .and_then(|c| c.override_idle_days)
538        .unwrap_or(idle_days);
539
540    // A repository may set its own floor, including `0` to opt out of a global one.
541    // An explicit directory selection overrides both: the caller already chose.
542    let min_size_bytes = if only.is_some() {
543        0
544    } else {
545        per_repo_config
546            .as_ref()
547            .and_then(|c| c.min_size_mb)
548            .map(|mb| mb.saturating_mul(BYTES_PER_MIB))
549            .unwrap_or(opts.min_size_bytes)
550    };
551
552    // Check if repo is idle (skip if active, unless forced)
553    if !force {
554        match git::is_repo_idle(repo_path, effective_idle_days) {
555            Ok(false) => {
556                results.push(PruneResult {
557                    repo_path: repo_path.to_path_buf(),
558                    adapter_name: "-".to_string(),
559                    bloat_dir: "-".to_string(),
560                    size_freed: 0,
561                    shared_bytes: 0,
562                    runtime: None,
563                    status: PruneStatus::SkippedActive,
564                });
565                return results;
566            }
567            Ok(true) => {} // Continue — repo is idle
568            Err(e) => {
569                results.push(PruneResult {
570                    repo_path: repo_path.to_path_buf(),
571                    adapter_name: "-".to_string(),
572                    bloat_dir: "-".to_string(),
573                    size_freed: 0,
574                    shared_bytes: 0,
575                    runtime: None,
576                    status: PruneStatus::ActivityCheckError(e.to_string()),
577                });
578                return results;
579            }
580        }
581    }
582
583    // A repository can hold several projects at several depths — `frontend/` on pnpm,
584    // `services/api/` on uv, `cli/` on cargo — and each is verified and pruned on its
585    // own terms.
586    let projects = workspace::discover_to_depth(
587        repo_path,
588        workspace::resolve_depth(repo_path, opts.scan_depth),
589    );
590
591    // Two adapters can legitimately claim the same directory (e.g. a cargo workspace
592    // member and its workspace root both resolving to the same `target`). Without this
593    // guard the size is counted twice and the second delete fails with "not found".
594    let mut claimed: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
595
596    // One `git log` walk per distinct threshold, computed lazily. Before per-adapter
597    // windows there was only ever one extra threshold to check; now a repository with
598    // cargo at 45 days and npm pinned to 30 needs two, and each is worth caching because
599    // the walk is the expensive part of a pass that finds nothing.
600    let mut idle_at: BTreeMap<u64, bool> = BTreeMap::new();
601
602    // One row per held adapter, not one per project: a monorepo with thirty cargo
603    // members would otherwise report the same window thirty times.
604    let mut window_reported: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
605
606    for project in &projects {
607        for adapter in &project.adapters {
608            if !opts.adapters.allows(adapter.name()) {
609                continue;
610            }
611
612            // Build trees come back by recompiling, and any adapter may carry a window
613            // of its own, so each one is asked what it needs. `force` bypasses this
614            // exactly as it bypasses the normal idle check; verification still applies.
615            let threshold =
616                opts.idle_threshold_for(adapter.name(), adapter.opt_in(), effective_idle_days);
617            if threshold > effective_idle_days && !force {
618                let idle_enough = *idle_at
619                    .entry(threshold)
620                    .or_insert_with(|| git::is_repo_idle(repo_path, threshold).unwrap_or(false));
621                if !idle_enough {
622                    // Held, not silent. This `continue` used to be the whole story,
623                    // and nothing downstream could say why the pass left the
624                    // repository alone.
625                    if window_reported.insert(adapter.name().to_string()) {
626                        results.push(PruneResult {
627                            repo_path: repo_path.to_path_buf(),
628                            adapter_name: adapter.name().to_string(),
629                            bloat_dir: "-".to_string(),
630                            size_freed: 0,
631                            shared_bytes: 0,
632                            runtime: None,
633                            status: PruneStatus::SkippedAdapterWindow(threshold),
634                        });
635                    }
636                    continue;
637                }
638            }
639
640            // Labels are repo-relative (`node_modules`, `frontend/node_modules`) so that
641            // two directories with the same basename in different projects stay
642            // distinguishable — both on screen and in the `only` selection.
643            //
644            // The size floor is applied before `claimed`, so a directory rejected for
645            // being too small does not also block a second adapter from considering it.
646            let bloat_dirs: Vec<(String, BloatDir)> = adapter
647                .bloat_dirs(&project.path)
648                .into_iter()
649                .map(|bd| (workspace::relative_label(repo_path, &bd.path), bd))
650                .filter(|(label, _)| only.is_none_or(|names| names.contains(label)))
651                .filter(|(_, bd)| bd.size_bytes >= min_size_bytes)
652                .filter(|(_, bd)| claimed.insert(bd.path.clone()))
653                .collect();
654
655            if bloat_dirs.is_empty() {
656                continue;
657            }
658
659            // Both refusals run before the dry-run branch AND before lockfile
660            // enforcement. Before dry-run, because an analysis that counted a
661            // symlinked or nested-git directory as reclaimable promised space the
662            // real pass then refused to touch. Before enforcement, because with
663            // `allow_manifest_rewrite` the enforcement step may rewrite a tracked
664            // lockfile — and rewriting one in service of directories that are then
665            // every one refused leaves a modified tracked file behind with nothing
666            // deleted, the exact background-pass surprise the config forbids.
667            let mut deletable: Vec<(String, BloatDir)> = Vec::new();
668            for (label, bd) in bloat_dirs {
669                if let Some(status) = shared_storage_refusal(&bd.path) {
670                    results.push(PruneResult {
671                        repo_path: repo_path.to_path_buf(),
672                        adapter_name: adapter.name().to_string(),
673                        bloat_dir: label,
674                        size_freed: 0,
675                        shared_bytes: 0,
676                        runtime: None,
677                        status,
678                    });
679                    continue;
680                }
681
682                deletable.push((label, bd));
683            }
684
685            if deletable.is_empty() {
686                continue;
687            }
688
689            // Enforce lockfile BEFORE any deletion (skipped in dry-run — analysis only)
690            if !dry_run {
691                let policy = crate::adapters::EnforcePolicy {
692                    allow_rewrite: opts.allow_manifest_rewrite,
693                    timeout: crate::adapters::command_timeout(opts.command_timeout_secs),
694                };
695                if let Err(e) = adapter.enforce_lockfile(&project.path, policy) {
696                    for (label, _) in &deletable {
697                        results.push(PruneResult {
698                            repo_path: repo_path.to_path_buf(),
699                            adapter_name: adapter.name().to_string(),
700                            bloat_dir: label.clone(),
701                            size_freed: 0,
702                            shared_bytes: 0,
703                            runtime: None,
704                            status: PruneStatus::LockfileError(e.to_string()),
705                        });
706                    }
707                    continue;
708                }
709            }
710
711            for (label, bd) in deletable {
712                if dry_run {
713                    results.push(PruneResult {
714                        repo_path: repo_path.to_path_buf(),
715                        adapter_name: adapter.name().to_string(),
716                        bloat_dir: label,
717                        size_freed: bd.size_bytes,
718                        shared_bytes: bd.shared_bytes,
719                        runtime: None,
720                        status: PruneStatus::SkippedDryRun,
721                    });
722                    continue;
723                }
724
725                // Asked *before* the delete: the record of which interpreter built a
726                // virtual environment lives inside the environment, so a moment later
727                // there is nothing left to ask.
728                let runtime = adapter.runtime_tag(&project.path, &bd.name);
729                results.push(delete_bloat(repo_path, adapter.name(), label, &bd, runtime));
730            }
731        }
732    }
733
734    results.extend(prune_declarations(
735        repo_path,
736        per_repo_config.as_ref(),
737        opts,
738        min_size_bytes,
739        only,
740        &mut claimed,
741    ));
742
743    // Nothing recognised, or recognised but nothing on disk to reclaim.
744    if results.is_empty() {
745        results.push(PruneResult {
746            repo_path: repo_path.to_path_buf(),
747            adapter_name: "-".to_string(),
748            bloat_dir: "-".to_string(),
749            size_freed: 0,
750            shared_bytes: 0,
751            runtime: None,
752            status: PruneStatus::NoBloat,
753        });
754    }
755
756    results
757}
758
759/// The refusals that apply to any directory, whoever nominated it.
760///
761/// Shared by the adapter loop, the declared-directory pass and `collect_bloat`, because
762/// the three of them disagreeing is exactly the bug this prevents: what `devp status`
763/// counts as reclaimable has to be what `devp run` actually deletes, and a directory
764/// declared by hand is no more deletable than one an adapter found.
765///
766/// `None` means nothing here stands in the way.
767fn shared_storage_refusal(path: &Path) -> Option<PruneStatus> {
768    // A symlinked/junctioned directory points at storage we do not own — in a monorepo
769    // it is usually the workspace root's real `node_modules`. Refuse rather than risk a
770    // recursive delete outside the repo.
771    if fs::symlink_metadata(path)
772        .map(|m| m.file_type().is_symlink())
773        .unwrap_or(false)
774    {
775        return Some(PruneStatus::SkippedSymlink(format!(
776            "`{}` is a symlink to storage dev-prune does not own — left alone. Remove \
777             the link yourself if you really want it gone.",
778            crate::output::clean_path(path)
779        )));
780    }
781
782    // A mount point is the same problem wearing different clothes: the name is inside
783    // the repository but the storage is somebody else's, and here there is no link to
784    // remove — unmounting is the only way out, which is a decision for whoever mounted
785    // it.
786    if is_mount_point(path) {
787        return Some(PruneStatus::SkippedSymlink(format!(
788            "`{}` is a mount point — it is on a different filesystem than the repository \
789             around it, so its contents are shared with whatever mounted it. Left alone.",
790            crate::output::clean_path(path)
791        )));
792    }
793
794    // Invariant 7 keeps the *walk* out of nested repositories, but the directory about
795    // to be deleted can hold one inside it — a `file:` dependency, a vendored checkout —
796    // with its own unpushed history. No lockfile rebuilds somebody else's git history,
797    // so refuse.
798    if let Some(nested) = find_nested_git(path) {
799        return Some(PruneStatus::SkippedNestedRepo(format!(
800            "`{}` contains a git repository at `{}` — refusing to delete it. Move or \
801             remove that checkout yourself if it holds nothing you need.",
802            crate::output::clean_path(path),
803            crate::output::clean_path(&nested)
804        )));
805    }
806
807    None
808}
809
810/// Delete one directory and report what happened, with one retry.
811fn delete_bloat(
812    repo_path: &Path,
813    adapter_name: &str,
814    label: String,
815    bd: &BloatDir,
816    runtime: Option<String>,
817) -> PruneResult {
818    let size = bd.size_bytes;
819    // `remove_dir_all` is not atomic: one locked file — an antivirus scan, an editor's
820    // file watcher — aborts it half-way, leaving a directory that is neither usable nor
821    // gone. Retry once after a beat, because such locks are usually released within
822    // moments of being hit — and a back-to-back retry lost the race to the very
823    // scanners it was meant to outwait.
824    let delete = fs::remove_dir_all(&bd.path).or_else(|_| {
825        std::thread::sleep(std::time::Duration::from_millis(250));
826        fs::remove_dir_all(&bd.path)
827    });
828    // "Not found" after a failed first attempt means the delete *did* complete — treat
829    // both the same.
830    let (size_freed, shared_bytes, status) = match delete {
831        Ok(()) => (size, bd.shared_bytes, PruneStatus::Pruned),
832        Err(_) if !bd.path.exists() => (size, bd.shared_bytes, PruneStatus::Pruned),
833        Err(e) => {
834            // Say what state the failure left behind. A half-deleted `node_modules` is
835            // corrupt whatever caused the abort, so the honest report is "no longer
836            // usable, rebuild it" — and the bytes already freed, so callers can record
837            // the partial pass and `devp restore` knows what to rebuild.
838            let remaining = crate::adapters::dir_size(&bd.path);
839            let freed = size.saturating_sub(remaining);
840            let message = if freed > 0 {
841                format!(
842                    "{e} — `{}` was partially deleted ({} of {} remains) and is no \
843                     longer usable. Close whatever holds it open, then run `devp \
844                     restore` to rebuild it.",
845                    crate::output::clean_path(&bd.path),
846                    crate::output::format_bytes(remaining),
847                    crate::output::format_bytes(size)
848                )
849            } else {
850                e.to_string()
851            };
852            (freed, 0, PruneStatus::DeleteError(message))
853        }
854    };
855    PruneResult {
856        repo_path: repo_path.to_path_buf(),
857        adapter_name: adapter_name.to_string(),
858        bloat_dir: label,
859        size_freed,
860        shared_bytes,
861        runtime,
862        status,
863    }
864}
865
866/// The directories this repository declared prunable, checked and then treated as bloat.
867///
868/// Runs after the adapters and shares their `claimed` set, so a project that declares
869/// something an adapter already found is not charged for it twice — and so the adapter's
870/// version, which has a lockfile behind it, is the one that wins.
871fn prune_declarations(
872    repo_path: &Path,
873    config: Option<&crate::config::PerRepoConfig>,
874    opts: &PruneOptions,
875    min_size_bytes: u64,
876    only: Option<&[String]>,
877    claimed: &mut std::collections::HashSet<PathBuf>,
878) -> Vec<PruneResult> {
879    let name = constants::DECLARED_ADAPTER_NAME;
880    if !opts.adapters.allows(name) {
881        return Vec::new();
882    }
883    let Some(declared) = config.and_then(|c| c.prunable.as_ref()) else {
884        return Vec::new();
885    };
886
887    let mut results = Vec::new();
888    for outcome in crate::declared::resolve(repo_path, declared) {
889        let target = match outcome {
890            crate::declared::Declaration::Prunable(target) => target,
891            // Printed even under `--only`, and even when the directory is below the
892            // size floor: a refusal means the repository asked for something dev-prune
893            // will not do, and silently doing nothing is how that stays unnoticed.
894            crate::declared::Declaration::Refused { label, reason } => {
895                results.push(PruneResult {
896                    repo_path: repo_path.to_path_buf(),
897                    adapter_name: name.to_string(),
898                    bloat_dir: label,
899                    size_freed: 0,
900                    shared_bytes: 0,
901                    runtime: None,
902                    status: PruneStatus::SkippedDeclaration(reason),
903                });
904                continue;
905            }
906        };
907
908        if only.is_some_and(|names| !names.contains(&target.label)) {
909            continue;
910        }
911        if target.size_bytes < min_size_bytes {
912            continue;
913        }
914        if !claimed.insert(target.path.clone()) {
915            continue;
916        }
917
918        let bd = BloatDir {
919            name: target.label.clone(),
920            path: target.path.clone(),
921            size_bytes: target.size_bytes,
922            shared_bytes: 0,
923        };
924        if let Some(status) = shared_storage_refusal(&bd.path) {
925            results.push(PruneResult {
926                repo_path: repo_path.to_path_buf(),
927                adapter_name: name.to_string(),
928                bloat_dir: target.label,
929                size_freed: 0,
930                shared_bytes: 0,
931                runtime: None,
932                status,
933            });
934            continue;
935        }
936        if opts.dry_run {
937            results.push(PruneResult {
938                repo_path: repo_path.to_path_buf(),
939                adapter_name: name.to_string(),
940                bloat_dir: target.label,
941                size_freed: target.size_bytes,
942                shared_bytes: 0,
943                runtime: None,
944                status: PruneStatus::SkippedDryRun,
945            });
946            continue;
947        }
948
949        // The rebuild command travels with the result the way an adapter's runtime tag
950        // does. It is the only record of how to put this directory back, and once the
951        // directory is gone the config file is the only place left holding it — which
952        // is no help at all to somebody reading a finished run report.
953        results.push(delete_bloat(
954            repo_path,
955            name,
956            target.label.clone(),
957            &bd,
958            Some(target.rebuild.clone()),
959        ));
960    }
961    results
962}
963
964/// Does `path` sit on a different filesystem from the directory that holds it?
965///
966/// Nothing inside a repository should: `node_modules` is an ordinary directory on the
967/// same volume as its parent. A mismatch means something was *mounted* there — a
968/// container's `-v shared_modules:/app/node_modules`, an NFS export, a bind mount
969/// pointing two checkouts at one cache — and what lives under it belongs to whoever
970/// set that up, not to this repository. A lockfile can rebuild this checkout's copy;
971/// it cannot rebuild the other consumers' copy, because there is only one copy.
972///
973/// Windows expresses the same idea as a reparse point, which the symlink refusal
974/// already catches, so this is a Unix-only check.
975#[cfg(unix)]
976fn is_mount_point(path: &Path) -> bool {
977    use std::os::unix::fs::MetadataExt;
978    let Some(parent) = path.parent() else {
979        return false;
980    };
981    match (fs::symlink_metadata(path), fs::symlink_metadata(parent)) {
982        (Ok(here), Ok(above)) => here.dev() != above.dev(),
983        // Unreadable is not evidence of a mount; the delete will fail on its own terms.
984        _ => false,
985    }
986}
987
988#[cfg(not(unix))]
989fn is_mount_point(_path: &Path) -> bool {
990    false
991}
992
993/// The first git repository found anywhere inside `dir`, if there is one.
994///
995/// `.git` as a directory is a full repository; as a file it is a submodule or worktree
996/// gitlink. Either way the history it anchors lives (at least partly) in the tree that
997/// is about to be deleted, and no lockfile can rebuild that.
998fn find_nested_git(dir: &Path) -> Option<PathBuf> {
999    walkdir::WalkDir::new(dir)
1000        .follow_links(false)
1001        .into_iter()
1002        .flatten()
1003        .find(|e| e.file_name() == ".git")
1004        .map(|e| e.into_path())
1005}
1006
1007/// Every bloat directory in a repository, across every nested project.
1008///
1009/// Returns the distinct adapter names in play alongside the deduplicated directories,
1010/// each labelled with its repository-relative path, and how many bytes each adapter
1011/// accounts for. Directories under `min_size_bytes` are omitted so that what `devp
1012/// status` reports as reclaimable is what `devp run` would actually offer to delete.
1013///
1014/// The per-adapter tally exists for the restore estimate: `node_modules` and `target`
1015/// come back at wildly different speeds, so a repository's total tells you nothing about
1016/// how long it takes to put back until it is split by who puts it back.
1017fn collect_bloat(
1018    repo_path: &Path,
1019    min_size_bytes: u64,
1020    depth: usize,
1021) -> (Vec<String>, Vec<BloatDir>, Vec<(String, u64)>) {
1022    let mut adapter_names: Vec<String> = Vec::new();
1023    let mut bloat: Vec<BloatDir> = Vec::new();
1024    let mut by_adapter: BTreeMap<String, u64> = BTreeMap::new();
1025    let mut claimed: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
1026
1027    for project in workspace::discover_to_depth(repo_path, depth) {
1028        for adapter in &project.adapters {
1029            let name = adapter.name();
1030            if !adapter_names.iter().any(|existing| existing == name) {
1031                adapter_names.push(name.to_string());
1032            }
1033            for bd in adapter.bloat_dirs(&project.path) {
1034                if bd.size_bytes < min_size_bytes {
1035                    continue;
1036                }
1037                // The same refusals the prune pass applies, for the same reason the
1038                // size floor is applied here: what `devp status` reports as reclaimable
1039                // must be what `devp run` would actually delete. A junctioned
1040                // `node_modules` even sizes somebody else's storage, so counting it
1041                // overstates the dashboard twice over.
1042                if shared_storage_refusal(&bd.path).is_some() {
1043                    continue;
1044                }
1045                if claimed.insert(bd.path.clone()) {
1046                    *by_adapter.entry(name.to_string()).or_default() += bd.size_bytes;
1047                    bloat.push(BloatDir {
1048                        name: workspace::relative_label(repo_path, &bd.path),
1049                        ..bd
1050                    });
1051                }
1052            }
1053        }
1054    }
1055
1056    // Declared directories count towards the dashboard exactly as adapter-found ones
1057    // do. A repository whose largest reclaimable tree is a declared one would otherwise
1058    // read as empty in `devp status` and then delete gigabytes in `devp run`.
1059    let declared = crate::config::PerRepoConfig::load_with_diagnostics(repo_path)
1060        .ok()
1061        .flatten()
1062        .and_then(|c| c.prunable)
1063        .unwrap_or_default();
1064    for outcome in crate::declared::resolve(repo_path, &declared) {
1065        let crate::declared::Declaration::Prunable(target) = outcome else {
1066            continue;
1067        };
1068        if target.size_bytes < min_size_bytes
1069            || shared_storage_refusal(&target.path).is_some()
1070            || !claimed.insert(target.path.clone())
1071        {
1072            continue;
1073        }
1074        let name = constants::DECLARED_ADAPTER_NAME;
1075        if !adapter_names.iter().any(|existing| existing == name) {
1076            adapter_names.push(name.to_string());
1077        }
1078        *by_adapter.entry(name.to_string()).or_default() += target.size_bytes;
1079        bloat.push(BloatDir {
1080            name: target.label,
1081            path: target.path,
1082            size_bytes: target.size_bytes,
1083            shared_bytes: 0,
1084        });
1085    }
1086
1087    (adapter_names, bloat, by_adapter.into_iter().collect())
1088}
1089
1090/// Run a prune pass across all registered repositories.
1091///
1092/// Each repository's own idle threshold applies; everything else in `opts` — the
1093/// adapter filter, the size floor, dry-run and force — is shared by the whole pass.
1094pub fn prune_all_with(registry: &mut Registry, opts: &PruneOptions) -> Vec<PruneResult> {
1095    let mut all_results = Vec::new();
1096
1097    // Collect paths first to avoid borrow issues.
1098    //
1099    // Sorted, because `repositories` is a HashMap: without this the output of two
1100    // identical runs lists the same repositories in a different order, which makes the
1101    // summary hard to read and the JSON document impossible to diff.
1102    let mut repos: Vec<(PathBuf, u64, bool)> = registry
1103        .repositories
1104        .iter()
1105        .map(|(path, entry)| {
1106            let idle_days = entry
1107                .override_idle_days
1108                .unwrap_or(registry.settings.idle_days);
1109            (path.clone(), idle_days, entry.enabled)
1110        })
1111        .collect();
1112    repos.sort_by(|a, b| a.0.cmp(&b.0));
1113
1114    for (path, idle_days, enabled) in repos {
1115        if !enabled {
1116            all_results.push(PruneResult {
1117                repo_path: path.clone(),
1118                adapter_name: "-".to_string(),
1119                bloat_dir: "-".to_string(),
1120                size_freed: 0,
1121                shared_bytes: 0,
1122                runtime: None,
1123                status: PruneStatus::Disabled,
1124            });
1125            continue;
1126        }
1127
1128        let results = prune_repo_with(
1129            &path,
1130            &PruneOptions {
1131                idle_days,
1132                ..opts.clone()
1133            },
1134        );
1135
1136        let path_freed: u64 = results
1137            .iter()
1138            .filter(|r| matches!(r.status, PruneStatus::Pruned))
1139            .map(|r| r.size_freed)
1140            .sum();
1141
1142        if path_freed > 0 {
1143            registry.mark_pruned(&path, path_freed);
1144        }
1145
1146        all_results.extend(results);
1147    }
1148
1149    all_results
1150}
1151
1152/// Run a prune pass across all registered repositories with default options.
1153pub fn prune_all(registry: &mut Registry, dry_run: bool, force: bool) -> Vec<PruneResult> {
1154    prune_all_with(registry, &PruneOptions::new(0, dry_run, force))
1155}
1156
1157/// Restore dependencies across every project in a tree.
1158///
1159/// Mirrors pruning: if `frontend/`, `services/api/` and `cli/` were each pruned, each is
1160/// restored by its own manager. The returned label is the adapter name for a project at
1161/// the root and `adapter (relative/path)` for a nested one.
1162///
1163/// Restore must reach at least as deep as the prune did. A repository configured to a
1164/// depth of 10 and pruned at 10, then restored at the default 6, comes back with its
1165/// deepest projects still empty — and nothing would have said so. `timeout` is the
1166/// user's `command_timeout_secs` for the same reason: a full reinstall is the longest
1167/// command this tool ever runs, and it used to be the only one that ignored the setting.
1168pub fn restore_project_to_depth(
1169    project_path: &Path,
1170    global_depth: usize,
1171    timeout: std::time::Duration,
1172) -> Result<Vec<(String, Result<()>)>> {
1173    let depth = workspace::resolve_depth(project_path, global_depth);
1174    let projects = workspace::discover_to_depth(project_path, depth);
1175
1176    if projects.is_empty() {
1177        anyhow::bail!(
1178            "No recognized package manager found in {}",
1179            project_path.display()
1180        );
1181    }
1182
1183    let mut results = Vec::new();
1184    for project in &projects {
1185        for adapter in &project.adapters {
1186            let label = if project.relative == "." {
1187                adapter.name().to_string()
1188            } else {
1189                format!("{} ({})", adapter.name(), project.relative)
1190            };
1191            results.push((label, adapter.restore(&project.path, timeout)));
1192        }
1193    }
1194
1195    Ok(results)
1196}
1197
1198/// The project directory that owns a bloat directory, as a repository-relative label.
1199///
1200/// Every adapter puts its bloat directory immediately inside the project it belongs to —
1201/// `node_modules`, `target`, `.venv`, `vendor` — so the owner is the label's parent.
1202/// `"node_modules"` belongs to the repository root, `"frontend/node_modules"` to
1203/// `frontend/`. Labels are `/`-separated on every platform; see
1204/// [`workspace::relative_label`].
1205fn owning_project(bloat_label: &str) -> &str {
1206    match bloat_label.rsplit_once('/') {
1207        Some((parent, _)) => parent,
1208        None => ".",
1209    }
1210}
1211
1212/// Restore exactly the projects a previous pass emptied, and nothing else.
1213///
1214/// `deleted` is the `(bloat directory label, adapter name)` pairs recorded at prune time.
1215/// [`restore_project_to_depth`] would reinstall every project in the tree; a repository
1216/// where one of five projects was pruned does not want the other four rebuilt, which on a
1217/// monorepo is the difference between one `npm ci` and five.
1218///
1219/// A recorded pair that no longer matches anything in the tree — the project was deleted,
1220/// renamed, or its manifest removed since the prune — comes back as an `Err` under its
1221/// own label rather than being dropped, because a restore that silently skips half its
1222/// work is the failure mode this whole command exists to avoid.
1223/// One recorded directory's restore: what was attempted, whether it worked, and what it
1224/// cost.
1225///
1226/// The cost is carried out of the engine rather than measured by the caller because this
1227/// is the only place that knows where one directory's rebuild starts and ends. A caller
1228/// timing the whole pass would learn the average of a `node_modules` and a `target`,
1229/// which is a number about nothing.
1230pub struct RestoreOutcome {
1231    /// `adapter (repo/relative/dir)`, as the command prints it.
1232    pub label: String,
1233    /// The adapter that owned the directory.
1234    pub adapter: String,
1235    /// Bytes the prune recorded for it — what this restore is putting back.
1236    pub bytes: u64,
1237    /// How long the rebuild took, successful or not.
1238    pub elapsed: std::time::Duration,
1239    /// Whether it worked.
1240    pub result: Result<()>,
1241}
1242
1243pub fn restore_deleted(
1244    repo_path: &Path,
1245    deleted: &[crate::config::PrunedDir],
1246    global_depth: usize,
1247    timeout: std::time::Duration,
1248) -> Vec<RestoreOutcome> {
1249    let depth = workspace::resolve_depth(repo_path, global_depth);
1250    let projects = workspace::discover_to_depth(repo_path, depth);
1251
1252    let mut results = Vec::new();
1253    for dir in deleted {
1254        let (bloat_label, adapter_name) = (&dir.bloat_dir, &dir.adapter);
1255        // Closure rather than a helper: it captures the record being restored, and the
1256        // three call sites below differ only in what they pass for `result`.
1257        let timed = |result: Result<()>, started: std::time::Instant| RestoreOutcome {
1258            label: format!("{adapter_name} ({bloat_label})"),
1259            adapter: adapter_name.clone(),
1260            bytes: dir.size_freed,
1261            elapsed: started.elapsed(),
1262            result,
1263        };
1264        let runtime = dir.runtime.as_deref();
1265        let wanted = owning_project(bloat_label);
1266        // The deleted directory's own name, so an adapter that supports several
1267        // (venv's `.venv`/`venv`/`my_env`) rebuilds the one that was actually there.
1268        let dir_name = bloat_label
1269            .rsplit_once('/')
1270            .map_or(bloat_label.as_str(), |(_, name)| name);
1271
1272        let found = projects
1273            .iter()
1274            .filter(|p| p.relative == wanted)
1275            .flat_map(|p| p.adapters.iter().map(move |a| (p, a)))
1276            .find(|(_, a)| a.name() == adapter_name);
1277
1278        if let Some((project, adapter)) = found {
1279            let started = std::time::Instant::now();
1280            let result = adapter.restore_named(&project.path, dir_name, runtime, timeout);
1281            results.push(timed(result, started));
1282            continue;
1283        }
1284
1285        // Re-detection can fail *because* the prune succeeded: deleting a virtual
1286        // environment removes the very `pyvenv.cfg` that venv detection looks for. The
1287        // recorded adapter passed detection and lockfile verification at prune time, so
1288        // when the project directory still exists, trust the record over a re-detect
1289        // that is looking at the hole the prune left.
1290        let project_dir = if wanted == "." {
1291            repo_path.to_path_buf()
1292        } else {
1293            repo_path.join(wanted)
1294        };
1295        let recorded = crate::adapters::get_all_adapters()
1296            .into_iter()
1297            .find(|a| a.name() == adapter_name);
1298        match recorded {
1299            Some(adapter) if project_dir.is_dir() => {
1300                let started = std::time::Instant::now();
1301                let result = adapter.restore_named(&project_dir, dir_name, runtime, timeout);
1302                results.push(timed(result, started));
1303            }
1304            _ => results.push(timed(
1305                Err(anyhow::anyhow!(
1306                    "`{wanted}` in {} is no longer a {adapter_name} project — it may have been \
1307                     moved or removed since the prune. Restore it by hand if it still exists.",
1308                    repo_path.display()
1309                )),
1310                std::time::Instant::now(),
1311            )),
1312        }
1313    }
1314
1315    results
1316}
1317
1318/// Reason why a repo was not selected as a prune candidate.
1319#[derive(Debug, Clone, PartialEq)]
1320pub enum SkipReason {
1321    /// Has pruneable bloat — this IS a candidate.
1322    Candidate,
1323    /// Repo has been active recently.
1324    Active,
1325    /// Opted out: either registry-disabled OR `ignore.devprune.json` file present OR `.devprune.json` ignore config.
1326    /// Both are treated identically.
1327    Ignored,
1328    /// No recognised package manager / bloat dirs found.
1329    NoBloat,
1330    /// Path no longer exists on disk.
1331    PathMissing,
1332    /// `.devprune.json` exists but does not parse, so nothing about this repo is known.
1333    ConfigError(String),
1334}
1335
1336impl std::fmt::Display for SkipReason {
1337    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1338        match self {
1339            SkipReason::Candidate => write!(f, "Candidate"),
1340            SkipReason::Active => write!(f, "Active (not idle)"),
1341            SkipReason::Ignored => write!(f, "Ignored"),
1342            SkipReason::NoBloat => write!(f, "No bloat found"),
1343            SkipReason::PathMissing => write!(f, "Path missing"),
1344            SkipReason::ConfigError(_) => write!(f, "Unreadable .devprune.json"),
1345        }
1346    }
1347}
1348
1349/// Full status entry for a single registered repository.
1350#[derive(Debug, Clone)]
1351pub struct RepoStatusEntry {
1352    /// Repository path.
1353    pub path: PathBuf,
1354    /// Registry metadata.
1355    pub entry: RepoEntry,
1356    /// Why this repo was/wasn't selected as a prune candidate.
1357    pub reason: SkipReason,
1358    /// Adapter names detected (e.g. ["npm", "uv"]).
1359    pub adapters: Vec<String>,
1360    /// Bloat directories and sizes (empty if not a candidate).
1361    pub bloat_dirs: Vec<BloatDir>,
1362    /// Total reclaimable bytes.
1363    pub reclaimable_bytes: u64,
1364    /// Reclaimable bytes split by the adapter that would have to put them back, sorted
1365    /// by adapter name. Empty whenever `bloat_dirs` is.
1366    pub reclaimable_by_adapter: Vec<(String, u64)>,
1367    /// Last git/file-system activity time.
1368    pub last_activity: Option<DateTime<Utc>>,
1369    /// Idle threshold that applies to this repo (days).
1370    pub idle_days: u64,
1371}
1372
1373/// Compute full status for ALL registered repositories.
1374///
1375/// Unlike `get_space_summary`, this includes every repo — active, disabled,
1376/// ignored, or missing — with a human-readable reason for each.
1377/// Everything `status` needs to say about one registered repository.
1378///
1379/// Split out of [`get_full_status`] so the scan can run several at once; it reads the
1380/// registry and the file system and writes nothing, which is what makes that safe.
1381fn status_for_repo(registry: &Registry, path: &Path, reg_entry: &RepoEntry) -> RepoStatusEntry {
1382    let registry_idle_days = reg_entry
1383        .override_idle_days
1384        .unwrap_or(registry.settings.idle_days);
1385
1386    // Path missing? Checked before the config is read, because a directory that is
1387    // gone has no config to read.
1388    if !path.exists() {
1389        return RepoStatusEntry {
1390            path: path.to_path_buf(),
1391            entry: reg_entry.clone(),
1392            reason: SkipReason::PathMissing,
1393            adapters: Vec::new(),
1394            bloat_dirs: Vec::new(),
1395            reclaimable_by_adapter: Vec::new(),
1396            reclaimable_bytes: 0,
1397            last_activity: None,
1398            idle_days: registry_idle_days,
1399        };
1400    }
1401
1402    // The same refusal-to-guess the prune pass makes. Reading this with
1403    // `load_from_repo` treated a broken file as "no config", so a repo that
1404    // `devp run` would refuse to touch showed up in the dashboard as a healthy
1405    // candidate with a reclaimable size next to it.
1406    let per_repo_config = match crate::config::PerRepoConfig::load_with_diagnostics(path) {
1407        Ok(cfg) => cfg,
1408        Err(e) => {
1409            return RepoStatusEntry {
1410                path: path.to_path_buf(),
1411                entry: reg_entry.clone(),
1412                reason: SkipReason::ConfigError(e),
1413                adapters: Vec::new(),
1414                bloat_dirs: Vec::new(),
1415                reclaimable_by_adapter: Vec::new(),
1416                reclaimable_bytes: 0,
1417                last_activity: last_activity_time(path),
1418                idle_days: registry_idle_days,
1419            };
1420        }
1421    };
1422    let idle_days = per_repo_config
1423        .as_ref()
1424        .and_then(|c| c.override_idle_days)
1425        .unwrap_or(registry_idle_days);
1426
1427    // Disabled in registry, ignore.devprune.json present, OR .devprune.json ignore=true
1428    let is_ignored = !reg_entry.enabled
1429        || path.join(constants::DEVPRUNE_IGNORE_FILE).exists()
1430        || per_repo_config.as_ref().map(|c| c.ignore).unwrap_or(false);
1431    if is_ignored {
1432        return RepoStatusEntry {
1433            path: path.to_path_buf(),
1434            entry: reg_entry.clone(),
1435            reason: SkipReason::Ignored,
1436            adapters: Vec::new(),
1437            bloat_dirs: Vec::new(),
1438            reclaimable_by_adapter: Vec::new(),
1439            reclaimable_bytes: 0,
1440            last_activity: last_activity_time(path),
1441            idle_days,
1442        };
1443    }
1444
1445    // Activity check. One computation drives both the column and the decision —
1446    // they used to be computed separately, from different rules, so a repo with
1447    // uncommitted edits was correctly held back as "Active" while the column next
1448    // to it showed the last *commit*, months earlier.
1449    let activity = git::get_last_activity(path).ok().flatten();
1450    let activity_time = to_utc(activity);
1451    let is_idle = git::is_idle_at(activity, idle_days);
1452
1453    // Detect adapters & bloat across every project in the repository
1454    let min_size_bytes = per_repo_config
1455        .as_ref()
1456        .and_then(|c| c.min_size_mb)
1457        .unwrap_or(registry.settings.min_size_mb)
1458        .saturating_mul(BYTES_PER_MIB);
1459    // Same resolution order as the size floor just above: the repository's own
1460    // config first, the global setting otherwise. The dashboard and a run must walk
1461    // to the same depth or `status` will list projects `run` never sees.
1462    let depth = workspace::clamp_depth(
1463        per_repo_config
1464            .as_ref()
1465            .and_then(|c| c.scan_depth)
1466            .unwrap_or(registry.settings.scan_depth),
1467    );
1468    let (adapter_names, all_bloat, by_adapter) = collect_bloat(path, min_size_bytes, depth);
1469    let reclaimable: u64 = all_bloat.iter().map(|b| b.size_bytes).sum();
1470
1471    // A repository idle past its own threshold can still be entirely held back by
1472    // adapter windows — `build_idle_days` for the opt-in build adapters, or an
1473    // `adapter_idle_days` entry. The dashboard used to call that a Candidate while a
1474    // run touched nothing. No new SkipReason: being held by a longer window *is*
1475    // being active, just against a higher bar — so the entry reports Active with
1476    // `idle_days` raised to the lowest window still unmet, which is the threshold
1477    // that actually decides this repository. A partial hold stays Candidate, because
1478    // a run would still prune the adapters whose window is met.
1479    let opt_in_names = crate::adapters::opt_in_adapter_names();
1480    let lowest_unmet_window = (is_idle && !by_adapter.is_empty())
1481        .then(|| {
1482            by_adapter
1483                .iter()
1484                .map(|(name, _)| {
1485                    let threshold = adapter_idle_threshold(
1486                        name,
1487                        opt_in_names.contains(&name.as_str()),
1488                        idle_days,
1489                        registry.settings.build_idle_days,
1490                        &registry.settings.adapter_idle_days,
1491                    );
1492                    (!git::is_idle_at(activity, threshold)).then_some(threshold)
1493                })
1494                .collect::<Option<Vec<u64>>>()
1495                .and_then(|unmet| unmet.into_iter().min())
1496        })
1497        .flatten();
1498
1499    let reason = if !is_idle || lowest_unmet_window.is_some() {
1500        SkipReason::Active
1501    } else if all_bloat.is_empty() {
1502        SkipReason::NoBloat
1503    } else {
1504        SkipReason::Candidate
1505    };
1506
1507    RepoStatusEntry {
1508        path: path.to_path_buf(),
1509        entry: reg_entry.clone(),
1510        reason,
1511        adapters: adapter_names,
1512        bloat_dirs: all_bloat,
1513        reclaimable_bytes: reclaimable,
1514        reclaimable_by_adapter: by_adapter,
1515        last_activity: activity_time,
1516        idle_days: lowest_unmet_window.unwrap_or(idle_days),
1517    }
1518}
1519
1520/// How many threads the status scan should use for `total` repositories.
1521///
1522/// Each repository is an independent read of the file system and the pass is bound by
1523/// I/O, not by the CPU — so oversubscribing the cores still helps, up to the point where
1524/// the disk becomes the queue rather than the processor. The multiplier is the ramp:
1525/// a machine that reports more parallelism gets proportionally more, and the ceiling
1526/// stops a 64-core box from starting more threads than any disk can usefully serve.
1527///
1528/// Never more threads than there are repositories: a registry of three should not start
1529/// thirty-two of them to do nothing. Never fewer than one, because the calling thread is
1530/// itself the first worker.
1531///
1532/// [`constants::STATUS_SCAN_THREADS_ENV`] overrides the whole calculation, clamped the
1533/// same way — the escape hatch for a machine where the guess is wrong in either
1534/// direction: a network filesystem that wants far more requests in flight, or a spinning
1535/// disk that is fastest with one.
1536fn scan_thread_count(total: usize) -> usize {
1537    let requested = std::env::var(constants::STATUS_SCAN_THREADS_ENV)
1538        .ok()
1539        .and_then(|v| v.trim().parse::<usize>().ok())
1540        .filter(|n| *n > 0)
1541        .unwrap_or_else(|| {
1542            std::thread::available_parallelism()
1543                .map(std::num::NonZeroUsize::get)
1544                .unwrap_or(4)
1545                .saturating_mul(constants::STATUS_SCAN_THREADS_PER_CORE)
1546        });
1547    clamp_scan_threads(requested, total)
1548}
1549
1550/// The clamping half of [`scan_thread_count`], without the environment read, so the
1551/// bounds can be tested without mutating process-wide state.
1552fn clamp_scan_threads(requested: usize, total: usize) -> usize {
1553    requested
1554        .clamp(1, constants::STATUS_SCAN_MAX_THREADS)
1555        .min(total.max(1))
1556}
1557
1558pub fn get_full_status(registry: &Registry) -> Vec<RepoStatusEntry> {
1559    get_full_status_reporting(registry, &|_done, _total| {})
1560}
1561
1562/// [`get_full_status`], reporting each repository as it finishes.
1563///
1564/// The scan is dominated by `collect_bloat`, which walks and sizes every dependency tree
1565/// it finds; on a registry of eighty repositories that was half a minute of silence
1566/// before anything appeared. The callback is what lets `devp status` draw a progress bar
1567/// over it instead — a dashboard that looks hung is one people kill before it renders.
1568///
1569/// The callback is invoked from several threads at once, and its first argument is the
1570/// number of repositories finished, not the index of this one: workers finish out of
1571/// order.
1572pub fn get_full_status_reporting(
1573    registry: &Registry,
1574    progress: &(dyn Fn(usize, usize) + Sync),
1575) -> Vec<RepoStatusEntry> {
1576    use std::sync::atomic::{AtomicUsize, Ordering};
1577
1578    let repos: Vec<(&PathBuf, &RepoEntry)> = registry.repositories.iter().collect();
1579    let total = repos.len();
1580    let workers = scan_thread_count(total);
1581
1582    // Work-stealing off a shared cursor rather than a fixed slice per thread, because the
1583    // cost per repository varies by orders of magnitude — one repository in a real
1584    // registry held a 2 GiB virtualenv while thirty others held nothing at all. A static
1585    // split leaves every other thread idle waiting for whichever one drew that repo.
1586    let next = AtomicUsize::new(0);
1587    let done = AtomicUsize::new(0);
1588
1589    let take_work = || {
1590        let mut mine = Vec::new();
1591        loop {
1592            let i = next.fetch_add(1, Ordering::Relaxed);
1593            if i >= total {
1594                break;
1595            }
1596            let (path, reg_entry) = repos[i];
1597            mine.push(status_for_repo(registry, path, reg_entry));
1598            progress(done.fetch_add(1, Ordering::Relaxed) + 1, total);
1599        }
1600        mine
1601    };
1602
1603    let chunks: Vec<Vec<RepoStatusEntry>> = std::thread::scope(|scope| {
1604        // `Builder::spawn_scoped` rather than `scope.spawn`, which panics when the OS
1605        // refuses a thread — under a low `ulimit -u`, in a constrained container, on a
1606        // machine already at its process limit. Refusing to draw a dashboard because the
1607        // system was busy is not an acceptable outcome, so a refusal here just means
1608        // fewer workers: whatever did start keeps pulling off the same cursor, and the
1609        // calling thread below is always one of them. In the worst case — nothing at all
1610        // would start — the scan runs single-threaded and still finishes.
1611        let mut handles = Vec::with_capacity(workers.saturating_sub(1));
1612        for n in 1..workers {
1613            match std::thread::Builder::new()
1614                .name(format!("devp-scan-{n}"))
1615                .spawn_scoped(scope, take_work)
1616            {
1617                Ok(handle) => handles.push(handle),
1618                Err(_) => break,
1619            }
1620        }
1621
1622        // The calling thread is a worker too, not a supervisor waiting on them. That is
1623        // what makes zero spawned threads a slow scan rather than a hung one.
1624        let mut chunks = vec![take_work()];
1625        chunks.extend(
1626            handles
1627                .into_iter()
1628                // A panicking worker takes the whole scan down with it. A dashboard for a
1629                // tool that deletes things must never quietly return a short list.
1630                .map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))),
1631        );
1632        chunks
1633    });
1634
1635    let mut entries: Vec<RepoStatusEntry> = chunks.into_iter().flatten().collect();
1636
1637    // Sort: what you can act on, then what is merely there, then what is gone — and by
1638    // path within each band. Path order alone put thirty-four dead entries at the top of
1639    // one dashboard, because `C:\Users\…\Temp` sorts before `V:\Code`, and the rows
1640    // that mattered started below the fold.
1641    fn rank(reason: &SkipReason) -> u8 {
1642        match reason {
1643            SkipReason::Candidate => 0,
1644            SkipReason::PathMissing => 2,
1645            _ => 1,
1646        }
1647    }
1648    entries.sort_by(|a, b| {
1649        rank(&a.reason)
1650            .cmp(&rank(&b.reason))
1651            .then_with(|| a.path.cmp(&b.path))
1652    });
1653
1654    entries
1655}
1656
1657/// The `n` repositories with the most reclaimable space, or all of them when `top` is
1658/// `None`.
1659///
1660/// `devp status` lists every registered repository, which on a machine tracking a hundred
1661/// of them pushes the handful actually worth pruning off the screen. Selection is by
1662/// reclaimable bytes, descending; the survivors are then put back into the order
1663/// [`get_full_status`] produced, so a truncated dashboard reads like a shorter version of
1664/// the full one rather than a differently-sorted one.
1665pub fn take_top(repos: &[RepoStatusEntry], top: Option<usize>) -> Vec<RepoStatusEntry> {
1666    let Some(n) = top else {
1667        return repos.to_vec();
1668    };
1669
1670    let mut ranked: Vec<usize> = (0..repos.len()).collect();
1671    ranked.sort_by_key(|&i| std::cmp::Reverse(repos[i].reclaimable_bytes));
1672    ranked.truncate(n);
1673    ranked.sort_unstable();
1674    ranked.into_iter().map(|i| repos[i].clone()).collect()
1675}
1676
1677/// Compute crisp, disambiguated project names for a repository path.
1678///
1679/// Uses `.devprune.json` custom `project_name` if present. Otherwise defaults to folder name.
1680/// If multiple repositories share the exact same folder name, disambiguates by including parent folder.
1681pub fn compute_display_name(repo_path: &Path, all_paths: &[PathBuf]) -> String {
1682    // A label, so a config that does not parse just falls through to the folder name —
1683    // the states that matter are reported by the caller.
1684    if let Some(cfg) = crate::config::PerRepoConfig::load_with_diagnostics(repo_path)
1685        .ok()
1686        .flatten()
1687        && let Some(custom) = cfg.project_name
1688        && !custom.trim().is_empty()
1689    {
1690        return custom;
1691    }
1692
1693    let folder_name = repo_path
1694        .file_name()
1695        .map(|n| n.to_string_lossy().to_string())
1696        .unwrap_or_else(|| crate::output::clean_path(repo_path));
1697
1698    // Check if duplicate folder names exist
1699    let duplicate_count = all_paths
1700        .iter()
1701        .filter(|p| {
1702            p.file_name()
1703                .map(|n| n.to_string_lossy().to_string())
1704                .as_deref()
1705                == Some(&folder_name)
1706        })
1707        .count();
1708
1709    if duplicate_count > 1
1710        && let Some(parent) = repo_path.parent()
1711        && let Some(parent_name) = parent.file_name()
1712    {
1713        return format!("{}/{}", parent_name.to_string_lossy(), folder_name);
1714    }
1715
1716    folder_name
1717}
1718
1719/// Best-effort last activity time for a repo: the later of its last commit and the
1720/// newest source file mtime, which is the same value the idle check uses.
1721fn last_activity_time(path: &Path) -> Option<DateTime<Utc>> {
1722    to_utc(git::get_last_activity(path).ok().flatten())
1723}
1724
1725/// A `SystemTime` as the UTC timestamp the status entries carry.
1726fn to_utc(system_time: Option<SystemTime>) -> Option<DateTime<Utc>> {
1727    system_time.map(|st| {
1728        let duration = st
1729            .duration_since(SystemTime::UNIX_EPOCH)
1730            .unwrap_or_default();
1731        DateTime::from_timestamp(duration.as_secs() as i64, 0).unwrap_or_default()
1732    })
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737    use super::*;
1738    use std::fs;
1739    use std::process::Command;
1740    use tempfile::TempDir;
1741
1742    /// Restore in these tests either fails before running anything or runs against an
1743    /// empty project; none of them should ever sit anywhere near this long.
1744    const TEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
1745
1746    #[test]
1747    fn an_ordinary_directory_is_not_a_mount_point() {
1748        // The check has to be silent on the only case that ever really happens; a real
1749        // mount cannot be created in a test without root, so this pins the negative.
1750        let tmp = TempDir::new().unwrap();
1751        let dir = tmp.path().join("node_modules");
1752        fs::create_dir_all(&dir).unwrap();
1753        assert!(!is_mount_point(&dir));
1754    }
1755
1756    #[test]
1757    fn a_filesystem_root_is_not_reported_as_a_mount_point() {
1758        // `/` has no parent, so the comparison has nothing to compare against. It must
1759        // answer "no" rather than panic on the `None`.
1760        let root = Path::new(std::path::MAIN_SEPARATOR_STR);
1761        assert!(!is_mount_point(root));
1762    }
1763
1764    fn create_git_repo_with_commit(path: &Path) {
1765        fs::create_dir_all(path).unwrap();
1766        Command::new("git")
1767            .args(["init"])
1768            .current_dir(path)
1769            .output()
1770            .unwrap();
1771        fs::write(path.join("README.md"), "# Test").unwrap();
1772        Command::new("git")
1773            .args(["add", "."])
1774            .current_dir(path)
1775            .output()
1776            .unwrap();
1777        Command::new("git")
1778            .args([
1779                "-c",
1780                "user.name=Test",
1781                "-c",
1782                "user.email=test@test.com",
1783                "commit",
1784                "-m",
1785                "initial",
1786            ])
1787            .current_dir(path)
1788            .output()
1789            .unwrap();
1790    }
1791
1792    #[test]
1793    fn a_bloat_label_names_the_project_that_owns_it() {
1794        assert_eq!(owning_project("node_modules"), ".");
1795        assert_eq!(owning_project("frontend/node_modules"), "frontend");
1796        assert_eq!(
1797            owning_project("packages/@scope/app/.venv"),
1798            "packages/@scope/app"
1799        );
1800    }
1801
1802    #[test]
1803    fn restore_deleted_touches_only_the_projects_that_were_pruned() {
1804        // Two npm projects, one of which was pruned. Restoring the whole tree would
1805        // reinstall both; only the recorded one may be attempted.
1806        let tmp = TempDir::new().unwrap();
1807        let root = tmp.path();
1808        for name in ["frontend", "docs"] {
1809            let dir = root.join(name);
1810            fs::create_dir_all(&dir).unwrap();
1811            fs::write(dir.join("package.json"), "{}").unwrap();
1812            fs::write(dir.join("package-lock.json"), "{}").unwrap();
1813        }
1814
1815        let deleted = vec![crate::config::PrunedDir {
1816            repo_path: root.to_path_buf(),
1817            bloat_dir: "frontend/node_modules".to_string(),
1818            adapter: "npm".to_string(),
1819            size_freed: 0,
1820            runtime: None,
1821        }];
1822        let results = restore_deleted(root, &deleted, 4, TEST_TIMEOUT);
1823
1824        assert_eq!(results.len(), 1, "one recorded directory, one attempt");
1825        assert_eq!(results[0].label, "npm (frontend/node_modules)");
1826    }
1827
1828    #[test]
1829    fn restore_deleted_reports_a_project_that_is_no_longer_there() {
1830        // Recorded at prune time, gone by restore time. Reported, never dropped: a
1831        // restore that quietly skips half its work is the failure this command prevents.
1832        let tmp = TempDir::new().unwrap();
1833        let deleted = vec![crate::config::PrunedDir {
1834            repo_path: tmp.path().to_path_buf(),
1835            bloat_dir: "services/api/.venv".to_string(),
1836            adapter: "uv".to_string(),
1837            size_freed: 0,
1838            runtime: None,
1839        }];
1840        let results = restore_deleted(tmp.path(), &deleted, 4, TEST_TIMEOUT);
1841
1842        assert_eq!(results.len(), 1);
1843        assert_eq!(results[0].label, "uv (services/api/.venv)");
1844        let err = results[0].result.as_ref().unwrap_err().to_string();
1845        assert!(err.contains("services/api"), "names the missing project");
1846        assert!(err.contains("uv"), "names the adapter that owned it");
1847    }
1848
1849    #[test]
1850    fn test_prune_status_display() {
1851        assert_eq!(PruneStatus::Pruned.to_string(), "Pruned");
1852        assert_eq!(PruneStatus::SkippedActive.to_string(), "Skipped (active)");
1853        assert_eq!(PruneStatus::SkippedDryRun.to_string(), "Skipped (dry run)");
1854        assert_eq!(
1855            PruneStatus::SkippedAdapterWindow(45).to_string(),
1856            "Not examined (adapter idle window: 45 days)"
1857        );
1858    }
1859
1860    #[test]
1861    fn test_prune_repo_non_git() {
1862        // A directory that is not a git repository produces a visible error line, not
1863        // silence — an empty result reads as "handled" in the run report.
1864        let tmp = TempDir::new().unwrap();
1865        let results = prune_repo(tmp.path(), 15, false, false);
1866        assert_eq!(results.len(), 1);
1867        assert!(matches!(results[0].status, PruneStatus::NotARepo));
1868    }
1869
1870    #[test]
1871    fn test_prune_repo_active_skipped() {
1872        let tmp = TempDir::new().unwrap();
1873        let repo = tmp.path().join("repo");
1874        create_git_repo_with_commit(&repo);
1875        // Just committed — active
1876        let results = prune_repo(&repo, 15, false, false);
1877        assert_eq!(results.len(), 1);
1878        assert!(matches!(results[0].status, PruneStatus::SkippedActive));
1879    }
1880
1881    /// An unreadable `.devprune.json` must never fall back to defaults: the file may have
1882    /// said `"ignore": true`, and guessing would delete from a repo that opted out.
1883    #[test]
1884    fn test_unparseable_per_repo_config_skips_the_repo() {
1885        let tmp = TempDir::new().unwrap();
1886        let repo = tmp.path().join("repo");
1887        create_git_repo_with_commit(&repo);
1888        fs::create_dir(repo.join("target")).unwrap();
1889        fs::write(repo.join("target").join("dummy"), "data").unwrap();
1890        fs::write(
1891            repo.join("Cargo.toml"),
1892            "[package]\nname = \"t\"\nversion = \"0.1.0\"",
1893        )
1894        .unwrap();
1895        fs::write(repo.join("Cargo.lock"), "# lockfile").unwrap();
1896        // Trailing comma — valid-looking, but not valid JSON.
1897        fs::write(repo.join(".devprune.json"), "{ \"ignore\": true, }").unwrap();
1898
1899        // Forced, non-dry-run: everything else would have this repo pruned.
1900        let results = prune_repo(&repo, 15, false, true);
1901
1902        assert_eq!(results.len(), 1);
1903        assert!(
1904            matches!(results[0].status, PruneStatus::ConfigError(_)),
1905            "expected ConfigError, got {:?}",
1906            results[0].status
1907        );
1908        assert!(repo.join("target").exists(), "target must survive");
1909    }
1910
1911    /// The dashboard and the prune pass have to agree about a broken config file.
1912    /// Reporting it as a healthy candidate with a size next to it invites the user to
1913    /// select a repository that `devp run` will then refuse to touch.
1914    #[test]
1915    fn a_broken_config_is_reported_by_status_and_not_as_a_candidate() {
1916        let tmp = TempDir::new().unwrap();
1917        let repo = tmp.path().join("repo");
1918        create_git_repo_with_commit(&repo);
1919        create_python_project(&repo);
1920        fs::write(repo.join(".devprune.json"), "{ \"ignore\": true, }").unwrap();
1921
1922        let mut registry = Registry::default();
1923        registry.add_repo(repo.clone());
1924
1925        let entries = get_full_status(&registry);
1926        assert_eq!(entries.len(), 1);
1927        assert!(
1928            matches!(entries[0].reason, SkipReason::ConfigError(_)),
1929            "expected ConfigError, got {:?}",
1930            entries[0].reason
1931        );
1932        assert_eq!(entries[0].reclaimable_bytes, 0);
1933    }
1934
1935    #[test]
1936    fn test_prune_repo_dry_run() {
1937        let tmp = TempDir::new().unwrap();
1938        let repo = tmp.path().join("repo");
1939        create_git_repo_with_commit(&repo);
1940        // Go rather than Cargo: `target/` belongs to an opt-in adapter now, and a
1941        // fixture nothing detects would make this test pass for the wrong reason.
1942        create_go_project(&repo);
1943        // Force + dry run → should report what WOULD be pruned
1944        let results = prune_repo(&repo, 15, true, true);
1945        let dry_run_results: Vec<_> = results
1946            .iter()
1947            .filter(|r| matches!(r.status, PruneStatus::SkippedDryRun))
1948            .collect();
1949        assert!(!dry_run_results.is_empty());
1950        // vendor should still exist
1951        assert!(repo.join("vendor").exists());
1952    }
1953
1954    #[test]
1955    fn an_unmet_adapter_window_reports_one_row_per_adapter_not_one_per_project() {
1956        let tmp = TempDir::new().unwrap();
1957        let repo = tmp.path().join("repo");
1958        create_git_repo_with_commit(&repo);
1959        // Two go projects, one window: the gate fires per project, the report must
1960        // not repeat itself.
1961        create_go_project(&repo);
1962        create_go_project(&repo.join("sub"));
1963
1964        // Base threshold 0: a just-committed repository already counts as idle, so
1965        // the pass reaches the per-adapter gate — where go's pinned 10 000-day window
1966        // is unmet and nothing behind it may even be looked at.
1967        let mut opts = PruneOptions::new(0, true, false);
1968        opts.adapter_idle_days.insert("go".to_string(), 10_000);
1969        let results = prune_repo_with(&repo, &opts);
1970
1971        let windows: Vec<_> = results
1972            .iter()
1973            .filter(|r| matches!(r.status, PruneStatus::SkippedAdapterWindow(_)))
1974            .collect();
1975        assert_eq!(windows.len(), 1, "{results:?}");
1976        assert_eq!(windows[0].adapter_name, "go");
1977        assert!(matches!(
1978            windows[0].status,
1979            PruneStatus::SkippedAdapterWindow(10_000)
1980        ));
1981        assert!(
1982            !results
1983                .iter()
1984                .any(|r| matches!(r.status, PruneStatus::SkippedDryRun)),
1985            "a held adapter must not also report candidates: {results:?}"
1986        );
1987    }
1988
1989    /// A Python project with a populated `requirements.txt` and a virtual environment.
1990    ///
1991    /// The venv adapter verifies its lockfile by reading files rather than by shelling
1992    /// out, so it is the one ecosystem that can be pruned for real inside a test.
1993    fn create_python_project(dir: &Path) {
1994        fs::create_dir_all(dir).unwrap();
1995        fs::write(dir.join("requirements.txt"), "requests==2.32.3\n").unwrap();
1996        let venv = dir.join(".venv");
1997        fs::create_dir_all(&venv).unwrap();
1998        fs::write(venv.join("pyvenv.cfg"), "home = /usr\n").unwrap();
1999        fs::write(venv.join("payload.bin"), vec![0u8; 4096]).unwrap();
2000    }
2001
2002    /// A Go module with a vendored dependency tree.
2003    ///
2004    /// `modules.txt` is not decoration: the adapter refuses a `vendor/` without it,
2005    /// because only a `go mod vendor` product carries one.
2006    fn create_go_project(dir: &Path) {
2007        fs::create_dir_all(dir).unwrap();
2008        fs::write(dir.join("go.mod"), "module example.com/x\n\ngo 1.22\n").unwrap();
2009        fs::write(dir.join("go.sum"), "").unwrap();
2010        let vendor = dir.join("vendor");
2011        fs::create_dir_all(&vendor).unwrap();
2012        fs::write(vendor.join("modules.txt"), "# example.com/dep v1.0.0\n").unwrap();
2013        fs::write(vendor.join("payload.bin"), vec![0u8; 4096]).unwrap();
2014    }
2015
2016    /// The `bloat_dir` labels of every result, sorted.
2017    fn labels(results: &[PruneResult]) -> Vec<String> {
2018        let mut out: Vec<String> = results.iter().map(|r| r.bloat_dir.clone()).collect();
2019        out.sort();
2020        out
2021    }
2022
2023    #[test]
2024    fn test_prune_finds_several_ecosystems_at_the_repo_root() {
2025        let tmp = TempDir::new().unwrap();
2026        let repo = tmp.path().join("repo");
2027        create_git_repo_with_commit(&repo);
2028
2029        create_go_project(&repo);
2030        fs::write(repo.join("package.json"), "{}").unwrap();
2031        fs::write(repo.join("package-lock.json"), "{}").unwrap();
2032        fs::create_dir(repo.join("node_modules")).unwrap();
2033        create_python_project(&repo);
2034
2035        let results = prune_repo(&repo, 15, true, true);
2036        assert_eq!(labels(&results), vec![".venv", "node_modules", "vendor"]);
2037    }
2038
2039    #[test]
2040    fn test_prune_finds_ecosystems_at_different_depths() {
2041        let tmp = TempDir::new().unwrap();
2042        let repo = tmp.path().join("repo");
2043        create_git_repo_with_commit(&repo);
2044
2045        fs::create_dir_all(repo.join("frontend")).unwrap();
2046        fs::write(repo.join("frontend/package.json"), "{}").unwrap();
2047        fs::write(repo.join("frontend/pnpm-lock.yaml"), "").unwrap();
2048        fs::create_dir(repo.join("frontend/node_modules")).unwrap();
2049
2050        create_go_project(&repo.join("tools/cli"));
2051
2052        create_python_project(&repo.join("services/api"));
2053
2054        let results = prune_repo(&repo, 15, true, true);
2055        assert_eq!(
2056            labels(&results),
2057            vec![
2058                "frontend/node_modules",
2059                "services/api/.venv",
2060                "tools/cli/vendor",
2061            ]
2062        );
2063    }
2064
2065    #[test]
2066    fn test_prune_deletes_only_the_selected_nested_directory() {
2067        let tmp = TempDir::new().unwrap();
2068        let repo = tmp.path().join("repo");
2069        create_git_repo_with_commit(&repo);
2070        create_python_project(&repo.join("a"));
2071        create_python_project(&repo.join("b"));
2072
2073        let results = prune_repo_selected(&repo, 0, false, true, Some(&["a/.venv".to_string()]));
2074
2075        assert_eq!(labels(&results), vec!["a/.venv"]);
2076        assert!(matches!(results[0].status, PruneStatus::Pruned));
2077        assert!(!repo.join("a/.venv").exists());
2078        assert!(repo.join("b/.venv").exists());
2079    }
2080
2081    #[test]
2082    fn test_prune_ignores_bloat_inside_a_nested_repository() {
2083        let tmp = TempDir::new().unwrap();
2084        let repo = tmp.path().join("repo");
2085        create_git_repo_with_commit(&repo);
2086        create_python_project(&repo.join("outer"));
2087
2088        // A submodule is its own repository with its own activity history — pruning it
2089        // as part of the parent would ignore that.
2090        let nested = repo.join("nested");
2091        create_git_repo_with_commit(&nested);
2092        create_python_project(&nested);
2093
2094        let results = prune_repo(&repo, 15, true, true);
2095        assert_eq!(labels(&results), vec!["outer/.venv"]);
2096    }
2097
2098    #[test]
2099    fn test_prune_repo_no_adapters() {
2100        let tmp = TempDir::new().unwrap();
2101        let repo = tmp.path().join("repo");
2102        create_git_repo_with_commit(&repo);
2103        // Force prune but no package manager files
2104        let results = prune_repo(&repo, 15, false, true);
2105        assert!(
2106            results
2107                .iter()
2108                .any(|r| matches!(r.status, PruneStatus::NoBloat))
2109        );
2110    }
2111
2112    #[test]
2113    fn test_prune_all_disabled() {
2114        let tmp = TempDir::new().unwrap();
2115        let _registry_path = tmp.path().join("registry.json");
2116
2117        let mut registry = Registry::default();
2118        let repo_path = PathBuf::from("/nonexistent/repo");
2119        registry.add_repo(repo_path.clone());
2120        registry.repositories.get_mut(&repo_path).unwrap().enabled = false;
2121
2122        let results = prune_all(&mut registry, false, false);
2123        assert!(
2124            results
2125                .iter()
2126                .any(|r| matches!(r.status, PruneStatus::Disabled))
2127        );
2128    }
2129
2130    #[test]
2131    fn test_restore_project_no_adapters() {
2132        let tmp = TempDir::new().unwrap();
2133        let result = restore_project_to_depth(
2134            tmp.path(),
2135            crate::constants::DEFAULT_SCAN_DEPTH,
2136            TEST_TIMEOUT,
2137        );
2138        assert!(result.is_err());
2139    }
2140
2141    #[test]
2142    fn restore_deleted_trusts_the_record_when_the_prune_erased_detection() {
2143        // Deleting a venv removes the very pyvenv.cfg that detection looks for, so
2144        // re-detection finds nothing. The recorded adapter must still be attempted —
2145        // not reported as "no longer a venv project".
2146        let tmp = TempDir::new().unwrap();
2147        let api = tmp.path().join("api");
2148        fs::create_dir_all(&api).unwrap();
2149        fs::write(api.join("requirements.txt"), "requests==2.32.3\n").unwrap();
2150        // No .venv on disk — the prune already removed it.
2151
2152        let deleted = vec![crate::config::PrunedDir {
2153            repo_path: tmp.path().to_path_buf(),
2154            bloat_dir: "api/.venv".to_string(),
2155            adapter: "venv".to_string(),
2156            size_freed: 0,
2157            runtime: None,
2158        }];
2159        // A zero timeout kills the rebuild the moment it starts; the test is about
2160        // which branch routes, not whether python can build an environment here.
2161        let results = restore_deleted(tmp.path(), &deleted, 4, std::time::Duration::ZERO);
2162
2163        assert_eq!(results.len(), 1);
2164        assert_eq!(results[0].label, "venv (api/.venv)");
2165        if let Err(e) = &results[0].result {
2166            assert!(
2167                !e.to_string().contains("no longer a"),
2168                "the recorded adapter must be attempted, got: {e}"
2169            );
2170        }
2171    }
2172
2173    #[test]
2174    fn a_git_repository_inside_a_bloat_directory_refuses_the_delete() {
2175        // A vendored checkout inside the directory about to be deleted carries its own
2176        // history, which no lockfile rebuilds. The whole delete must be refused.
2177        let tmp = TempDir::new().unwrap();
2178        let repo = tmp.path().join("repo");
2179        create_git_repo_with_commit(&repo);
2180        create_python_project(&repo);
2181        fs::create_dir_all(repo.join(".venv/src/vendored/.git")).unwrap();
2182
2183        let results = prune_repo_selected(&repo, 0, false, true, Some(&[".venv".to_string()]));
2184
2185        assert_eq!(results.len(), 1);
2186        let PruneStatus::SkippedNestedRepo(msg) = &results[0].status else {
2187            panic!("expected a refusal, got {:?}", results[0].status);
2188        };
2189        assert!(msg.contains("git repository"), "says why: {msg}");
2190        assert!(repo.join(".venv").exists(), "nothing may be deleted");
2191        assert_eq!(results[0].size_freed, 0);
2192    }
2193
2194    fn status_entry(name: &str, reclaimable: u64) -> RepoStatusEntry {
2195        RepoStatusEntry {
2196            path: PathBuf::from(name),
2197            entry: RepoEntry::new(),
2198            reason: SkipReason::Candidate,
2199            adapters: Vec::new(),
2200            bloat_dirs: Vec::new(),
2201            reclaimable_by_adapter: Vec::new(),
2202            reclaimable_bytes: reclaimable,
2203            last_activity: None,
2204            idle_days: 15,
2205        }
2206    }
2207
2208    #[test]
2209    fn take_top_selects_by_size_but_keeps_the_dashboard_order() {
2210        let repos = [
2211            status_entry("small", 10),
2212            status_entry("big", 300),
2213            status_entry("mid", 200),
2214        ];
2215        let names: Vec<String> = take_top(&repos, Some(2))
2216            .iter()
2217            .map(|e| e.path.display().to_string())
2218            .collect();
2219        // Selection is by reclaimable bytes; the survivors come back in the order the
2220        // full dashboard had them, so a truncated list reads like a shorter version of
2221        // the full one rather than a differently-sorted one.
2222        assert_eq!(names, vec!["big", "mid"]);
2223    }
2224
2225    #[test]
2226    fn take_top_without_a_limit_or_with_an_oversized_one_returns_everything() {
2227        let repos = [status_entry("a", 1), status_entry("b", 2)];
2228        assert_eq!(take_top(&repos, None).len(), 2);
2229        assert_eq!(take_top(&repos, Some(10)).len(), 2);
2230        assert_eq!(take_top(&repos, Some(0)).len(), 0);
2231    }
2232
2233    #[test]
2234    fn test_restore_project_with_npm() {
2235        let tmp = TempDir::new().unwrap();
2236        fs::write(tmp.path().join("package.json"), "{}").unwrap();
2237        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
2238        let results = restore_project_to_depth(
2239            tmp.path(),
2240            crate::constants::DEFAULT_SCAN_DEPTH,
2241            TEST_TIMEOUT,
2242        );
2243        // Will fail because npm isn't available in test env, but shouldn't panic
2244        assert!(results.is_ok());
2245        let results = results.unwrap();
2246        assert!(!results.is_empty());
2247        assert_eq!(results[0].0, "npm");
2248    }
2249
2250    #[test]
2251    fn the_scan_never_starts_more_threads_than_there_is_work() {
2252        // A registry of three should not start thirty-two of them to do nothing.
2253        assert_eq!(clamp_scan_threads(32, 3), 3);
2254        // Nor fewer than one on an empty registry: the calling thread is worker zero, and
2255        // a count of zero would mean the work loop never ran at all.
2256        assert_eq!(clamp_scan_threads(0, 0), 1);
2257        assert_eq!(clamp_scan_threads(0, 50), 1);
2258    }
2259
2260    #[test]
2261    fn an_absurd_thread_request_is_clamped_rather_than_honoured() {
2262        // `DEV_PRUNE_SCAN_THREADS=9999` is a typo, not an instruction.
2263        assert_eq!(
2264            clamp_scan_threads(9_999, 500),
2265            constants::STATUS_SCAN_MAX_THREADS
2266        );
2267    }
2268
2269    #[test]
2270    fn a_registry_of_one_repository_is_scanned_on_the_calling_thread_alone() {
2271        assert_eq!(clamp_scan_threads(16, 1), 1);
2272    }
2273}