Skip to main content

dev_prune/
config.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Configuration and registry management for dev-prune.
5//
6// This module handles persistent storage of:
7// - Global settings (idle threshold, check interval, daemon toggle)
8// - Registered repository paths and their metadata
9//
10// All data is stored in `~/.config/dev-prune/registry.json`.
11
12use std::collections::{BTreeMap, HashMap, HashSet};
13use std::fs;
14use std::io::Write as _;
15use std::path::{Path, PathBuf};
16
17use anyhow::{Context, Result};
18use chrono::{DateTime, Utc};
19use serde::{Deserialize, Serialize};
20
21use crate::constants;
22
23/// Global settings that control prune behavior.
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
25pub struct Settings {
26    /// Number of inactive days before a repo is eligible for pruning.
27    pub idle_days: u64,
28    /// Interval in days between automated daemon checks.
29    pub check_interval_days: u64,
30    /// Whether the setup pass installs the OS scheduler. On by default.
31    pub auto_daemon: bool,
32    /// Whether the setup pass installs the global Git hooks. On by default.
33    #[serde(default = "default_auto_hooks")]
34    pub auto_hooks: bool,
35    /// Whether dev-prune installs its own missing integrations. On by default.
36    #[serde(default = "default_auto_setup")]
37    pub auto_setup: bool,
38    /// Whether `link` and `init` write a default `.devprune.json` into repositories
39    /// they register. Off by default; see [`constants::DEFAULT_AUTO_CONFIG`].
40    #[serde(default = "default_auto_config")]
41    pub auto_config: bool,
42    /// Whether interactive confirmation is required before pruning.
43    #[serde(default = "default_require_confirmation")]
44    pub require_confirmation: bool,
45    /// Timeout in seconds for lockfile enforcement / CLI commands (default 600s = 10m).
46    #[serde(default = "default_command_timeout_secs")]
47    pub command_timeout_secs: u64,
48    /// Smallest bloat directory worth deleting, in MiB. `0` disables the floor.
49    ///
50    /// Below this size the reinstall costs more than the space is worth, so the
51    /// directory is not offered as a candidate at all.
52    #[serde(default = "default_min_size_mb")]
53    pub min_size_mb: u64,
54    /// Whether dev-prune asks GitHub for the latest release from time to time.
55    ///
56    /// On by default, and opt-*out* rather than opt-in: an out-of-date cleanup tool is a
57    /// tool whose safety fixes you do not have. The request sends nothing but itself —
58    /// no identifier, no configuration, no usage data. Turn it off with
59    /// `devp config set update_check false`.
60    #[serde(default = "default_update_check")]
61    pub update_check: bool,
62    /// How many directory levels below a repository root discovery descends.
63    ///
64    /// Six by default. A flat repository never notices; a monorepo that nests projects
65    /// under `packages/@scope/name/app` does. Raise it when `devp status` does not list
66    /// a project you know is there, and remember that the walk gets more expensive with
67    /// every level. Clamped to [`constants::MAX_SCAN_DEPTH_LIMIT`].
68    #[serde(default = "default_scan_depth")]
69    pub scan_depth: usize,
70    /// Whether cargo and go may run the sync command that rewrites tracked manifests.
71    ///
72    /// Off. See [`constants::DEFAULT_ALLOW_MANIFEST_REWRITE`] — with this off, both are
73    /// verified read-only and a project with no lockfile at all is simply not pruned.
74    #[serde(default = "default_allow_manifest_rewrite")]
75    pub allow_manifest_rewrite: bool,
76    /// Days between automatic release checks.
77    ///
78    /// Only the *automatic* check honours this; `devp update` always asks, because you
79    /// are standing there waiting for the answer.
80    #[serde(default = "default_update_check_interval_days")]
81    pub update_check_interval_days: i64,
82    /// How long the release check waits for GitHub before giving up, in seconds.
83    ///
84    /// Five is right on a normal connection and too short behind some corporate proxies,
85    /// which is the whole reason this is a setting rather than a constant.
86    #[serde(default = "default_update_check_timeout_secs")]
87    pub update_check_timeout_secs: u64,
88    /// Whether the setup pass may install the Git hooks *in front of* another tool's.
89    ///
90    /// Off. With it on, a `core.hooksPath` that belongs to husky is not a reason to skip:
91    /// dev-prune takes the slot and forwards every hook back to the directory it
92    /// displaced. Behaviour-preserving, but it is still someone else's setup, so it is
93    /// asked for rather than assumed. Same thing as `devp hook install --chain`.
94    #[serde(default = "default_auto_hooks_chain")]
95    pub auto_hooks_chain: bool,
96    /// Whether the opt-in Cargo adapter is active. Off by default, and the reason is
97    /// the same one that keeps `enable_gradle` off: Rust's `target/` is compiler
98    /// output. `cargo metadata --locked` proves the *crates* come back from
99    /// `Cargo.lock`, but nothing downloads a compiled artefact — the directory returns
100    /// only by rebuilding, which on a large workspace is minutes rather than the
101    /// seconds a dependency reinstall costs. See [`crate::adapters::cargo_adapter`].
102    #[serde(default)]
103    pub enable_cargo: bool,
104    /// Whether the opt-in Gradle build-tool adapter is active. Off by default:
105    /// `build/` comes back by recompiling the project, so nobody should find it
106    /// deleted without having asked. See [`crate::adapters::gradle`].
107    #[serde(default)]
108    pub enable_gradle: bool,
109    /// Whether the opt-in Maven build-tool adapter is active. Off by default, for the
110    /// same reason as `enable_gradle`. See [`crate::adapters::maven`].
111    #[serde(default)]
112    pub enable_maven: bool,
113    /// Whether the opt-in Swift Package Manager adapter is active. Off by default, for
114    /// the same reason as `enable_gradle`: `.build/` holds compiled modules and comes
115    /// back through `swift build`. See [`crate::adapters::swift`].
116    #[serde(default)]
117    pub enable_swift: bool,
118    /// Whether the opt-in Dart and Flutter adapter is active. Off by default: the pub
119    /// metadata in `.dart_tool/` is a second's work to restore, but the `build_runner`
120    /// and `flutter_build` caches beside it are compiler output and come back only by
121    /// recompiling. See [`crate::adapters::dart`].
122    #[serde(default)]
123    pub enable_dart: bool,
124    /// Whether the opt-in Mix build-tree adapter is active. Off by default, and separate
125    /// from the always-on `mix` adapter: that one deletes `deps/`, which comes back by
126    /// downloading, while `_build/` comes back only by recompiling the project and every
127    /// dependency in it. See [`crate::adapters::mix_build`].
128    #[serde(default)]
129    pub enable_mix_build: bool,
130    /// Whether the opt-in vcpkg adapter is active. Off by default: vcpkg builds every
131    /// port from source, so `vcpkg_installed/` comes back by compiling Boost or Qt
132    /// again rather than by downloading them. See [`crate::adapters::vcpkg`].
133    #[serde(default)]
134    pub enable_vcpkg: bool,
135
136    /// Whether the opt-in CMake build-tree adapter is active. Off by default: a build
137    /// tree is object files and linked binaries, and it comes back by compiling the
138    /// project again. See [`crate::adapters::cmake_build`].
139    #[serde(default)]
140    pub enable_cmake_build: bool,
141    /// Idle days required before *build-tree* directories — everything the opt-in
142    /// adapters claim — are pruned.
143    ///
144    /// Separate from `idle_days` because the cost of being wrong is different: a
145    /// deleted `node_modules` is one `npm ci` away, a deleted Android `build/` is a
146    /// long recompile. Applied as `max(build_idle_days, idle_days)`.
147    #[serde(default = "default_build_idle_days")]
148    pub build_idle_days: u64,
149    /// Whether a newer release installs itself at the end of a prune pass, once the
150    /// periodic check has found one.
151    ///
152    /// On by default. A pruner that runs on a schedule is exactly the kind of tool
153    /// nobody thinks to upgrade, and an old one keeps whatever bug it shipped with
154    /// forever. What runs here is the download-and-replace half only: see
155    /// [`crate::commands::update::maybe_auto_update`], which never hands the machine to
156    /// a package manager unattended and stands aside entirely on WinGet, Scoop and
157    /// Homebrew, where the manager owns the upgrade.
158    #[serde(default = "default_auto_update")]
159    pub auto_update: bool,
160    /// Whether this copy stays on the version it is, whatever else is configured.
161    ///
162    /// Off by default, and turned on only by a person typing
163    /// `devp config set version_lock true`. While it is on, `auto_update` does not run
164    /// however it is set, `devp update --install` refuses, `devp install --channel`
165    /// refuses because moving channels installs the latest release, and the install
166    /// scripts leave the binary exactly where they find it. There is no flag that
167    /// bypasses it: releasing the pin is the same kind of decision as setting it, and
168    /// belongs to the same person.
169    ///
170    /// It exists because `auto_update = false` was never the whole answer. That setting
171    /// stops one path; a machine that has to keep shipping the same tool for a year --
172    /// a CI image, a reproduction that stops reproducing the moment the tool changes
173    /// underneath it, a locked-down build box -- also has to survive someone re-running
174    /// the install one-liner out of habit.
175    #[serde(default)]
176    pub version_lock: bool,
177    /// Adapters switched off by name, whatever their lockfiles say.
178    ///
179    /// A deny-list rather than twenty `enable_*` booleans, because the answer for
180    /// almost everyone is "none of them" and a list of exceptions says that in one
181    /// place. It is a *preference*, and the opposite of `enable_gradle` and friends:
182    /// those are off until asked for because deleting a build tree is expensive to
183    /// undo, whereas `node_modules` is safe to prune and merely something a particular
184    /// person may not want touched.
185    ///
186    /// Names are the adapter names `--only`/`--skip` take. Applied in
187    /// [`crate::adapters::detect_adapters`], so a disabled adapter is invisible to
188    /// every command at once rather than listed by `status` and skipped by `run`.
189    #[serde(default)]
190    pub disabled_adapters: Vec<String>,
191    /// Per-adapter idle windows, in days, keyed by adapter name.
192    ///
193    /// The one dial that is neither global nor per-repository: "wait longer before
194    /// touching Rust" is a statement about a *toolchain*, not about one checkout, and
195    /// before this it could only be said by moving the global window for everything.
196    ///
197    /// **A floor, never a bypass.** The value is applied as
198    /// `max(idle_days, adapter_idle_days[name])`, so it can only make an adapter wait
199    /// longer than the repository-level check already requires. A smaller number is
200    /// accepted and simply has no effect — the repository gate runs first and is the
201    /// same gate for every adapter, and letting one adapter lower it would be a
202    /// bypass of the idle check rather than a preference.
203    ///
204    /// `BTreeMap` rather than `HashMap` so the JSON round-trips in a stable order and
205    /// a diff of the registry file shows what actually changed.
206    #[serde(default)]
207    pub adapter_idle_days: BTreeMap<String, u64>,
208    /// Per-manager cache size caps, in gibibytes, keyed by cache manager name.
209    ///
210    /// A download cache is a bet that re-downloading costs more than the disk it
211    /// occupies, and the bet stops paying somewhere: a `uv` cache past ten gigabytes is
212    /// keeping wheels for Python versions the machine no longer has, and no repository's
213    /// lockfile will ever say so. This is where that ceiling is written down.
214    ///
215    /// **It never deletes anything on its own.** `devp caches` marks a cache over its
216    /// cap and `devp caches clear --over-cap` empties exactly those; nothing dev-prune
217    /// runs on a schedule touches a cache, which is a promise `devp caches` prints in
218    /// so many words and a size cap is not a reason to break.
219    ///
220    /// Keyed by the names `devp caches clear <MANAGER>` takes, not by adapter name.
221    /// They mostly agree — `npm`, `uv`, `cargo`, `go` — but `pip`, `nuget`, `conan`,
222    /// `conda`, `vcpkg` and `hex` are caches with no adapter, and `venv`, `terraform`
223    /// and `dart` are adapters with no cache. Empty by default: no cache is too big
224    /// until someone says what too big is.
225    #[serde(default)]
226    pub cache_max_gb: BTreeMap<String, u64>,
227    /// Language for dev-prune's own headings and summary lines.
228    ///
229    /// English by default, and English wherever a translation has not reached a string
230    /// yet -- see [`crate::i18n`] for what is translated and, more importantly, what is
231    /// not: `--json`, exit codes, flag names, config keys and the sentences a refusal
232    /// prints stay in English in every language, because they are a contract or a
233    /// diagnosis rather than prose.
234    ///
235    /// `DEV_PRUNE_LANG` overrides this for one invocation. An unrecognised code falls
236    /// back to English rather than failing.
237    #[serde(default = "default_language")]
238    pub language: String,
239    /// Settings this build has never heard of, carried through a save verbatim.
240    ///
241    /// A registry written by a newer dev-prune can hold keys this build does not
242    /// know, and every save rewrites the whole `settings` object — so without this,
243    /// one run of an older binary (a pinned CI image, a machine `version_lock` holds
244    /// back) silently erased the newer binary's configuration. `BTreeMap` for the
245    /// same stable-diff reason as `adapter_idle_days`.
246    #[serde(flatten, default)]
247    pub unknown_keys: BTreeMap<String, serde_json::Value>,
248}
249
250fn default_build_idle_days() -> u64 {
251    constants::DEFAULT_BUILD_IDLE_DAYS
252}
253
254fn default_require_confirmation() -> bool {
255    constants::DEFAULT_REQUIRE_CONFIRMATION
256}
257
258fn default_command_timeout_secs() -> u64 {
259    constants::DEFAULT_COMMAND_TIMEOUT_SECS
260}
261
262fn default_auto_hooks() -> bool {
263    constants::DEFAULT_AUTO_HOOKS
264}
265
266fn default_auto_setup() -> bool {
267    constants::DEFAULT_AUTO_SETUP
268}
269
270fn default_auto_config() -> bool {
271    constants::DEFAULT_AUTO_CONFIG
272}
273
274fn default_update_check() -> bool {
275    constants::DEFAULT_UPDATE_CHECK
276}
277
278fn default_auto_update() -> bool {
279    constants::DEFAULT_AUTO_UPDATE
280}
281
282fn default_min_size_mb() -> u64 {
283    constants::DEFAULT_MIN_SIZE_MB
284}
285
286fn default_scan_depth() -> usize {
287    constants::DEFAULT_SCAN_DEPTH
288}
289
290fn default_allow_manifest_rewrite() -> bool {
291    constants::DEFAULT_ALLOW_MANIFEST_REWRITE
292}
293
294fn default_update_check_interval_days() -> i64 {
295    constants::UPDATE_CHECK_INTERVAL_DAYS
296}
297
298fn default_update_check_timeout_secs() -> u64 {
299    constants::UPDATE_CHECK_TIMEOUT_SECS
300}
301
302fn default_auto_hooks_chain() -> bool {
303    constants::DEFAULT_AUTO_HOOKS_CHAIN
304}
305
306fn default_language() -> String {
307    constants::DEFAULT_LANGUAGE.to_string()
308}
309
310impl Default for Settings {
311    fn default() -> Self {
312        Self {
313            idle_days: constants::DEFAULT_IDLE_DAYS,
314            check_interval_days: constants::DEFAULT_CHECK_INTERVAL_DAYS,
315            auto_daemon: constants::DEFAULT_AUTO_DAEMON,
316            auto_hooks: constants::DEFAULT_AUTO_HOOKS,
317            auto_setup: constants::DEFAULT_AUTO_SETUP,
318            auto_config: constants::DEFAULT_AUTO_CONFIG,
319            require_confirmation: constants::DEFAULT_REQUIRE_CONFIRMATION,
320            command_timeout_secs: constants::DEFAULT_COMMAND_TIMEOUT_SECS,
321            min_size_mb: constants::DEFAULT_MIN_SIZE_MB,
322            update_check: constants::DEFAULT_UPDATE_CHECK,
323            scan_depth: constants::DEFAULT_SCAN_DEPTH,
324            allow_manifest_rewrite: constants::DEFAULT_ALLOW_MANIFEST_REWRITE,
325            update_check_interval_days: constants::UPDATE_CHECK_INTERVAL_DAYS,
326            update_check_timeout_secs: constants::UPDATE_CHECK_TIMEOUT_SECS,
327            auto_hooks_chain: constants::DEFAULT_AUTO_HOOKS_CHAIN,
328            enable_cargo: false,
329            enable_gradle: false,
330            enable_maven: false,
331            enable_swift: false,
332            enable_dart: false,
333            enable_mix_build: false,
334            enable_vcpkg: false,
335            enable_cmake_build: false,
336            build_idle_days: constants::DEFAULT_BUILD_IDLE_DAYS,
337            auto_update: constants::DEFAULT_AUTO_UPDATE,
338            version_lock: constants::DEFAULT_VERSION_LOCK,
339            disabled_adapters: Vec::new(),
340            adapter_idle_days: BTreeMap::new(),
341            cache_max_gb: BTreeMap::new(),
342            language: constants::DEFAULT_LANGUAGE.to_string(),
343            unknown_keys: BTreeMap::new(),
344        }
345    }
346}
347
348/// Outcome of recording a repository's identity when it was registered.
349///
350/// Reported rather than silent: a registration that quietly absorbed another entry's
351/// prune history would be indistinguishable from one that lost it.
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub enum Adoption {
354    /// No dead entry claimed this identity.
355    Nothing,
356    /// This registration took over the history of a path that no longer exists.
357    Moved(PathBuf),
358    /// More than one dead entry claims the identity, so none was chosen.
359    Ambiguous,
360}
361
362/// Metadata for a single registered repository.
363#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
364pub struct RepoEntry {
365    /// Timestamp when the repo was added to the registry.
366    pub added_at: DateTime<Utc>,
367    /// Timestamp of the last successful prune, if any.
368    pub last_pruned_at: Option<DateTime<Utc>>,
369    /// Per-repo override for idle days (overrides global setting).
370    pub override_idle_days: Option<u64>,
371    /// Whether this repo is enabled for pruning.
372    pub enabled: bool,
373    /// Cumulative bytes reclaimed from this repository.
374    ///
375    /// Recorded from 1.1.0 onward. Registries written by 1.0.0 have no such figure and
376    /// deserialize to zero, so `devp stats` says where the number starts rather than
377    /// implying a repository pruned last March never freed anything.
378    #[serde(default)]
379    pub total_freed_bytes: u64,
380    /// The repository's root commit, recorded when it was registered.
381    ///
382    /// A repository that is moved keeps this; its path does not. Without it a moved
383    /// workspace registers as a brand new repository and its prune history is stranded
384    /// on a path that will never exist again. Registries written before 1.4.0 have none,
385    /// and re-registering the repository is what fills it in.
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub identity: Option<String>,
388}
389
390impl RepoEntry {
391    /// Creates a new `RepoEntry` with the current timestamp.
392    pub fn new() -> Self {
393        Self {
394            added_at: Utc::now(),
395            last_pruned_at: None,
396            override_idle_days: None,
397            enabled: true,
398            total_freed_bytes: 0,
399            identity: None,
400        }
401    }
402}
403
404impl Default for RepoEntry {
405    fn default() -> Self {
406        Self::new()
407    }
408}
409
410/// Resolve where a repository's shared git directory actually lives.
411///
412/// `.git` is a directory in an ordinary clone, but in worktrees and submodules it is a
413/// one-line `gitdir: <path>` pointer file — and a worktree's private gitdir in turn
414/// holds a `commondir` file pointing at the shared one, which is where `info/exclude`
415/// lives. Returns `None` when the path is not inside a git repository at all.
416fn git_common_dir(repo_path: &Path) -> Option<PathBuf> {
417    let dot_git = repo_path.join(".git");
418    let git_dir = if dot_git.is_dir() {
419        dot_git
420    } else {
421        let pointer = fs::read_to_string(&dot_git).ok()?;
422        let target = pointer.strip_prefix("gitdir:")?.trim();
423        let target = Path::new(target);
424        if target.is_absolute() {
425            target.to_path_buf()
426        } else {
427            repo_path.join(target)
428        }
429    };
430    if let Ok(common) = fs::read_to_string(git_dir.join("commondir")) {
431        let target = Path::new(common.trim());
432        if target.is_absolute() {
433            return Some(target.to_path_buf());
434        }
435        return Some(git_dir.join(target));
436    }
437    Some(git_dir)
438}
439
440/// Ensure an entry (e.g. ".devprune.json") is in the repository's `.git/info/exclude`.
441///
442/// The exclude file, not `.gitignore`: the config records one machine's preferences,
443/// and `.gitignore` is a tracked file shared by everyone who clones the repository —
444/// appending to it silently puts an uncommitted change in the user's diff. The exclude
445/// file gives the same "never shows up in `git status`" result without touching
446/// anything the repository tracks.
447pub fn ensure_in_git_exclude(repo_path: &Path, entry: &str) -> Result<()> {
448    let Some(git_dir) = git_common_dir(repo_path) else {
449        return Ok(());
450    };
451    let info_dir = git_dir.join("info");
452    fs::create_dir_all(&info_dir)?;
453    let exclude_path = info_dir.join("exclude");
454    if exclude_path.exists() {
455        let content = fs::read_to_string(&exclude_path)?;
456        if !content.lines().any(|line| line.trim() == entry) {
457            let mut file = fs::OpenOptions::new().append(true).open(&exclude_path)?;
458            let prefix = if content.ends_with('\n') || content.is_empty() {
459                ""
460            } else {
461                "\n"
462            };
463            writeln!(file, "{prefix}{entry}")?;
464        }
465    } else {
466        fs::write(&exclude_path, format!("{entry}\n"))?;
467    }
468    Ok(())
469}
470
471/// Normalise a repository path into the form used as a registry key.
472///
473/// Falls back to the path as given when it cannot be canonicalised (e.g. it no longer
474/// exists), so entries for deleted repos stay addressable.
475pub fn canonical_key(path: &Path) -> PathBuf {
476    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
477}
478
479/// Resolve `.` and `..` segments and anchor a relative path to the working directory,
480/// for paths that no longer exist and so cannot be canonicalised whole. The deepest
481/// ancestor that still exists is canonicalised and the missing tail re-appended:
482/// registry keys are canonical, and a deleted repo named through a symlinked parent —
483/// macOS's `/var` → `/private/var` temp tree being the everyday case — would otherwise
484/// spell the same directory through a different root and never compare equal.
485fn lexical_absolute(path: &Path) -> PathBuf {
486    use std::path::Component;
487    let mut out = if path.is_absolute() {
488        PathBuf::new()
489    } else {
490        std::env::current_dir().unwrap_or_default()
491    };
492    for comp in path.components() {
493        match comp {
494            Component::CurDir => {}
495            Component::ParentDir => {
496                out.pop();
497            }
498            other => out.push(other.as_os_str()),
499        }
500    }
501    let mut prefix = out.as_path();
502    while !prefix.as_os_str().is_empty() {
503        if let Ok(real) = prefix.canonicalize() {
504            if let Ok(tail) = out.strip_prefix(prefix) {
505                return real.join(tail);
506            }
507            break;
508        }
509        match prefix.parent() {
510            Some(parent) => prefix = parent,
511            None => break,
512        }
513    }
514    out
515}
516
517/// Whether two paths name the same directory, tolerating the differences
518/// canonicalisation normally absorbs: the Windows `\\?\` prefix, separator style,
519/// trailing separators, and case on Windows.
520fn loose_path_eq(a: &Path, b: &Path) -> bool {
521    let norm = |p: &Path| {
522        let s = p.to_string_lossy().replace('\\', "/");
523        let s = s.strip_prefix("//?/").unwrap_or(&s);
524        let s = s.trim_end_matches('/').to_string();
525        if cfg!(windows) { s.to_lowercase() } else { s }
526    };
527    norm(a) == norm(b)
528}
529
530/// Expand a leading `~` to the user's home directory.
531///
532/// POSIX shells do this before the argument ever reaches a program, so on Linux and
533/// macOS it is usually a no-op. PowerShell and cmd do not: they hand a native
534/// executable the literal three characters `~/C`, and `devp init ~/Code` — the exact
535/// line in the README and on the landing page — would register a directory called `~`
536/// sitting in the current working directory. Quoting defeats the expansion in *every*
537/// shell, so `devp init "~/Code"` needs this too.
538///
539/// Only a bare `~` or a `~` followed by a separator is expanded. `~alice` means "some
540/// other user's home" in shell syntax and cannot be resolved portably, and `~backup` is
541/// a perfectly ordinary directory name.
542pub fn expand_tilde(raw: &str) -> String {
543    let Some(rest) = raw.strip_prefix('~') else {
544        return raw.to_string();
545    };
546    if !(rest.is_empty() || rest.starts_with('/') || rest.starts_with('\\')) {
547        return raw.to_string();
548    }
549    let Some(home) = dirs::home_dir() else {
550        // No home directory to expand to. Handing back the literal `~` lets the caller
551        // fail with "no such directory", which is a better error than a silent guess.
552        return raw.to_string();
553    };
554    if rest.is_empty() {
555        return home.to_string_lossy().into_owned();
556    }
557    home.join(rest.trim_start_matches(['/', '\\']))
558        .to_string_lossy()
559        .into_owned()
560}
561
562/// Structured per-repository configuration file stored inside repo roots as `.devprune.json`.
563#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
564pub struct PerRepoConfig {
565    /// JSON Schema reference URL for IDE IntelliSense and validation.
566    #[serde(rename = "$schema", default = "default_schema_url")]
567    pub schema: String,
568    /// Custom display name for this project in TUI and CLI status views.
569    #[serde(default)]
570    pub project_name: Option<String>,
571    /// Whether this repository is ignored/excluded from pruning.
572    #[serde(default)]
573    pub ignore: bool,
574    /// Disable global Git auto-registration hooks for this specific workspace.
575    #[serde(default)]
576    pub disable_hooks: bool,
577    /// Disable background daemon automated pruning pass for this specific workspace.
578    #[serde(default)]
579    pub disable_daemon: bool,
580    /// Custom override for idle days threshold (overrides global settings).
581    #[serde(default)]
582    pub override_idle_days: Option<u64>,
583    /// Custom override for the size floor, in MiB (overrides global `min_size_mb`).
584    ///
585    /// `Some(0)` is a meaningful value: it turns the floor off for this repository even
586    /// when a global floor is set.
587    #[serde(default)]
588    pub min_size_mb: Option<u64>,
589    /// Custom override for how deep discovery walks this repository.
590    ///
591    /// The setting that most often needs to differ per repository rather than globally:
592    /// one deeply-nested monorepo should not make every other repository pay for a
593    /// deeper walk. Clamped to [`constants::MAX_SCAN_DEPTH_LIMIT`] like the global one.
594    #[serde(default)]
595    pub scan_depth: Option<usize>,
596    /// What this project declares prunable beyond what an adapter can recognise.
597    #[serde(default, skip_serializing_if = "Option::is_none")]
598    pub prunable: Option<Prunable>,
599}
600
601/// The nested half of a repository's config: what this project says is rebuildable.
602///
603/// A section rather than a top-level key, because the keys above it are the whole of
604/// what a repository could say in 1.0.0 and the list of things it might want to say is
605/// not finished. Everything that arrives later and describes *what to delete* belongs
606/// under this heading with `directories`, so the file grows a section at a time instead
607/// of a scatter of top-level names nobody can group by eye.
608#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
609pub struct Prunable {
610    /// Directories dev-prune would never find on its own, each with its way back.
611    #[serde(default, skip_serializing_if = "Vec::is_empty")]
612    pub directories: Vec<DeclaredDir>,
613    /// Declared paths to leave alone on this machine, whoever declared them.
614    ///
615    /// `project.devprune.json` is committed, so one person's `scratch` is everybody's
616    /// `scratch`, and the teammate whose copy is holding something had no way to say so
617    /// short of editing a file the whole team shares. Same spelling as a `path` in
618    /// `directories`; the entry it names is skipped entirely.
619    #[serde(default, skip_serializing_if = "Vec::is_empty")]
620    pub exclude: Vec<String>,
621}
622
623/// One directory a project declares prunable, and the command that puts it back.
624///
625/// Every adapter in this tool earns the right to delete a directory by finding a
626/// lockfile that can rebuild it. A declaration is the same bargain made by hand: the
627/// project states the directory, and states what rebuilds it, and dev-prune checks that
628/// the stated command is one this machine could actually run before it deletes anything.
629///
630/// `rebuild` is required, and required is the point. An optional one would have made
631/// "delete this, I have no idea how to get it back" the path of least resistance in a
632/// file that gets committed and cloned.
633#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
634pub struct DeclaredDir {
635    /// Repository-relative, `/`-separated. Never absolute, never `..`, never `.git`.
636    pub path: String,
637    /// The command that rebuilds it. Shown, never run — see [`crate::declared`].
638    pub rebuild: String,
639    /// Why this is safe to lose, in the project's own words. Printed beside the path.
640    #[serde(default, skip_serializing_if = "Option::is_none")]
641    pub why: Option<String>,
642}
643
644// Deliberately absent: `allow_manifest_rewrite`.
645//
646// Only the settings whose right value depends on the *project* have a per-repository
647// form. `allow_manifest_rewrite` is a permission the user grants their own machine, and
648// — exactly as with `post_prune_command` below — nothing stops a project from committing
649// its `.devprune.json`: the `.git/info/exclude` entry [`PerRepoConfig::save_to_repo`]
650// writes is local to one clone and excludes nothing already tracked. A
651// per-repository form would therefore let a repository nobody has read grant itself the
652// right to have `cargo generate-lockfile` / `go mod tidy` rewrite its tracked manifests
653// during an unattended pass. The `auto_*` and `update_check*` settings describe the
654// machine rather than a project and would mean nothing here either.
655
656// Removed: `custom_bloat_dirs` and `post_prune_command`.
657//
658// Both were serialized, schema'd and documented but never read by any code path, so
659// setting them did nothing. `post_prune_command` is also not a feature that should be
660// reintroduced casually: nothing stops a project from committing its `.devprune.json`,
661// so honouring it would mean cloning an untrusted repository and running `devp` hands
662// that repository arbitrary code execution on the user's machine.
663
664fn default_schema_url() -> String {
665    if let Ok(config_dir) = Registry::config_dir() {
666        let local_schema = config_dir.join("bin").join("devprune.schema.json");
667        if local_schema.exists() {
668            // `file://` + `/` + an absolute path. Unix paths already start with a
669            // separator, so pasting them in unconditionally produced `file:////home/...`
670            // — four slashes, which editors reject, leaving the `$schema` link dead and
671            // no IntelliSense at all on the platform where most of them run.
672            return file_uri(&crate::output::clean_path(&local_schema));
673        }
674    }
675    constants::JSON_SCHEMA_URL.to_string()
676}
677
678/// A `file://` URI for an absolute path.
679///
680/// `file://` + `/` + the path. Unix paths already start with a separator, so pasting one
681/// in unconditionally produced `file:////home/...` — four slashes, which editors reject,
682/// leaving the `$schema` link dead and no IntelliSense at all on the platform where most
683/// of them run.
684fn file_uri(clean_path: &str) -> String {
685    format!("file:///{}", clean_path.trim_start_matches('/'))
686}
687
688impl Default for PerRepoConfig {
689    fn default() -> Self {
690        Self {
691            schema: default_schema_url(),
692            project_name: None,
693            ignore: false,
694            disable_hooks: false,
695            disable_daemon: false,
696            override_idle_days: None,
697            min_size_mb: None,
698            scan_depth: None,
699            prunable: None,
700        }
701    }
702}
703
704impl PerRepoConfig {
705    /// Load per-repo config from `.devprune.json`, or `None` when there is no such file.
706    ///
707    /// This is the only loader. There used to be a second one that returned `None` for a
708    /// file that failed to parse as well as for one that was absent, and every caller of
709    /// it then went on to act as though the repository had no configuration: the prune
710    /// pass ignored an `"ignore": true` it could not read, and the two workspace toggles
711    /// wrote a fresh default file straight over the user's broken one, taking every
712    /// override in it with them. A caller that genuinely does not care — the display-name
713    /// lookup — says so with `.ok().flatten()`.
714    pub fn load_with_diagnostics(repo_path: &Path) -> Result<Option<Self>, String> {
715        Ok(RepoConfigLayers::load(repo_path)?.effective())
716    }
717
718    /// Save per-repo config to `.devprune.json` in the repo root, and record it in the
719    /// repository's `.git/info/exclude` so it never shows up in `git status`.
720    pub fn save_to_repo(&self, repo_path: &Path) -> Result<()> {
721        let config_file = repo_path.join(constants::PER_REPO_CONFIG_FILE);
722        let content = serde_json::to_string_pretty(self)?;
723        fs::write(&config_file, content)?;
724        let _ = ensure_in_git_exclude(repo_path, constants::PER_REPO_CONFIG_FILE);
725        let _ = ensure_in_git_exclude(repo_path, constants::DEVPRUNE_IGNORE_FILE);
726        Ok(())
727    }
728
729    /// Which of a repository's config files exist and do not parse, and why.
730    ///
731    /// [`load_with_diagnostics`](Self::load_with_diagnostics) collapses both into one
732    /// refusal, which is the right answer for every reader: a config that cannot be read
733    /// is a repository dev-prune will not touch, whichever file it was in. `devp doctor`
734    /// is the one caller that has to know which, because it repairs the personal file by
735    /// renaming it aside and must never do that to a file the user has committed.
736    pub fn broken_files(repo_path: &Path) -> Vec<(&'static str, String)> {
737        [
738            constants::PROJECT_REPO_CONFIG_FILE,
739            constants::PER_REPO_CONFIG_FILE,
740        ]
741        .into_iter()
742        .filter_map(|name| match read_layer(&repo_path.join(name)) {
743            Err(e) => Some((name, e)),
744            Ok(_) => None,
745        })
746        .collect()
747    }
748
749    /// Keys a repository config file spells out that dev-prune does not read.
750    ///
751    /// Unknown keys are tolerated on purpose — a file written by a newer dev-prune must
752    /// not stop an older one from reading the keys it does know — so
753    /// `deny_unknown_fields` is the one fix this must never become. The cost of that
754    /// tolerance is that a typo (`idle_days` for `override_idle_days`) silently does
755    /// nothing, and nothing on this machine ever tells its author why. This is the
756    /// diagnostic half: `devp doctor` names each stray key, and behaviour changes
757    /// nowhere.
758    pub fn unknown_keys(repo_path: &Path) -> Vec<(&'static str, String)> {
759        const KNOWN: &[&str] = &[
760            "$schema",
761            "project_name",
762            "ignore",
763            "disable_hooks",
764            "disable_daemon",
765            "override_idle_days",
766            "min_size_mb",
767            "scan_depth",
768            "prunable",
769        ];
770        const KNOWN_PRUNABLE: &[&str] = &["directories", "exclude"];
771        const KNOWN_DIRECTORY: &[&str] = &["path", "rebuild", "why"];
772
773        let mut out = Vec::new();
774        for name in [
775            constants::PROJECT_REPO_CONFIG_FILE,
776            constants::PER_REPO_CONFIG_FILE,
777        ] {
778            let Ok(content) = fs::read_to_string(repo_path.join(name)) else {
779                continue;
780            };
781            let Ok(serde_json::Value::Object(map)) = serde_json::from_str(&content) else {
782                continue;
783            };
784            for key in map.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
785                out.push((name, key.clone()));
786            }
787            let Some(serde_json::Value::Object(prunable)) = map.get("prunable") else {
788                continue;
789            };
790            for key in prunable
791                .keys()
792                .filter(|k| !KNOWN_PRUNABLE.contains(&k.as_str()))
793            {
794                out.push((name, format!("prunable.{key}")));
795            }
796            if let Some(serde_json::Value::Array(dirs)) = prunable.get("directories") {
797                for entry in dirs.iter().filter_map(|d| d.as_object()) {
798                    for key in entry
799                        .keys()
800                        .filter(|k| !KNOWN_DIRECTORY.contains(&k.as_str()))
801                    {
802                        out.push((name, format!("prunable.directories[].{key}")));
803                    }
804                }
805            }
806        }
807        out
808    }
809
810    /// The personal `.devprune.json` alone, for a caller about to write it back.
811    ///
812    /// [`load_with_diagnostics`](Self::load_with_diagnostics) answers "what is in force
813    /// here", which is the merge of both files and the right answer for everything that
814    /// reads. It is the wrong answer for anything that writes: saving it copies the
815    /// project file's values into the personal one, and the next edit to the project
816    /// file leaves that copy behind, silently overriding the file it was copied from.
817    pub fn load_personal_for_write(repo_path: &Path) -> Result<Option<Self>, String> {
818        Ok(RepoConfigLayers::load(repo_path)?
819            .personal_config()
820            .cloned())
821    }
822}
823
824/// Write a starter `project.devprune.json`: a schema link, and the empty section.
825///
826/// Deliberately not a serialized [`PerRepoConfig::default`]. Every scalar key the
827/// project file names is a key it wins, so writing all of them out would have `--team`
828/// quietly take over every setting in the `.devprune.json` beside it — including the
829/// ones that file was created to hold. An empty team file decides nothing until the team
830/// decides something, and the `$schema` link is what makes deciding it a matter of
831/// autocomplete rather than of remembering the key names.
832///
833/// The one thing written out is the empty `prunable.directories`, which decides nothing
834/// either — an empty list adds no directories. It is there because a section nobody can
835/// see is a section nobody fills in, and this is the file a person or an agent is
836/// expected to fill in.
837///
838/// No `ensure_in_git_exclude`, and that omission is the entire point. [`PerRepoConfig::
839/// save_to_repo`] hides what it writes because one person's overrides are nobody else's
840/// business; hiding this one would leave it identical to the file beside it and useful
841/// to nobody.
842pub fn write_project_starter(repo_path: &Path) -> Result<()> {
843    let file = repo_path.join(constants::PROJECT_REPO_CONFIG_FILE);
844    let starter = serde_json::json!({
845        "$schema": default_schema_url(),
846        "prunable": { "directories": [] },
847    });
848    fs::write(&file, serde_json::to_string_pretty(&starter)?)?;
849    Ok(())
850}
851
852/// Which of a repository's two config files an effective value came from.
853#[derive(Debug, Clone, Copy, PartialEq, Eq)]
854pub enum ConfigSource {
855    /// Spelled out in the committed `project.devprune.json`.
856    Project,
857    /// Spelled out in the git-excluded `.devprune.json`.
858    Personal,
859    /// In neither file, so whatever the global setting or the built-in default says.
860    Default,
861}
862
863impl ConfigSource {
864    /// The file this answer came from, or where to look when it came from no file.
865    pub fn label(self) -> &'static str {
866        match self {
867            Self::Project => constants::PROJECT_REPO_CONFIG_FILE,
868            Self::Personal => constants::PER_REPO_CONFIG_FILE,
869            Self::Default => "global setting",
870        }
871    }
872}
873
874/// A repository's configuration as the two files that can contribute to it.
875///
876/// The project file wins every scalar key it names, and the personal file answers the
877/// rest. That is the inverse of the usual local-overrides-committed convention, and
878/// deliberately so: the settings here are the ones a *project* decides, and a team that
879/// has written down "this repository is not worth pruning" wants that to survive a
880/// teammate's stale personal file rather than lose to it.
881///
882/// "Names a key" means the key is literally in the file. A project file silent on
883/// `ignore` does not overrule the personal one with serde's `false`, because a default
884/// filled in by the deserializer is not something anybody wrote down.
885///
886/// `prunable.directories` is the one thing that unions instead of winning. It is a list
887/// of separate declarations rather than a single decided value, so there is nothing for
888/// one file to win: "the team says this cache is rebuildable" and "so is this one on my
889/// machine" are both true at once, and a rule that let the committed file silence the
890/// personal list would delete somebody's own declaration the day their team wrote their
891/// first one. `prunable.exclude` unions for the opposite reason: a veto only ever
892/// deletes less, so it is safe to honour from whichever file wrote it.
893///
894/// Nothing here widens what a repository can ask for. Both files deserialize into the
895/// same [`PerRepoConfig`], so the two settings the type deliberately does not carry —
896/// `allow_manifest_rewrite` and `post_prune_command` — are still absent from both, and
897/// every field that is present is either display-only or scope-shaping. A committed
898/// `.devprune.json` has had exactly this reach since 1.0.0, since the `.git/info/exclude`
899/// entry is local to one clone and excludes nothing already tracked; the shared file
900/// makes that reach a named, documented file instead of an accident.
901pub struct RepoConfigLayers {
902    /// The committed file and the keys it actually spells out.
903    project: Option<(PerRepoConfig, HashSet<String>)>,
904    /// The git-excluded file and the keys it actually spells out.
905    personal: Option<(PerRepoConfig, HashSet<String>)>,
906}
907
908impl RepoConfigLayers {
909    /// Read both files. `Err` if either exists and does not parse.
910    pub fn load(repo_path: &Path) -> Result<Self, String> {
911        Ok(Self {
912            project: read_layer(&repo_path.join(constants::PROJECT_REPO_CONFIG_FILE))?,
913            personal: read_layer(&repo_path.join(constants::PER_REPO_CONFIG_FILE))?,
914        })
915    }
916
917    /// The merged configuration, or `None` when the repository has neither file.
918    ///
919    /// `None` rather than the defaults, because every caller of this treats "no config"
920    /// and "a config that happens to match the defaults" as the same thing to act on but
921    /// not the same thing to report.
922    pub fn effective(&self) -> Option<PerRepoConfig> {
923        if self.project.is_none() && self.personal.is_none() {
924            return None;
925        }
926        let base = self
927            .personal
928            .as_ref()
929            .map(|(c, _)| c.clone())
930            .unwrap_or_default();
931        let Some((project, keys)) = &self.project else {
932            return Some(base);
933        };
934        let said = |k: &str| keys.contains(k);
935        let declared = merge_declarations(project.prunable.as_ref(), base.prunable);
936        Some(PerRepoConfig {
937            // Never taken from the project file. `$schema` points at a validator, and the
938            // one this clone should resolve is the one this machine has —
939            // `default_schema_url` prefers a local copy when there is one, which a
940            // teammate's committed absolute path would override with a file that does
941            // not exist here.
942            schema: base.schema,
943            project_name: pick(
944                said("project_name"),
945                &project.project_name,
946                base.project_name,
947            ),
948            ignore: pick(said("ignore"), &project.ignore, base.ignore),
949            disable_hooks: pick(
950                said("disable_hooks"),
951                &project.disable_hooks,
952                base.disable_hooks,
953            ),
954            disable_daemon: pick(
955                said("disable_daemon"),
956                &project.disable_daemon,
957                base.disable_daemon,
958            ),
959            override_idle_days: pick(
960                said("override_idle_days"),
961                &project.override_idle_days,
962                base.override_idle_days,
963            ),
964            min_size_mb: pick(said("min_size_mb"), &project.min_size_mb, base.min_size_mb),
965            scan_depth: pick(said("scan_depth"), &project.scan_depth, base.scan_depth),
966            prunable: declared,
967        })
968    }
969
970    /// The committed file as it stands, before the personal one fills any gaps in.
971    pub fn project_config(&self) -> Option<&PerRepoConfig> {
972        self.project.as_ref().map(|(c, _)| c)
973    }
974
975    /// The personal file as it stands, before the project one overrules any of it.
976    pub fn personal_config(&self) -> Option<&PerRepoConfig> {
977        self.personal.as_ref().map(|(c, _)| c)
978    }
979
980    /// Which file each setting's effective value came from.
981    ///
982    /// This is what gets shown instead of copying the project file's values into
983    /// `.devprune.json` as a visible "mirror". A second copy of a value is a second copy
984    /// free to drift from the first, and the question somebody actually has in front of
985    /// two config files is not "what does each say" but "which one won".
986    pub fn rows(&self) -> Vec<(&'static str, String, ConfigSource)> {
987        let cfg = self.effective().unwrap_or_default();
988        vec![
989            (
990                "project_name",
991                opt(&cfg.project_name),
992                self.source_of("project_name"),
993            ),
994            ("ignore", cfg.ignore.to_string(), self.source_of("ignore")),
995            (
996                "disable_hooks",
997                cfg.disable_hooks.to_string(),
998                self.source_of("disable_hooks"),
999            ),
1000            (
1001                "disable_daemon",
1002                cfg.disable_daemon.to_string(),
1003                self.source_of("disable_daemon"),
1004            ),
1005            (
1006                "override_idle_days",
1007                opt(&cfg.override_idle_days),
1008                self.source_of("override_idle_days"),
1009            ),
1010            (
1011                "min_size_mb",
1012                opt(&cfg.min_size_mb),
1013                self.source_of("min_size_mb"),
1014            ),
1015            (
1016                "scan_depth",
1017                opt(&cfg.scan_depth),
1018                self.source_of("scan_depth"),
1019            ),
1020        ]
1021    }
1022
1023    /// Which file spelled this key out, in precedence order.
1024    pub fn source_of(&self, key: &str) -> ConfigSource {
1025        if self.project.as_ref().is_some_and(|(_, k)| k.contains(key)) {
1026            ConfigSource::Project
1027        } else if self.personal.as_ref().is_some_and(|(_, k)| k.contains(key)) {
1028            ConfigSource::Personal
1029        } else {
1030            ConfigSource::Default
1031        }
1032    }
1033}
1034
1035/// `project` when the project file named this key, `personal` otherwise.
1036fn pick<T: Clone>(project_said_so: bool, project: &T, personal: T) -> T {
1037    if project_said_so {
1038        project.clone()
1039    } else {
1040        personal
1041    }
1042}
1043
1044/// Both files' declarations, the committed ones first, one entry per path.
1045///
1046/// Deduplicated by path rather than by whole entry: two files naming the same directory
1047/// with two different `rebuild` commands is one directory, and the committed one is the
1048/// answer — a teammate whose personal file still names last year's build script should
1049/// get the project's current one, not a second delete of the same path.
1050///
1051/// `exclude` unions the same way and from either file. It can only ever take a directory
1052/// out of play, so there is nothing for the committed file to protect by winning it —
1053/// and the person who needs one is by definition the person that file is wrong for.
1054fn merge_declarations(project: Option<&Prunable>, personal: Option<Prunable>) -> Option<Prunable> {
1055    let mut directories: Vec<DeclaredDir> =
1056        project.map(|p| p.directories.clone()).unwrap_or_default();
1057    let mut exclude: Vec<String> = project.map(|p| p.exclude.clone()).unwrap_or_default();
1058    let personal = personal.unwrap_or_default();
1059    for dir in personal.directories {
1060        if !directories.iter().any(|d| d.path == dir.path) {
1061            directories.push(dir);
1062        }
1063    }
1064    for path in personal.exclude {
1065        if !exclude.contains(&path) {
1066            exclude.push(path);
1067        }
1068    }
1069    if directories.is_empty() && exclude.is_empty() {
1070        None
1071    } else {
1072        Some(Prunable {
1073            directories,
1074            exclude,
1075        })
1076    }
1077}
1078
1079/// How an unset optional reads in the provenance table.
1080fn opt<T: std::fmt::Display>(value: &Option<T>) -> String {
1081    value
1082        .as_ref()
1083        .map_or_else(|| "not set".to_string(), ToString::to_string)
1084}
1085
1086/// Parse one config file into its values and the set of keys it actually spells out.
1087fn read_layer(path: &Path) -> Result<Option<(PerRepoConfig, HashSet<String>)>, String> {
1088    if !path.exists() {
1089        return Ok(None);
1090    }
1091    let content = fs::read_to_string(path).map_err(|e| format!("Failed to read file: {e}"))?;
1092    // `clean_path`, like every other path this tool shows. `Display` on a canonicalised
1093    // Windows path leaks the `\\?\` extended-length prefix into an error message the user
1094    // is being asked to act on.
1095    let cfg = serde_json::from_str::<PerRepoConfig>(&content)
1096        .map_err(|e| format!("Syntax error in `{}`: {e}", crate::output::clean_path(path)))?;
1097    // The same text just deserialized into a struct, so it is a JSON object and this
1098    // cannot fail; it is parsed a second time only because serde has by then thrown away
1099    // the difference between a key the file set and a key it defaulted.
1100    let keys = serde_json::from_str::<HashMap<String, serde_json::Value>>(&content)
1101        .map(|m| m.into_keys().collect())
1102        .unwrap_or_default();
1103    Ok(Some((cfg, keys)))
1104}
1105
1106/// One directory a prune pass deleted.
1107///
1108/// Enough to put it back and nothing more: which repository it belonged to, which
1109/// project inside that repository owned it, and who verified it. No file list — the
1110/// lockfile is the record of the contents, which is the whole premise of the tool.
1111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1112pub struct PrunedDir {
1113    /// Repository root the directory belonged to.
1114    pub repo_path: PathBuf,
1115    /// Repository-relative label, `/`-separated: `node_modules`, `frontend/node_modules`.
1116    pub bloat_dir: String,
1117    /// Adapter that verified and deleted it.
1118    pub adapter: String,
1119    /// Bytes reclaimed.
1120    pub size_freed: u64,
1121    /// The language runtime the deleted directory was built against — `"3.12"` for a
1122    /// virtual environment created by Python 3.12 — so a restore can rebuild on that
1123    /// interpreter instead of on whatever happens to be first on `PATH` today.
1124    ///
1125    /// `None` for every manager that pins its own toolchain in the lockfile (cargo, npm,
1126    /// go) and for anything pruned before 1.4.0. Optional rather than required for that
1127    /// second reason: a `registry.json` written by an older version has to keep loading.
1128    #[serde(default, skip_serializing_if = "Option::is_none")]
1129    pub runtime: Option<String>,
1130}
1131
1132/// What the most recent prune pass deleted, for `devp restore --last-run`.
1133///
1134/// Only passes that actually deleted something are recorded. A later run that frees
1135/// nothing — everything was active, everything was already clean — leaves this alone,
1136/// because "put back what you just took" should still mean the pass that took something.
1137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1138pub struct LastPrune {
1139    /// When the pass ran.
1140    pub at: DateTime<Utc>,
1141    /// Every directory it removed.
1142    pub dirs: Vec<PrunedDir>,
1143}
1144
1145/// A one-line summary of a completed prune pass, for `devp stats`.
1146///
1147/// Deliberately not a second copy of [`LastPrune`]. That one exists so
1148/// `devp restore --last-run` can put files back, so it carries the full directory list
1149/// and only ever describes the most recent pass. This one is a trend line — four numbers
1150/// per pass, bounded by [`constants::PRUNE_HISTORY_LIMIT`] — and could not restore
1151/// anything if it wanted to.
1152#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1153pub struct PruneRunSummary {
1154    /// When the pass ran.
1155    pub at: DateTime<Utc>,
1156    /// Bytes reclaimed by the pass.
1157    pub bytes_freed: u64,
1158    /// How many directories it removed.
1159    pub dirs_removed: usize,
1160    /// How many distinct repositories it touched.
1161    pub repos_touched: usize,
1162}
1163
1164/// The top-level registry structure persisted to disk.
1165#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1166pub struct Registry {
1167    /// Schema version for forward compatibility.
1168    pub version: String,
1169    /// Global settings.
1170    pub settings: Settings,
1171    /// Map of canonical repo paths to their metadata.
1172    pub repositories: HashMap<PathBuf, RepoEntry>,
1173    /// Total cumulative bytes freed historically across all prune passes.
1174    #[serde(default)]
1175    pub total_freed_bytes: u64,
1176    /// Total bytes given back by `devp caches clear`, ever, on this machine.
1177    ///
1178    /// Kept apart from `total_freed_bytes` rather than folded into it, because the two
1179    /// cost different things to undo. A prune deletes what a lockfile proves it can
1180    /// rebuild, and getting it back is one reinstall in one repository; emptying a shared
1181    /// cache costs a download in every project on the disk. Not keyed by repository for
1182    /// the same reason: a package manager's cache belongs to none of them.
1183    ///
1184    /// Recorded from 1.9.0 onward, so a registry written before then deserializes to
1185    /// zero and starts counting from the next clear.
1186    #[serde(default)]
1187    pub total_cache_freed_bytes: u64,
1188    /// How many prune passes have deleted something, ever.
1189    ///
1190    /// One per *pass*, not per repository and not per directory — a `devp run` that
1191    /// cleared eleven directories across four repositories counts once. Incremented in
1192    /// exactly one place, [`Registry::record_prune`], which is also where the pass is
1193    /// recorded for `devp restore --last-run`; keeping the two together is what stops
1194    /// them meaning different things depending on which command did the pruning.
1195    #[serde(default)]
1196    pub total_pruned_count: u64,
1197    /// List of repository paths added in the most recent init/link action (for devp undo).
1198    #[serde(default)]
1199    pub last_added_repos: Vec<PathBuf>,
1200    /// What the most recent prune pass deleted (for `devp restore --last-run`).
1201    #[serde(default)]
1202    pub last_prune: Option<LastPrune>,
1203    /// Summaries of recent prune passes, oldest first, for `devp stats`.
1204    ///
1205    /// Capped at [`constants::PRUNE_HISTORY_LIMIT`]. Recorded from 1.1.0 onward.
1206    #[serde(default)]
1207    pub prune_history: Vec<PruneRunSummary>,
1208    /// When the release check last ran, so it runs at most once every
1209    /// `UPDATE_CHECK_INTERVAL_DAYS` instead of on every command.
1210    #[serde(default)]
1211    pub last_update_check: Option<DateTime<Utc>>,
1212    /// The newest release seen by the last check, so the reminder survives until the
1213    /// user actually upgrades without needing the network again.
1214    #[serde(default)]
1215    pub latest_known_version: Option<String>,
1216    /// How fast each adapter has actually restored on this machine.
1217    ///
1218    /// Measured by `devp restore --last-run`, which is the one command that knows both
1219    /// how long a restore took and how many bytes it put back. Local only: nothing here
1220    /// is uploaded, compared against anyone else's machine, or used for anything except
1221    /// the estimate `devp status` prints. See `docs/PRIVACY.md`.
1222    #[serde(default)]
1223    pub restore_rates: BTreeMap<String, RestoreRate>,
1224}
1225
1226/// One adapter's observed restore throughput on this machine.
1227///
1228/// Totals rather than a stored average, because that is what lets a new measurement be
1229/// folded in without keeping the individual samples — and the individual samples are
1230/// per-repository, which is exactly the shape of data this tool has no business keeping.
1231#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1232pub struct RestoreRate {
1233    /// How many restores this average is made of.
1234    pub samples: u32,
1235    /// Bytes those restores put back.
1236    pub bytes: u64,
1237    /// Milliseconds they took.
1238    pub millis: u64,
1239}
1240
1241impl RestoreRate {
1242    /// Bytes per second, or `None` when the record cannot support the division.
1243    pub fn bytes_per_sec(&self) -> Option<f64> {
1244        (self.samples > 0 && self.millis > 0 && self.bytes > 0)
1245            .then(|| self.bytes as f64 * 1000.0 / self.millis as f64)
1246    }
1247}
1248
1249impl Default for Registry {
1250    fn default() -> Self {
1251        Self {
1252            version: "1.0".to_string(),
1253            settings: Settings::default(),
1254            repositories: HashMap::new(),
1255            total_freed_bytes: 0,
1256            total_cache_freed_bytes: 0,
1257            total_pruned_count: 0,
1258            last_added_repos: Vec::new(),
1259            last_prune: None,
1260            prune_history: Vec::new(),
1261            last_update_check: None,
1262            latest_known_version: None,
1263            restore_rates: BTreeMap::new(),
1264        }
1265    }
1266}
1267
1268impl Registry {
1269    /// Returns the path to the config directory (`~/.config/dev-prune/`).
1270    ///
1271    /// Uses the `dirs` crate to resolve the platform-specific config location:
1272    /// - Linux/macOS: `~/.config/dev-prune/`
1273    /// - Windows: `C:\Users\<user>\AppData\Roaming\dev-prune\` (or `~/.config/dev-prune/`)
1274    pub fn config_dir() -> Result<PathBuf> {
1275        if let Ok(override_dir) = std::env::var(constants::ENV_CONFIG_DIR_OVERRIDE) {
1276            return Ok(PathBuf::from(override_dir));
1277        }
1278        let base = dirs::config_dir().context("Could not determine config directory")?;
1279        Ok(base.join(constants::CONFIG_DIR_NAME))
1280    }
1281
1282    /// Returns the full path to the registry file.
1283    pub fn registry_path() -> Result<PathBuf> {
1284        Ok(Self::config_dir()?.join(constants::REGISTRY_FILENAME))
1285    }
1286
1287    /// Loads the registry from disk, or the defaults when there is nothing to load.
1288    ///
1289    /// Reading does not write. This used to persist the default registry on the way
1290    /// out, which made `devp --dry-run init` create the very file it had just promised
1291    /// not to write and gave `devp status --json` — documented as a pure read — a side
1292    /// effect on first use. Every command that actually changes something calls
1293    /// [`Registry::save`], and that creates the directory as needed.
1294    pub fn load() -> Result<Self> {
1295        Self::load_from(&Self::registry_path()?)
1296    }
1297
1298    /// Loads the registry from a specific path (for testing or custom locations).
1299    ///
1300    /// Non-persisting, exactly like [`Registry::load`], which is implemented on top of
1301    /// it. The two used to disagree — this one wrote the defaults out when the file was
1302    /// missing — which is the sort of difference that makes a test pass while the
1303    /// behaviour it stands in for is broken.
1304    pub fn load_from(path: &Path) -> Result<Self> {
1305        if !path.exists() {
1306            return Ok(Registry::default());
1307        }
1308        let contents = fs::read_to_string(path)
1309            .with_context(|| format!("Failed to read registry at {}", path.display()))?;
1310        serde_json::from_str(&contents)
1311            .with_context(|| format!("Failed to parse registry at {}", path.display()))
1312    }
1313
1314    /// Saves the registry to disk atomically (write to temp, then rename).
1315    pub fn save(&self) -> Result<()> {
1316        let path = Self::registry_path()?;
1317        self.save_to(&path)
1318    }
1319
1320    /// Saves the registry to a specific path (for testing or custom locations).
1321    pub fn save_to(&self, path: &Path) -> Result<()> {
1322        if let Some(parent) = path.parent() {
1323            fs::create_dir_all(parent)
1324                .with_context(|| format!("Failed to create config dir {}", parent.display()))?;
1325        }
1326        // Unique per process. A manual run and the scheduled daemon pass can save at the
1327        // same moment; with a shared `registry.json.tmp`, one process could rename the
1328        // other's half-written file into place as a torn, unparseable registry.
1329        let tmp_path = path.with_extension(format!("json.{}.tmp", std::process::id()));
1330        let contents =
1331            serde_json::to_string_pretty(self).context("Failed to serialize registry")?;
1332        {
1333            // `sync_all` before the rename, or the atomicity is only apparent: after a
1334            // power cut the rename can survive while the data does not, leaving the
1335            // registry as zero bytes — the one outcome this dance exists to prevent.
1336            use std::io::Write;
1337            let mut file = fs::File::create(&tmp_path)
1338                .with_context(|| format!("Failed to write temp registry {}", tmp_path.display()))?;
1339            file.write_all(contents.as_bytes())
1340                .with_context(|| format!("Failed to write temp registry {}", tmp_path.display()))?;
1341            file.sync_all()
1342                .with_context(|| format!("Failed to flush temp registry {}", tmp_path.display()))?;
1343        }
1344        fs::rename(&tmp_path, path)
1345            .with_context(|| format!("Failed to rename temp registry to {}", path.display()))?;
1346
1347        // A crash between write and rename strands that process's `.<pid>.tmp` forever.
1348        // Sweep siblings old enough that no live save can still own them.
1349        if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
1350            let prefix = format!("{}.", name.to_string_lossy());
1351            if let Ok(entries) = fs::read_dir(parent) {
1352                for entry in entries.flatten() {
1353                    let file_name = entry.file_name();
1354                    let file_name = file_name.to_string_lossy();
1355                    if file_name.starts_with(&prefix)
1356                        && file_name.ends_with(".tmp")
1357                        && entry
1358                            .metadata()
1359                            .and_then(|m| m.modified())
1360                            .ok()
1361                            .and_then(|t| t.elapsed().ok())
1362                            .is_some_and(|age| age.as_secs() > 3600)
1363                    {
1364                        let _ = fs::remove_file(entry.path());
1365                    }
1366                }
1367            }
1368        }
1369        Ok(())
1370    }
1371
1372    /// Adds a repository to the registry. Returns `true` if newly added, `false` if already present.
1373    pub fn add_repo(&mut self, path: PathBuf) -> bool {
1374        // The registry is keyed by path, so `./foo`, `foo/`, and the absolute form
1375        // would otherwise register as three separate repositories.
1376        let path = canonical_key(&path);
1377        if self.repositories.contains_key(&path) {
1378            return false;
1379        }
1380        self.repositories.insert(path, RepoEntry::new());
1381        true
1382    }
1383
1384    /// Record `identity` against a registered repository, and hand it the history of the
1385    /// entry it moved away from.
1386    ///
1387    /// Called after `add_repo` from both `link` and `init`. When exactly one registered
1388    /// path no longer exists on disk and carries the same root commit, that entry is the
1389    /// same repository at its old location: its `added_at`, prune history and settings
1390    /// move across and the dead row is removed. Two dead entries claiming one identity
1391    /// is a clone, not a move, so nothing is guessed — the caller says so instead.
1392    ///
1393    /// Also the backfill path. Entries registered before 1.4.0 have no identity, so
1394    /// nothing they do can be recognised as a move; re-registering them records one, and
1395    /// a single `devp init ~/code` backfills the whole registry.
1396    pub fn adopt_moved_entry(&mut self, path: &Path, identity: Option<String>) -> Adoption {
1397        let key = canonical_key(path);
1398        let Some(identity) = identity else {
1399            return Adoption::Nothing;
1400        };
1401
1402        let mut claimants: Vec<PathBuf> = self
1403            .repositories
1404            .iter()
1405            .filter(|(p, e)| {
1406                **p != key && e.identity.as_deref() == Some(identity.as_str()) && !p.exists()
1407            })
1408            .map(|(p, _)| p.clone())
1409            .collect();
1410        // Deterministic: two dead entries with one identity is a report, not a coin toss,
1411        // and the report must read the same twice.
1412        claimants.sort();
1413
1414        let adopted = match claimants.len() {
1415            0 => Adoption::Nothing,
1416            1 => Adoption::Moved(claimants.remove(0)),
1417            _ => Adoption::Ambiguous,
1418        };
1419
1420        if let Adoption::Moved(ref old) = adopted
1421            && let Some(previous) = self.repositories.remove(old)
1422        {
1423            if let Some(entry) = self.repositories.get_mut(&key) {
1424                // Everything the old path had earned. `enabled` and the idle override
1425                // come across too: a repository the user had switched off did not switch
1426                // itself back on by being moved.
1427                entry.added_at = previous.added_at;
1428                entry.last_pruned_at = previous.last_pruned_at;
1429                entry.override_idle_days = previous.override_idle_days;
1430                entry.enabled = previous.enabled;
1431                entry.total_freed_bytes = previous.total_freed_bytes;
1432            }
1433            self.last_added_repos.retain(|p| p != old);
1434        }
1435
1436        if let Some(entry) = self.repositories.get_mut(&key) {
1437            entry.identity = Some(identity);
1438        }
1439        adopted
1440    }
1441
1442    /// Whether a registered repository still has no recorded identity.
1443    ///
1444    /// The global Git hook runs `devp link --quiet` on every commit, and backfilling
1445    /// unconditionally would shell out to git and rewrite the registry once per commit
1446    /// forever. This makes it once per repository.
1447    pub fn needs_identity(&self, path: &Path) -> bool {
1448        self.repositories
1449            .get(&canonical_key(path))
1450            .is_some_and(|e| e.identity.is_none())
1451    }
1452
1453    /// Removes a repository from the registry. Returns `true` if it was present.
1454    ///
1455    /// A repository that has been deleted from disk cannot be canonicalised any more,
1456    /// so `canonical_key` falls back to the path as typed — which never equals the
1457    /// canonical key it was registered under (on Windows those carry the `\\?\`
1458    /// prefix). Unlinking a deleted repository is the most ordinary reason to unlink
1459    /// at all, so a direct miss falls back to a lexical comparison.
1460    pub fn remove_repo(&mut self, path: &Path) -> bool {
1461        let target = lexical_absolute(path);
1462        let removed = if self.repositories.remove(&canonical_key(path)).is_some() {
1463            true
1464        } else {
1465            let found = self
1466                .repositories
1467                .keys()
1468                .find(|k| loose_path_eq(k, &target))
1469                .cloned();
1470            found.is_some_and(|k| self.repositories.remove(&k).is_some())
1471        };
1472        if removed {
1473            // The undo list stores the canonical `\\?\`-prefixed spelling, while a
1474            // deleted directory can only be named lexically — strict equality misses,
1475            // and the next `devp undo` "reverts" by removing nothing.
1476            self.last_added_repos.retain(|p| !loose_path_eq(p, &target));
1477        }
1478        removed
1479    }
1480
1481    // Removed: `repo_paths` and `effective_idle_days`.
1482    //
1483    // Neither had a caller outside this file's own tests. `effective_idle_days` had also
1484    // drifted from the rule the engine actually applies: it looked the repository up by
1485    // the path as given, where every write to `repositories` goes through
1486    // `canonical_key`, so `devp`'s own relative paths would have missed the entry and
1487    // silently returned the global threshold instead of the repository's override.
1488
1489    /// Credit `bytes_freed` to one repository, and to the machine-wide total.
1490    ///
1491    /// Safe to call once per repository or once per directory — every figure it touches
1492    /// is either a sum or a timestamp, so the two styles agree. Counting *passes* is
1493    /// deliberately not done here for exactly that reason; that lives in
1494    /// [`Registry::record_prune`], which is called once per pass.
1495    pub fn mark_pruned(&mut self, path: &Path, bytes_freed: u64) {
1496        // Same rule as every other accessor: the map is keyed by `canonical_key`, so a
1497        // raw lookup would silently skip the per-repo credit for a relative or
1498        // differently-spelled path while still growing the machine-wide total.
1499        if let Some(entry) = self.repositories.get_mut(&canonical_key(path)) {
1500            entry.last_pruned_at = Some(Utc::now());
1501            entry.total_freed_bytes += bytes_freed;
1502        }
1503        self.total_freed_bytes += bytes_freed;
1504    }
1505
1506    /// Credit `bytes` to the machine's running cache-clear total.
1507    pub fn record_cache_clear(&mut self, bytes: u64) {
1508        self.total_cache_freed_bytes += bytes;
1509    }
1510
1511    /// Record what a prune pass deleted, replacing any earlier record.
1512    ///
1513    /// A pass that deleted nothing is not a pass worth remembering, so an empty list is
1514    /// ignored rather than stored — otherwise `devp run` on an already-clean machine
1515    /// would quietly throw away the record of the run the user actually wants back.
1516    ///
1517    /// This is the one place a prune pass is counted. It sets [`Registry::last_prune`],
1518    /// appends a [`PruneRunSummary`] to [`Registry::prune_history`] and bumps
1519    /// [`Registry::total_pruned_count`], because "a pass happened and it deleted things"
1520    /// is exactly the condition all three describe. Splitting them across call sites is
1521    /// how the counter previously came to mean repositories in `devp run` and directories
1522    /// in the `devp status` dashboard.
1523    /// Fold one measured restore into an adapter's running average.
1524    ///
1525    /// Ignores anything too quick to have been real work — see
1526    /// [`constants::RESTORE_RATE_MIN_MILLIS`] — because a manager that found everything
1527    /// still in its cache returns in a moment and would teach a throughput no cold
1528    /// restore can reach. That is the difference between an estimate that is optimistic
1529    /// and one that is wrong.
1530    pub fn record_restore(&mut self, adapter: &str, bytes: u64, millis: u64) {
1531        if bytes == 0 || millis < constants::RESTORE_RATE_MIN_MILLIS {
1532            return;
1533        }
1534        let rate = self.restore_rates.entry(adapter.to_string()).or_default();
1535        if rate.samples >= constants::RESTORE_RATE_SAMPLE_CAP {
1536            rate.samples /= 2;
1537            rate.bytes /= 2;
1538            rate.millis /= 2;
1539        }
1540        rate.samples += 1;
1541        rate.bytes = rate.bytes.saturating_add(bytes);
1542        rate.millis = rate.millis.saturating_add(millis);
1543    }
1544
1545    /// How long putting back `by_adapter` would take, from what this machine has
1546    /// measured.
1547    ///
1548    /// Returns the seconds and the bytes those seconds account for. Anything from an
1549    /// adapter that has never been timed here is left out of both, so a caller can say
1550    /// how much of the estimate is actually covered rather than quietly quoting a
1551    /// number for half the work. `None` when nothing is covered at all — an estimate
1552    /// with no measurement behind it is a guess, and this command does not print
1553    /// guesses.
1554    pub fn estimate_restore(&self, by_adapter: &[(String, u64)]) -> Option<(f64, u64)> {
1555        let mut secs = 0.0;
1556        let mut covered = 0u64;
1557        for (adapter, bytes) in by_adapter {
1558            let Some(rate) = self
1559                .restore_rates
1560                .get(adapter)
1561                .and_then(|r| r.bytes_per_sec())
1562            else {
1563                continue;
1564            };
1565            secs += *bytes as f64 / rate;
1566            covered = covered.saturating_add(*bytes);
1567        }
1568        (covered > 0).then_some((secs, covered))
1569    }
1570
1571    pub fn record_prune(&mut self, dirs: Vec<PrunedDir>) {
1572        self.record_prune_progress(Utc::now(), dirs);
1573    }
1574
1575    /// Record a pass's progress mid-flight, superseding this same pass's earlier record.
1576    ///
1577    /// `at` identifies the pass: a repeated call with the same timestamp replaces the
1578    /// history entry and `last_prune` it wrote before, rather than counting a second
1579    /// pass. This exists so a long pass can persist after every repository — a crash
1580    /// half-way through used to leave `devp restore --last-run` pointing at the
1581    /// *previous* pass, offering to reinstall directories that were never deleted while
1582    /// saying nothing about the ones that were.
1583    pub fn record_prune_progress(&mut self, at: DateTime<Utc>, dirs: Vec<PrunedDir>) {
1584        if dirs.is_empty() {
1585            return;
1586        }
1587        if self.prune_history.last().map(|s| s.at) == Some(at) {
1588            self.prune_history.pop();
1589        } else {
1590            self.total_pruned_count += 1;
1591        }
1592
1593        self.prune_history.push(PruneRunSummary {
1594            at,
1595            bytes_freed: dirs.iter().map(|d| d.size_freed).sum(),
1596            dirs_removed: dirs.len(),
1597            repos_touched: dirs
1598                .iter()
1599                .map(|d| &d.repo_path)
1600                .collect::<HashSet<_>>()
1601                .len(),
1602        });
1603        // Oldest first, so the overflow comes off the front.
1604        if self.prune_history.len() > constants::PRUNE_HISTORY_LIMIT {
1605            let excess = self.prune_history.len() - constants::PRUNE_HISTORY_LIMIT;
1606            self.prune_history.drain(..excess);
1607        }
1608
1609        self.last_prune = Some(LastPrune { at, dirs });
1610    }
1611
1612    /// Returns the number of registered repositories.
1613    pub fn repo_count(&self) -> usize {
1614        self.repositories.len()
1615    }
1616}
1617
1618#[cfg(test)]
1619mod tests {
1620    use super::*;
1621    use tempfile::TempDir;
1622
1623    fn test_registry_path(dir: &TempDir) -> PathBuf {
1624        dir.path().join("dev-prune").join("registry.json")
1625    }
1626
1627    fn a_pruned_dir(label: &str) -> PrunedDir {
1628        PrunedDir {
1629            repo_path: PathBuf::from("/repo"),
1630            bloat_dir: label.to_string(),
1631            adapter: "npm".to_string(),
1632            size_freed: 42,
1633            runtime: None,
1634        }
1635    }
1636
1637    #[test]
1638    fn cache_clears_accumulate_separately_from_prunes() {
1639        let dir = TempDir::new().expect("temp dir");
1640        let path = test_registry_path(&dir);
1641
1642        let mut registry = Registry::default();
1643        registry.mark_pruned(Path::new("/repo"), 42);
1644        registry.record_cache_clear(6_000_000_000);
1645        registry.record_cache_clear(2_000_000_000);
1646        registry.save_to(&path).expect("saved");
1647
1648        let reloaded = Registry::load_from(&path).expect("reloaded");
1649        assert_eq!(reloaded.total_cache_freed_bytes, 8_000_000_000);
1650        // The prune total is untouched by either clear. `devp stats` prints them as two
1651        // lines because emptying a shared cache is not the same promise as pruning one
1652        // repository, and one combined figure would answer neither question.
1653        assert_eq!(reloaded.total_freed_bytes, 42);
1654    }
1655
1656    #[test]
1657    fn a_registry_written_before_1_9_0_reads_the_cache_total_as_zero() {
1658        // The `#[serde(default)]`, exercised. Without it every registry on every machine
1659        // that upgraded would fail to parse, and `devp stats` would exit 1.
1660        let dir = TempDir::new().expect("temp dir");
1661        let path = test_registry_path(&dir);
1662        std::fs::create_dir_all(path.parent().expect("parent")).expect("config dir");
1663
1664        // Built by removing the one key 1.8.0 did not write, rather than hand-typed, so
1665        // this stays a test of the `default` and not of whichever unrelated field is
1666        // added to `Settings` next.
1667        let mut older = Registry {
1668            total_freed_bytes: 99,
1669            ..Default::default()
1670        };
1671        older.record_cache_clear(500);
1672        let mut document: serde_json::Value =
1673            serde_json::from_str(&serde_json::to_string(&older).expect("serialized"))
1674                .expect("re-parsed");
1675        assert!(
1676            document
1677                .as_object_mut()
1678                .expect("an object")
1679                .remove("total_cache_freed_bytes")
1680                .is_some(),
1681            "the field this test is about must be in the document to begin with"
1682        );
1683        std::fs::write(&path, document.to_string()).expect("wrote an older registry");
1684
1685        let registry = Registry::load_from(&path).expect("an older registry still parses");
1686        assert_eq!(registry.total_cache_freed_bytes, 0);
1687        assert_eq!(registry.total_freed_bytes, 99);
1688    }
1689
1690    #[test]
1691    fn a_setting_from_a_newer_version_survives_this_version_saving() {
1692        // The `#[serde(flatten)]` catch-all, exercised. A registry written by a newer
1693        // dev-prune can hold settings keys this build has never heard of, and every
1694        // save rewrites the whole `settings` object — so before the catch-all, one
1695        // run of an older binary (a pinned CI image, a machine `version_lock` holds
1696        // back) silently erased the newer binary's configuration.
1697        let dir = TempDir::new().expect("temp dir");
1698        let path = test_registry_path(&dir);
1699        std::fs::create_dir_all(path.parent().expect("parent")).expect("config dir");
1700
1701        let mut document: serde_json::Value =
1702            serde_json::from_str(&serde_json::to_string(&Registry::default()).expect("serialized"))
1703                .expect("re-parsed");
1704        document["settings"]["from_the_future"] = serde_json::json!({ "answer": 42 });
1705        std::fs::write(&path, document.to_string()).expect("wrote a newer registry");
1706
1707        let loaded = Registry::load_from(&path).expect("a newer registry still parses");
1708        loaded.save_to(&path).expect("saved");
1709
1710        let saved: serde_json::Value =
1711            serde_json::from_str(&std::fs::read_to_string(&path).expect("read back"))
1712                .expect("parsed");
1713        assert_eq!(saved["settings"]["from_the_future"]["answer"], 42);
1714    }
1715
1716    #[test]
1717    fn a_prune_that_deleted_nothing_does_not_erase_the_last_one() {
1718        // Otherwise a second `devp run` on an already-clean machine throws away the
1719        // record of the pass the user actually wants to undo.
1720        let mut registry = Registry::default();
1721        registry.record_prune(vec![a_pruned_dir("node_modules")]);
1722        let recorded = registry.last_prune.clone().expect("first pass recorded");
1723
1724        registry.record_prune(Vec::new());
1725
1726        assert_eq!(registry.last_prune, Some(recorded));
1727    }
1728
1729    #[test]
1730    fn a_later_prune_replaces_the_record() {
1731        let mut registry = Registry::default();
1732        registry.record_prune(vec![a_pruned_dir("node_modules")]);
1733        registry.record_prune(vec![a_pruned_dir("frontend/node_modules")]);
1734
1735        let dirs = registry.last_prune.unwrap().dirs;
1736        assert_eq!(dirs.len(), 1);
1737        assert_eq!(dirs[0].bloat_dir, "frontend/node_modules");
1738    }
1739
1740    #[test]
1741    fn the_last_prune_record_survives_a_save_and_load() {
1742        // `restore --last-run` reads it out of a file written by a process that has
1743        // already exited, so the round trip is the whole feature.
1744        let dir = TempDir::new().unwrap();
1745        let path = test_registry_path(&dir);
1746
1747        let mut registry = Registry::default();
1748        registry.record_prune(vec![a_pruned_dir("frontend/node_modules")]);
1749        registry.save_to(&path).unwrap();
1750
1751        let loaded = Registry::load_from(&path).unwrap();
1752        assert_eq!(loaded.last_prune, registry.last_prune);
1753    }
1754
1755    #[test]
1756    fn a_registry_written_before_the_field_existed_still_loads() {
1757        // The registry on disk predates `last_prune`; a missing key means "no pass
1758        // recorded", not a parse failure that would lock the user out of their config.
1759        let dir = TempDir::new().unwrap();
1760        let path = test_registry_path(&dir);
1761        fs::create_dir_all(path.parent().unwrap()).unwrap();
1762        fs::write(
1763            &path,
1764            r#"{"version":"1.0","settings":{"idle_days":15,"check_interval_days":2,
1765               "auto_daemon":true},"repositories":{}}"#,
1766        )
1767        .unwrap();
1768
1769        let loaded = Registry::load_from(&path).unwrap();
1770        assert_eq!(loaded.last_prune, None);
1771    }
1772
1773    #[test]
1774    fn a_leading_tilde_becomes_the_home_directory() {
1775        // The whole reason this exists: PowerShell hands `devp init ~/Code` straight
1776        // through, so without expansion the registry gains a repository at `.\~\Code`.
1777        let home = dirs::home_dir().expect("test host has a home directory");
1778
1779        assert_eq!(expand_tilde("~"), home.to_string_lossy());
1780        assert_eq!(
1781            expand_tilde("~/Code"),
1782            home.join("Code").to_string_lossy(),
1783            "forward slash, as typed in every shell"
1784        );
1785        assert_eq!(
1786            expand_tilde("~\\Code"),
1787            home.join("Code").to_string_lossy(),
1788            "backslash, as typed in PowerShell"
1789        );
1790    }
1791
1792    #[test]
1793    fn a_tilde_that_is_not_a_home_reference_is_left_alone() {
1794        // `~alice` is another user's home in shell syntax and cannot be resolved
1795        // portably; `~backup` and `./~tmp` are ordinary directory names. Rewriting any
1796        // of them would silently point the user at the wrong directory.
1797        for raw in ["~alice/Code", "~backup", "./~tmp", "Code~", "", "."] {
1798            assert_eq!(expand_tilde(raw), raw, "{raw} must survive untouched");
1799        }
1800    }
1801
1802    #[test]
1803    fn test_default_settings() {
1804        let settings = Settings::default();
1805        assert_eq!(settings.idle_days, 15);
1806        assert_eq!(settings.check_interval_days, 2);
1807        // On by default: dev-prune installs its own integrations, once per version,
1808        // and only the ones it finds missing.
1809        assert!(settings.auto_daemon);
1810        assert!(settings.auto_hooks);
1811        assert!(settings.auto_setup);
1812    }
1813
1814    #[test]
1815    fn settings_written_before_the_automation_toggles_existed_still_load() {
1816        // Real registries on disk predate `auto_hooks` / `auto_setup`; an upgrade must
1817        // read them rather than fail to parse and lose every registered repository.
1818        let json = r#"{
1819            "idle_days": 30,
1820            "check_interval_days": 2,
1821            "auto_daemon": false
1822        }"#;
1823        let settings: Settings = serde_json::from_str(json).unwrap();
1824        assert_eq!(settings.idle_days, 30);
1825        assert!(!settings.auto_daemon, "an explicit opt-out is preserved");
1826        assert!(settings.auto_hooks, "a missing key takes the default");
1827        assert!(settings.auto_setup);
1828    }
1829
1830    #[test]
1831    fn test_default_registry() {
1832        let registry = Registry::default();
1833        assert_eq!(registry.version, "1.0");
1834        assert_eq!(registry.settings, Settings::default());
1835        assert!(registry.repositories.is_empty());
1836    }
1837
1838    #[test]
1839    fn test_repo_entry_new() {
1840        let entry = RepoEntry::new();
1841        assert!(entry.enabled);
1842        assert!(entry.last_pruned_at.is_none());
1843        assert!(entry.override_idle_days.is_none());
1844    }
1845
1846    #[test]
1847    fn test_save_and_load() {
1848        let tmp = TempDir::new().unwrap();
1849        let path = test_registry_path(&tmp);
1850
1851        let mut registry = Registry::default();
1852        registry.add_repo(PathBuf::from("/test/repo"));
1853        registry.save_to(&path).unwrap();
1854
1855        let loaded = Registry::load_from(&path).unwrap();
1856        assert_eq!(loaded.repo_count(), 1);
1857        assert!(
1858            loaded
1859                .repositories
1860                .contains_key(&PathBuf::from("/test/repo"))
1861        );
1862    }
1863
1864    #[test]
1865    fn loading_a_missing_registry_yields_the_defaults_and_writes_nothing() {
1866        let tmp = TempDir::new().unwrap();
1867        let path = test_registry_path(&tmp);
1868
1869        let loaded = Registry::load_from(&path).unwrap();
1870        assert_eq!(loaded, Registry::default());
1871        // Reading is not writing. `devp --dry-run` and `devp status --json` both promise
1872        // to leave the disk alone, and both start by loading the registry.
1873        assert!(!path.exists(), "loading the registry created it");
1874    }
1875
1876    #[test]
1877    fn test_add_repo_returns_true_for_new() {
1878        let mut registry = Registry::default();
1879        assert!(registry.add_repo(PathBuf::from("/test/repo")));
1880    }
1881
1882    #[test]
1883    fn test_add_repo_returns_false_for_duplicate() {
1884        let mut registry = Registry::default();
1885        registry.add_repo(PathBuf::from("/test/repo"));
1886        assert!(!registry.add_repo(PathBuf::from("/test/repo")));
1887    }
1888
1889    #[test]
1890    fn test_remove_repo() {
1891        let mut registry = Registry::default();
1892        registry.add_repo(PathBuf::from("/test/repo"));
1893        assert!(registry.remove_repo(Path::new("/test/repo")));
1894        assert!(!registry.remove_repo(Path::new("/test/repo")));
1895        assert_eq!(registry.repo_count(), 0);
1896    }
1897
1898    /// macOS puts temp trees behind `/var` → `/private/var`, so a repo registered
1899    /// through the symlink is keyed under the real path — and once deleted, the
1900    /// symlinked spelling cannot be canonicalised whole. The lexical fallback must
1901    /// resolve the surviving parent, or unlink reports "not registered" for a
1902    /// directory the user is looking at in their own prompt.
1903    #[cfg(unix)]
1904    #[test]
1905    fn a_deleted_repo_named_through_a_symlinked_parent_still_unlinks() {
1906        let tmp = TempDir::new().unwrap();
1907        let real_parent = tmp.path().join("real");
1908        std::fs::create_dir(&real_parent).unwrap();
1909        let alias = tmp.path().join("alias");
1910        std::os::unix::fs::symlink(&real_parent, &alias).unwrap();
1911
1912        let repo = real_parent.join("repo");
1913        std::fs::create_dir(&repo).unwrap();
1914        let mut registry = Registry::default();
1915        registry.add_repo(alias.join("repo"));
1916        std::fs::remove_dir(&repo).unwrap();
1917
1918        assert!(registry.remove_repo(&alias.join("repo")));
1919        assert_eq!(registry.repo_count(), 0);
1920    }
1921
1922    #[test]
1923    fn test_mark_pruned() {
1924        let mut registry = Registry::default();
1925        registry.add_repo(PathBuf::from("/test/repo"));
1926        assert!(
1927            registry.repositories[&PathBuf::from("/test/repo")]
1928                .last_pruned_at
1929                .is_none()
1930        );
1931        registry.mark_pruned(Path::new("/test/repo"), 1024);
1932        assert!(
1933            registry.repositories[&PathBuf::from("/test/repo")]
1934                .last_pruned_at
1935                .is_some()
1936        );
1937        assert_eq!(registry.total_freed_bytes, 1024);
1938        // Not the pass counter — that is `record_prune`'s job, once per pass.
1939        assert_eq!(registry.total_pruned_count, 0);
1940    }
1941
1942    #[test]
1943    fn a_pass_is_counted_once_however_much_it_deleted() {
1944        // The counter is published as `prune_passes`, and it used to be incremented once
1945        // per repository by `devp run` and once per *directory* by the status dashboard,
1946        // so the same work produced a different number depending on where it started.
1947        let mut registry = Registry::default();
1948        registry.add_repo(PathBuf::from("/repo"));
1949
1950        registry.mark_pruned(Path::new("/repo"), 1024);
1951        registry.mark_pruned(Path::new("/repo"), 1024);
1952        registry.record_prune(vec![
1953            a_pruned_dir("node_modules"),
1954            a_pruned_dir("frontend/node_modules"),
1955        ]);
1956
1957        assert_eq!(registry.total_pruned_count, 1);
1958
1959        registry.record_prune(vec![a_pruned_dir("target")]);
1960        assert_eq!(registry.total_pruned_count, 2);
1961
1962        // A pass that deleted nothing is not a pass.
1963        registry.record_prune(Vec::new());
1964        assert_eq!(registry.total_pruned_count, 2);
1965    }
1966
1967    #[test]
1968    fn mark_pruned_credits_the_repo_under_its_canonical_key() {
1969        // On Windows, `canonicalize` yields a `\\?\`-prefixed path, so a registry keyed
1970        // by the canonical form and a `mark_pruned` looking up the raw form would miss —
1971        // growing the machine-wide total while the repository's own figure stayed zero.
1972        let tmp = TempDir::new().unwrap();
1973        let raw = tmp.path().to_path_buf();
1974
1975        let mut registry = Registry::default();
1976        registry.add_repo(raw.clone());
1977        registry.mark_pruned(&raw, 1024);
1978
1979        let entry = &registry.repositories[&canonical_key(&raw)];
1980        assert_eq!(entry.total_freed_bytes, 1024);
1981        assert!(entry.last_pruned_at.is_some());
1982        assert_eq!(registry.total_freed_bytes, 1024);
1983    }
1984
1985    #[test]
1986    fn each_repository_accumulates_its_own_total() {
1987        // `devp stats` ranks repositories against each other, so the per-repo figure has
1988        // to be a running total and not the size of the most recent pass.
1989        let mut registry = Registry::default();
1990        registry.add_repo(PathBuf::from("/test/repo"));
1991        registry.add_repo(PathBuf::from("/test/other"));
1992
1993        registry.mark_pruned(Path::new("/test/repo"), 1024);
1994        registry.mark_pruned(Path::new("/test/repo"), 2048);
1995        registry.mark_pruned(Path::new("/test/other"), 512);
1996
1997        assert_eq!(
1998            registry.repositories[&PathBuf::from("/test/repo")].total_freed_bytes,
1999            3072
2000        );
2001        assert_eq!(
2002            registry.repositories[&PathBuf::from("/test/other")].total_freed_bytes,
2003            512
2004        );
2005        assert_eq!(registry.total_freed_bytes, 3584);
2006    }
2007
2008    #[test]
2009    fn the_prune_history_summarises_the_pass() {
2010        let mut registry = Registry::default();
2011        registry.record_prune(vec![
2012            a_pruned_dir("node_modules"),
2013            a_pruned_dir("frontend/node_modules"),
2014        ]);
2015
2016        let summary = registry.prune_history.last().expect("pass summarised");
2017        assert_eq!(summary.bytes_freed, 84);
2018        assert_eq!(summary.dirs_removed, 2);
2019        // Both fixtures live under `/repo`, so this is one repository, not two.
2020        assert_eq!(summary.repos_touched, 1);
2021    }
2022
2023    #[test]
2024    fn the_prune_history_is_capped_and_drops_the_oldest() {
2025        // The registry is rewritten in full on every save, so an uncapped list would grow
2026        // the file forever on a machine running the scheduled pass.
2027        let mut registry = Registry::default();
2028        for _ in 0..constants::PRUNE_HISTORY_LIMIT + 5 {
2029            registry.record_prune(vec![a_pruned_dir("node_modules")]);
2030        }
2031
2032        assert_eq!(registry.prune_history.len(), constants::PRUNE_HISTORY_LIMIT);
2033        let first = registry.prune_history.first().unwrap().at;
2034        let last = registry.prune_history.last().unwrap().at;
2035        assert!(first <= last, "oldest first");
2036    }
2037
2038    #[test]
2039    fn test_repo_count() {
2040        let mut registry = Registry::default();
2041        assert_eq!(registry.repo_count(), 0);
2042        registry.add_repo(PathBuf::from("/a"));
2043        registry.add_repo(PathBuf::from("/b"));
2044        assert_eq!(registry.repo_count(), 2);
2045    }
2046
2047    #[test]
2048    fn a_local_schema_uri_has_exactly_three_slashes_on_either_platform() {
2049        assert_eq!(
2050            file_uri("/home/dev/.config/dev-prune/bin/devprune.schema.json"),
2051            "file:///home/dev/.config/dev-prune/bin/devprune.schema.json"
2052        );
2053        assert_eq!(
2054            file_uri("C:/Users/dev/AppData/Roaming/dev-prune/bin/devprune.schema.json"),
2055            "file:///C:/Users/dev/AppData/Roaming/dev-prune/bin/devprune.schema.json"
2056        );
2057    }
2058
2059    #[test]
2060    fn a_broken_per_repo_config_is_an_error_rather_than_an_absent_one() {
2061        // The distinction the whole tool leans on: "no config" means take the defaults,
2062        // "unreadable config" means refuse — never overwrite, never prune on a guess.
2063        let tmp = TempDir::new().unwrap();
2064        let repo = tmp.path();
2065        assert_eq!(PerRepoConfig::load_with_diagnostics(repo), Ok(None));
2066
2067        fs::write(
2068            repo.join(constants::PER_REPO_CONFIG_FILE),
2069            r#"{ "ignore": true, }"#,
2070        )
2071        .unwrap();
2072        let err = PerRepoConfig::load_with_diagnostics(repo).unwrap_err();
2073        assert!(err.contains("Syntax error"), "{err}");
2074
2075        fs::write(
2076            repo.join(constants::PER_REPO_CONFIG_FILE),
2077            r#"{ "ignore": true }"#,
2078        )
2079        .unwrap();
2080        assert!(
2081            PerRepoConfig::load_with_diagnostics(repo)
2082                .unwrap()
2083                .unwrap()
2084                .ignore
2085        );
2086    }
2087
2088    /// A typo'd key must be pointed out and must not refuse the file: the same
2089    /// tolerance that lets a newer dev-prune's file load in an older one is what makes
2090    /// the typo silent everywhere else.
2091    #[test]
2092    fn a_typo_key_is_reported_but_never_refused() {
2093        let tmp = TempDir::new().unwrap();
2094        let repo = tmp.path();
2095        fs::write(
2096            repo.join(constants::PER_REPO_CONFIG_FILE),
2097            r#"{ "ignore": true, "idle_days": 30, "prunable": { "directores": [] } }"#,
2098        )
2099        .unwrap();
2100
2101        let cfg = PerRepoConfig::load_with_diagnostics(repo).unwrap().unwrap();
2102        assert!(cfg.ignore, "the keys the file spells right still apply");
2103
2104        let unknown: Vec<String> = PerRepoConfig::unknown_keys(repo)
2105            .into_iter()
2106            .map(|(_, k)| k)
2107            .collect();
2108        assert_eq!(unknown, vec!["idle_days", "prunable.directores"]);
2109    }
2110
2111    /// Drift guard: a field added to [`PerRepoConfig`] without extending the known-key
2112    /// list would make doctor warn about a key the tool itself wrote.
2113    #[test]
2114    fn every_key_the_type_serializes_is_a_known_key() {
2115        let tmp = TempDir::new().unwrap();
2116        let repo = tmp.path();
2117        let full = PerRepoConfig {
2118            project_name: Some("x".into()),
2119            ignore: true,
2120            disable_hooks: true,
2121            disable_daemon: true,
2122            override_idle_days: Some(1),
2123            min_size_mb: Some(1),
2124            scan_depth: Some(1),
2125            prunable: Some(Prunable {
2126                directories: vec![DeclaredDir {
2127                    path: "scratch".into(),
2128                    rebuild: "echo not needed".into(),
2129                    why: Some("scratch".into()),
2130                }],
2131                exclude: vec!["dist".into()],
2132            }),
2133            ..PerRepoConfig::default()
2134        };
2135        fs::write(
2136            repo.join(constants::PER_REPO_CONFIG_FILE),
2137            serde_json::to_string_pretty(&full).unwrap(),
2138        )
2139        .unwrap();
2140        assert_eq!(PerRepoConfig::unknown_keys(repo), Vec::new());
2141    }
2142
2143    #[test]
2144    fn the_project_file_wins_the_keys_it_names_and_no_others() {
2145        let tmp = TempDir::new().unwrap();
2146        let repo = tmp.path();
2147
2148        // A team file that says one thing, and a personal file that says three.
2149        fs::write(
2150            repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2151            r#"{ "ignore": true }"#,
2152        )
2153        .unwrap();
2154        fs::write(
2155            repo.join(constants::PER_REPO_CONFIG_FILE),
2156            r#"{ "ignore": false, "scan_depth": 12, "project_name": "mine" }"#,
2157        )
2158        .unwrap();
2159
2160        let cfg = PerRepoConfig::load_with_diagnostics(repo).unwrap().unwrap();
2161        assert!(cfg.ignore, "the committed file decides the key it names");
2162        assert_eq!(
2163            cfg.scan_depth,
2164            Some(12),
2165            "and decides nothing about the keys it does not"
2166        );
2167        assert_eq!(cfg.project_name.as_deref(), Some("mine"));
2168
2169        let layers = RepoConfigLayers::load(repo).unwrap();
2170        assert_eq!(layers.source_of("ignore"), ConfigSource::Project);
2171        assert_eq!(layers.source_of("scan_depth"), ConfigSource::Personal);
2172        assert_eq!(layers.source_of("min_size_mb"), ConfigSource::Default);
2173    }
2174
2175    #[test]
2176    fn a_serde_default_is_not_a_project_decision() {
2177        // The whole reason the key set is carried around. Serde fills `ignore` in as
2178        // `false` for a file that never mentioned it, and a merge that could not tell
2179        // those apart would have every project file silently un-ignoring repositories
2180        // its author had said nothing about.
2181        let tmp = TempDir::new().unwrap();
2182        let repo = tmp.path();
2183        fs::write(
2184            repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2185            r#"{ "scan_depth": 3 }"#,
2186        )
2187        .unwrap();
2188        fs::write(
2189            repo.join(constants::PER_REPO_CONFIG_FILE),
2190            r#"{ "ignore": true }"#,
2191        )
2192        .unwrap();
2193
2194        let cfg = PerRepoConfig::load_with_diagnostics(repo).unwrap().unwrap();
2195        assert!(cfg.ignore);
2196        assert_eq!(cfg.scan_depth, Some(3));
2197    }
2198
2199    #[test]
2200    fn a_broken_project_file_is_named_and_never_healed_in_place() {
2201        let tmp = TempDir::new().unwrap();
2202        let repo = tmp.path();
2203        fs::write(
2204            repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2205            r#"{ "ignore": true, }"#,
2206        )
2207        .unwrap();
2208
2209        // Same refusal as a broken personal file: nothing reads a config it cannot
2210        // parse, whichever file it was in.
2211        assert!(
2212            PerRepoConfig::load_with_diagnostics(repo)
2213                .unwrap_err()
2214                .contains("Syntax error")
2215        );
2216
2217        // But the repair path has to know which file, because one of them is tracked.
2218        let broken = PerRepoConfig::broken_files(repo);
2219        assert_eq!(broken.len(), 1);
2220        assert_eq!(broken[0].0, constants::PROJECT_REPO_CONFIG_FILE);
2221    }
2222
2223    #[test]
2224    fn a_new_project_file_is_visible_to_git_and_decides_nothing() {
2225        let tmp = TempDir::new().unwrap();
2226        let repo = tmp.path();
2227        fs::create_dir_all(repo.join(".git").join("info")).unwrap();
2228        fs::write(
2229            repo.join(constants::PER_REPO_CONFIG_FILE),
2230            r#"{ "ignore": true, "scan_depth": 9 }"#,
2231        )
2232        .unwrap();
2233
2234        write_project_starter(repo).unwrap();
2235
2236        // `save_to_repo` hides what it writes; this one must not, or the file is a
2237        // per-machine file with a misleading name.
2238        let exclude = repo.join(".git").join("info").join("exclude");
2239        let listed = fs::read_to_string(&exclude).unwrap_or_default();
2240        assert!(
2241            !listed.contains(constants::PROJECT_REPO_CONFIG_FILE),
2242            "the committed file must never be excluded: {listed}"
2243        );
2244
2245        // And creating it must not have quietly taken over the file beside it. A
2246        // serialized `PerRepoConfig::default()` would name all seven keys and therefore
2247        // win all seven.
2248        let layers = RepoConfigLayers::load(repo).unwrap();
2249        assert_eq!(layers.source_of("ignore"), ConfigSource::Personal);
2250        let cfg = layers.effective().unwrap();
2251        assert!(cfg.ignore);
2252        assert_eq!(cfg.scan_depth, Some(9));
2253
2254        // The empty section is written so it can be seen and filled in, which means it
2255        // has to be inert until somebody fills it in.
2256        assert!(cfg.prunable.is_none(), "an empty list declares nothing");
2257    }
2258
2259    #[test]
2260    fn a_write_back_never_copies_the_project_answer_into_the_personal_file() {
2261        // The drift this feature would otherwise create: `devp config --update` and the
2262        // workspace toggles all read-modify-write `.devprune.json`, and a merged read
2263        // would bake the team's value into one person's file, where it outlives the
2264        // next edit to the file it came from.
2265        let tmp = TempDir::new().unwrap();
2266        let repo = tmp.path();
2267        fs::write(
2268            repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2269            r#"{ "ignore": true }"#,
2270        )
2271        .unwrap();
2272        fs::write(
2273            repo.join(constants::PER_REPO_CONFIG_FILE),
2274            r#"{ "scan_depth": 4 }"#,
2275        )
2276        .unwrap();
2277
2278        let personal = PerRepoConfig::load_personal_for_write(repo)
2279            .unwrap()
2280            .unwrap();
2281        assert!(!personal.ignore, "the project answer must not travel");
2282        assert_eq!(personal.scan_depth, Some(4));
2283    }
2284
2285    #[test]
2286    fn a_personal_exclusion_vetoes_a_declaration_the_project_committed() {
2287        // The conflict the key exists for: the committed file says `scratch` is
2288        // rebuildable, and on this one machine `scratch` is holding something. The way
2289        // out must not be editing a file the whole team shares.
2290        let tmp = TempDir::new().unwrap();
2291        let repo = tmp.path();
2292        fs::write(
2293            repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2294            r#"{ "prunable": { "directories": [
2295                 { "path": "scratch", "rebuild": "make scratch" }
2296               ] } }"#,
2297        )
2298        .unwrap();
2299        fs::write(
2300            repo.join(constants::PER_REPO_CONFIG_FILE),
2301            r#"{ "prunable": { "exclude": ["scratch"] } }"#,
2302        )
2303        .unwrap();
2304
2305        let prunable = PerRepoConfig::load_with_diagnostics(repo)
2306            .unwrap()
2307            .unwrap()
2308            .prunable
2309            .unwrap();
2310
2311        // The declaration survives the merge and is vetoed when it is resolved, so
2312        // deleting the exclusion later puts the directory back in play without anyone
2313        // having to re-declare it.
2314        assert_eq!(prunable.directories.len(), 1);
2315        assert_eq!(prunable.exclude, ["scratch"]);
2316    }
2317
2318    #[test]
2319    fn declarations_from_both_files_add_up_rather_than_one_silencing_the_other() {
2320        let tmp = TempDir::new().unwrap();
2321        let repo = tmp.path();
2322        fs::write(
2323            repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2324            r#"{ "prunable": { "directories": [
2325                 { "path": "tools/vendor", "rebuild": "make vendor" },
2326                 { "path": ".cache/shared", "rebuild": "make cache" }
2327               ] } }"#,
2328        )
2329        .unwrap();
2330        fs::write(
2331            repo.join(constants::PER_REPO_CONFIG_FILE),
2332            r#"{ "prunable": { "directories": [
2333                 { "path": ".cache/shared", "rebuild": "an old script I wrote" },
2334                 { "path": "scratch", "rebuild": "make scratch" }
2335               ] } }"#,
2336        )
2337        .unwrap();
2338
2339        let dirs = PerRepoConfig::load_with_diagnostics(repo)
2340            .unwrap()
2341            .unwrap()
2342            .prunable
2343            .unwrap()
2344            .directories;
2345
2346        // Every key above this one is decided by one file or the other. A list is not a
2347        // decision, so nobody's entry is dropped for having been written by the wrong
2348        // person.
2349        let paths: Vec<&str> = dirs.iter().map(|d| d.path.as_str()).collect();
2350        assert_eq!(paths, ["tools/vendor", ".cache/shared", "scratch"]);
2351
2352        // One path is still one directory, and the committed answer is the current one.
2353        assert_eq!(dirs[1].rebuild, "make cache");
2354    }
2355
2356    #[test]
2357    fn test_serialization_roundtrip() {
2358        let mut registry = Registry::default();
2359        registry.settings.idle_days = 30;
2360        registry.add_repo(PathBuf::from("/test/repo"));
2361
2362        let json = serde_json::to_string_pretty(&registry).unwrap();
2363        let deserialized: Registry = serde_json::from_str(&json).unwrap();
2364        assert_eq!(registry.settings.idle_days, deserialized.settings.idle_days);
2365        assert_eq!(registry.repo_count(), deserialized.repo_count());
2366    }
2367
2368    #[test]
2369    fn test_atomic_save_leaves_no_tmp() {
2370        let tmp = TempDir::new().unwrap();
2371        let path = test_registry_path(&tmp);
2372
2373        let registry = Registry::default();
2374        registry.save_to(&path).unwrap();
2375
2376        assert!(path.exists());
2377        // Nothing but the registry itself may remain — a leftover `*.tmp` would mean the
2378        // rename never happened.
2379        let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap())
2380            .unwrap()
2381            .flatten()
2382            .filter(|e| e.path() != path)
2383            .collect();
2384        assert!(leftovers.is_empty(), "leftover files: {leftovers:?}");
2385    }
2386
2387    #[test]
2388    fn exclude_entry_lands_in_git_info_exclude_not_gitignore() {
2389        let tmp = TempDir::new().unwrap();
2390        let repo = tmp.path();
2391        fs::create_dir(repo.join(".git")).unwrap();
2392
2393        ensure_in_git_exclude(repo, ".devprune.json").unwrap();
2394
2395        let exclude = fs::read_to_string(repo.join(".git/info/exclude")).unwrap();
2396        assert!(exclude.lines().any(|l| l == ".devprune.json"));
2397        // The whole point of using the exclude file: the shared, tracked `.gitignore`
2398        // must never be created or touched.
2399        assert!(!repo.join(".gitignore").exists());
2400    }
2401
2402    #[test]
2403    fn exclude_entry_is_appended_once_and_preserves_existing_lines() {
2404        let tmp = TempDir::new().unwrap();
2405        let repo = tmp.path();
2406        fs::create_dir_all(repo.join(".git/info")).unwrap();
2407        // No trailing newline, deliberately — the append must not glue two entries
2408        // onto one line.
2409        fs::write(repo.join(".git/info/exclude"), "*.log").unwrap();
2410
2411        ensure_in_git_exclude(repo, ".devprune.json").unwrap();
2412        ensure_in_git_exclude(repo, ".devprune.json").unwrap();
2413
2414        let exclude = fs::read_to_string(repo.join(".git/info/exclude")).unwrap();
2415        let lines: Vec<_> = exclude.lines().collect();
2416        assert_eq!(lines, vec!["*.log", ".devprune.json"]);
2417    }
2418
2419    #[test]
2420    fn exclude_follows_a_gitdir_pointer_file() {
2421        // Worktrees and submodules have a one-line `.git` *file*, and a worktree's
2422        // private gitdir points at the shared one via `commondir` — where the real
2423        // `info/exclude` lives.
2424        let tmp = TempDir::new().unwrap();
2425        let shared = tmp.path().join("main-clone/.git");
2426        let worktree_gitdir = shared.join("worktrees/wt");
2427        fs::create_dir_all(&worktree_gitdir).unwrap();
2428        fs::write(worktree_gitdir.join("commondir"), "../..\n").unwrap();
2429
2430        let wt = tmp.path().join("wt");
2431        fs::create_dir(&wt).unwrap();
2432        fs::write(
2433            wt.join(".git"),
2434            format!("gitdir: {}\n", worktree_gitdir.display()),
2435        )
2436        .unwrap();
2437
2438        ensure_in_git_exclude(&wt, ".devprune.json").unwrap();
2439
2440        let exclude = fs::read_to_string(shared.join("info/exclude")).unwrap();
2441        assert!(exclude.lines().any(|l| l == ".devprune.json"));
2442    }
2443
2444    #[test]
2445    fn exclude_is_a_no_op_outside_a_git_repository() {
2446        let tmp = TempDir::new().unwrap();
2447
2448        ensure_in_git_exclude(tmp.path(), ".devprune.json").unwrap();
2449
2450        assert!(!tmp.path().join(".git").exists());
2451        assert!(!tmp.path().join(".gitignore").exists());
2452    }
2453    /// A repository that moved is recognised, and arrives with everything it had earned.
2454    #[test]
2455    fn adopt_moved_entry_transfers_history() {
2456        let mut reg = Registry::default();
2457        let old = PathBuf::from("/nowhere/old-home/project");
2458        let mut entry = RepoEntry::new();
2459        entry.identity = Some("abc1234def".into());
2460        entry.total_freed_bytes = 4096;
2461        entry.enabled = false;
2462        entry.override_idle_days = Some(90);
2463        reg.repositories.insert(old.clone(), entry);
2464
2465        let new = std::env::temp_dir().join("devprune-adopt-live");
2466        reg.repositories.insert(new.clone(), RepoEntry::new());
2467
2468        let outcome = reg.adopt_moved_entry(&new, Some("abc1234def".into()));
2469        assert_eq!(outcome, Adoption::Moved(old.clone()));
2470        assert!(!reg.repositories.contains_key(&old));
2471
2472        let moved = &reg.repositories[&canonical_key(&new)];
2473        assert_eq!(moved.total_freed_bytes, 4096);
2474        // A repository the user had switched off did not switch itself back on by
2475        // being moved.
2476        assert!(!moved.enabled);
2477        assert_eq!(moved.override_idle_days, Some(90));
2478        assert_eq!(moved.identity.as_deref(), Some("abc1234def"));
2479    }
2480
2481    /// Two dead entries with one root commit are clones, not a move. Nothing is guessed.
2482    #[test]
2483    fn adopt_moved_entry_refuses_to_guess_between_two() {
2484        let mut reg = Registry::default();
2485        for name in ["/nowhere/a", "/nowhere/b"] {
2486            let mut entry = RepoEntry::new();
2487            entry.identity = Some("shared".into());
2488            reg.repositories.insert(PathBuf::from(name), entry);
2489        }
2490        let new = std::env::temp_dir().join("devprune-adopt-ambiguous");
2491        reg.repositories.insert(new.clone(), RepoEntry::new());
2492
2493        assert_eq!(
2494            reg.adopt_moved_entry(&new, Some("shared".into())),
2495            Adoption::Ambiguous
2496        );
2497        assert_eq!(reg.repositories.len(), 3);
2498        // The identity is still recorded, so the next registration can recognise it
2499        // once the duplicates are cleared.
2500        assert_eq!(
2501            reg.repositories[&canonical_key(&new)].identity.as_deref(),
2502            Some("shared")
2503        );
2504    }
2505
2506    /// An entry whose path still exists is not a move, however matching its history.
2507    #[test]
2508    fn adopt_moved_entry_never_takes_from_a_live_path() {
2509        let dir = tempfile::tempdir().unwrap();
2510        let live = dir.path().join("live");
2511        std::fs::create_dir(&live).unwrap();
2512
2513        let mut reg = Registry::default();
2514        let mut entry = RepoEntry::new();
2515        entry.identity = Some("same".into());
2516        entry.total_freed_bytes = 999;
2517        reg.repositories.insert(canonical_key(&live), entry);
2518
2519        let other = dir.path().join("other");
2520        std::fs::create_dir(&other).unwrap();
2521        reg.repositories
2522            .insert(canonical_key(&other), RepoEntry::new());
2523
2524        assert_eq!(
2525            reg.adopt_moved_entry(&other, Some("same".into())),
2526            Adoption::Nothing
2527        );
2528        assert_eq!(
2529            reg.repositories[&canonical_key(&live)].total_freed_bytes,
2530            999
2531        );
2532    }
2533
2534    /// A repository with no commits has no identity, so nothing is adopted and nothing
2535    /// is recorded — a guess would be worse than the dead entry it replaced.
2536    #[test]
2537    fn adopt_moved_entry_ignores_a_missing_identity() {
2538        let mut reg = Registry::default();
2539        let mut entry = RepoEntry::new();
2540        entry.identity = Some("orphan".into());
2541        reg.repositories
2542            .insert(PathBuf::from("/nowhere/gone"), entry);
2543        let new = std::env::temp_dir().join("devprune-adopt-unborn");
2544        reg.repositories.insert(new.clone(), RepoEntry::new());
2545
2546        assert_eq!(reg.adopt_moved_entry(&new, None), Adoption::Nothing);
2547        assert_eq!(reg.repositories.len(), 2);
2548        assert!(reg.needs_identity(&new));
2549    }
2550
2551    #[test]
2552    fn a_restore_too_quick_to_be_real_teaches_nothing() {
2553        // A manager that found everything still in its cache returns in a moment. Folding
2554        // that into the average would claim a throughput no cold restore can reach, and
2555        // the estimate exists precisely to describe a cold one.
2556        let mut reg = Registry::default();
2557        reg.record_restore("npm", 500_000_000, 10);
2558        reg.record_restore("npm", 0, 60_000);
2559        assert!(reg.restore_rates.is_empty(), "{:?}", reg.restore_rates);
2560
2561        reg.record_restore("npm", 500_000_000, 60_000);
2562        assert_eq!(reg.restore_rates["npm"].samples, 1);
2563    }
2564
2565    #[test]
2566    fn the_average_forgets_the_disk_the_machine_no_longer_has() {
2567        let mut reg = Registry::default();
2568        for _ in 0..constants::RESTORE_RATE_SAMPLE_CAP {
2569            reg.record_restore("npm", 1_000_000, 1_000);
2570        }
2571        assert_eq!(
2572            reg.restore_rates["npm"].samples,
2573            constants::RESTORE_RATE_SAMPLE_CAP
2574        );
2575
2576        // The cap is a halving, not a ceiling: the next sample still lands, on top of
2577        // half of what came before.
2578        reg.record_restore("npm", 1_000_000, 1_000);
2579        let rate = &reg.restore_rates["npm"];
2580        assert_eq!(rate.samples, constants::RESTORE_RATE_SAMPLE_CAP / 2 + 1);
2581        assert!(rate.bytes_per_sec().is_some());
2582    }
2583
2584    #[test]
2585    fn an_estimate_with_nothing_measured_is_not_offered() {
2586        // Never a zero and never a guess: a machine that has not restored anything yet
2587        // has no honest answer to "how long is this to undo", so it does not print one.
2588        let reg = Registry::default();
2589        assert!(reg.estimate_restore(&[("npm".into(), 1_000_000)]).is_none());
2590    }
2591
2592    #[test]
2593    fn an_untimed_adapter_is_left_out_of_the_coverage() {
2594        // Half an answer, reported as half. Counting cargo's bytes at npm's speed would
2595        // be the one thing worse than saying nothing.
2596        let mut reg = Registry::default();
2597        reg.record_restore("npm", 10_000_000, 10_000);
2598        let (secs, covered) = reg
2599            .estimate_restore(&[("npm".into(), 10_000_000), ("cargo".into(), 90_000_000)])
2600            .expect("npm alone is enough to answer for npm");
2601        assert_eq!(covered, 10_000_000, "cargo has never been timed here");
2602        assert!((secs - 10.0).abs() < 0.01, "{secs}");
2603    }
2604}