Skip to main content

dev_prune/
lib.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4pub mod adapters;
5pub mod channel;
6pub mod commands;
7pub mod config;
8pub mod constants;
9pub mod daemon;
10pub mod declared;
11pub mod engine;
12pub mod help;
13pub mod i18n;
14pub mod json;
15pub mod output;
16pub mod pathenv;
17pub mod receipt;
18pub mod scanner;
19pub mod setup;
20pub mod spawn;
21pub mod tui;
22pub mod workspace;
23
24use clap::{Parser, Subcommand};
25
26/// Process exit codes, so scripts and CI can branch on the outcome.
27///
28/// These are part of the tool's contract and are documented in `docs/CLI_REFERENCE.md`;
29/// changing one is a breaking change.
30pub mod exit_code {
31    /// The command did what it was asked to do. A prune that deleted nothing because
32    /// nothing was idle is still a success.
33    pub const OK: i32 = 0;
34    /// The command failed. The reason is on stderr.
35    pub const FAILURE: i32 = 1;
36    /// The arguments were not usable. Emitted by clap, listed here so the set is complete.
37    pub const USAGE: i32 = 2;
38}
39
40/// The machine's own architecture, reported only when it differs from this build's.
41///
42/// `std::env::consts::ARCH` is baked in at compile time, so a 32-bit build on a 64-bit
43/// machine reports `x86` and looks, to anyone reading it, like a claim about the
44/// hardware. Windows sets [`constants::ENV_NATIVE_ARCH`] under WOW64 and under ARM64
45/// emulation; it is the only thing an emulated process can ask. The names are mapped to
46/// Rust's spellings so the two halves of "x86, but this machine is x86_64" match.
47///
48/// `None` means the build and the machine agree, or the question cannot be answered —
49/// both of which are reported as nothing at all rather than as a guess.
50pub fn native_arch_if_emulated() -> Option<String> {
51    let native = std::env::var(constants::ENV_NATIVE_ARCH).ok()?;
52    let native = native.trim();
53    if native.is_empty() {
54        return None;
55    }
56    let mapped = match native.to_ascii_uppercase().as_str() {
57        "AMD64" => "x86_64".to_string(),
58        "ARM64" => "aarch64".to_string(),
59        "X86" => "x86".to_string(),
60        other => other.to_ascii_lowercase(),
61    };
62    (mapped != std::env::consts::ARCH).then_some(mapped)
63}
64
65/// Marker for errors that are usage mistakes rather than runtime failures.
66///
67/// clap exits `USAGE` for conflicts it can see at parse time; combinations only the
68/// command logic can judge — `run --json` with neither `--dry-run` nor `--yes` — used
69/// to exit `FAILURE`, which told a script "the prune broke" when the truth was "the
70/// command line was incomplete". Raising this instead routes them to `USAGE`.
71#[derive(Debug)]
72pub struct UsageError(pub String);
73
74impl std::fmt::Display for UsageError {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.write_str(&self.0)
77    }
78}
79
80impl std::error::Error for UsageError {}
81
82/// Restore the default disposition for `SIGPIPE`.
83///
84/// Rust ignores `SIGPIPE` at startup, which turns `devp status | head` into a panic —
85/// "failed printing to stdout" plus a backtrace — where every other Unix tool simply
86/// stops. Putting the default back makes dev-prune behave like `ls` in a pipeline.
87#[cfg(unix)]
88fn restore_sigpipe() {
89    // SAFETY: `signal` with SIG_DFL is async-signal-safe and this runs before any
90    // thread is spawned.
91    unsafe {
92        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
93    }
94}
95
96#[cfg(not(unix))]
97fn restore_sigpipe() {}
98
99/// Explain the rename, then answer the question the user was really asking.
100///
101/// Nobody types `--force` for fun. They type it because something was not pruned and
102/// they want the tool to stop arguing — so a bare "the flag moved" note would leave
103/// them exactly as stuck as before. The list below is every reason a directory gets
104/// skipped, with the fix, because six of the seven are not what `--force` was for.
105///
106/// Goes to stderr with the rest of the diagnostics, so `--json` stays parseable.
107fn print_force_help() {
108    output::print_notice(
109        "`--force` is now `--ignore-idle`, which is what it has always actually done. \
110         The old spelling still works.",
111    );
112    eprintln!(
113        "
114  Reaching for --force usually means something did not get pruned. It is one of these:
115
116    Not idle yet          A commit or a source edit inside idle_days (15 by default).
117                          This is the one --ignore-idle is for.
118    Lockfile unusable     The package manager could not confirm it. Run the command
119                          dev-prune printed, then try again. No flag skips this check.
120    Opted out             `ignore.devprune.json` in the root, or `\"ignore\": true`
121                          in `.devprune.json`.
122    Under the size floor  Smaller than min_size_mb. `--min-size 0` includes it.
123    Not registered        `devp link .` first; `devp status` shows what is tracked.
124    Nested or symlinked   A submodule is pruned as itself, never as part of its
125                          parent, and a linked directory is refused. By design.
126    Too deep              Beyond scan_depth (6 levels). `devp config set scan_depth N`.
127
128  `devp run --dry-run` names the actual reason, per repository.
129
130  Still stuck? Ask your AI assistant — `devp skill` hands it the full troubleshooting
131  tree, including this list. It has read it. It wrote it.
132"
133    );
134}
135
136/// Whether a failure is just the reader at the other end of a pipe hanging up.
137///
138/// `devp status | head -5` is a normal thing to type, and the closed pipe it produces is
139/// not an error worth printing — printing it would itself fail.
140fn is_broken_pipe(err: &anyhow::Error) -> bool {
141    err.chain().any(|cause| {
142        cause
143            .downcast_ref::<std::io::Error>()
144            .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::BrokenPipe)
145    })
146}
147
148/// Universal, lockfile-safe workspace pruner and background dependency cleaner.
149///
150/// Note: `dev-prune` and `devp` are interchangeable binary aliases.
151#[derive(Parser, Debug)]
152#[command(name = constants::APP_NAME)]
153#[command(version = constants::VERSION)]
154#[command(author = constants::AUTHOR)]
155#[command(long_version = constants::LONG_VERSION.as_str())]
156#[command(
157    about = "Universal, lockfile-safe workspace pruner and background dependency cleaner\nNote: `dev-prune` and `devp` are interchangeable binary aliases."
158)]
159#[command(
160    after_help = "EXAMPLES:\n  devp init ~/Code          Scan directory trees & onboard workspaces\n  devp link                 Register current repository\n  devp run                  Execute prune pass across inactive repositories\n  devp status               View system status dashboard\n  devp status --top 10      Show only the ten biggest reclaims\n  devp stats                Lifetime totals, recent passes, biggest repositories\n  devp caches               Size every package manager cache (deletes nothing)\n  devp completions powershell   Emit a shell completion script\n  devp status daemon        Check background daemon status (alias for `devp config daemon status`)\n  devp status . hook        Check workspace Git hook status (alias for `devp config . hook status`)\n  devp config . daemon disable  Disable daemon background pass for current workspace\n  devp restore .            Restore missing node_modules/.venv via lockfile\n  devp undo                 Revert most recent init or link action\n\nBINARY ALIAS:\n  `dev-prune` and `devp` invoke the exact same executable.\n\ndev-prune is written by VKrishna04 and licensed Apache-2.0.\n  https://github.com/Life-Experimentalist/dev-prune"
161)]
162pub struct Cli {
163    #[command(subcommand)]
164    command: Commands,
165
166    /// Simulate pruning without deleting any files.
167    #[arg(long, global = true)]
168    dry_run: bool,
169
170    /// Prune repositories you are still working in, ignoring the idle-day threshold.
171    ///
172    /// This is the *only* check it lifts. Lockfile verification, `ignore.devprune.json`,
173    /// `"ignore": true`, symlink refusal and nested-repository refusal all still apply.
174    #[arg(long, global = true)]
175    ignore_idle: bool,
176
177    /// Deprecated spelling of `--ignore-idle`.
178    ///
179    /// Renamed because "force" reads like "override the safety checks", which it never
180    /// did — it only ever skipped the idle-day wait. Still accepted; prints a note.
181    #[arg(long, global = true)]
182    force: bool,
183
184    /// Bypass interactive confirmation prompts.
185    #[arg(long, short = 'y', global = true)]
186    yes: bool,
187}
188
189#[derive(Subcommand, Debug)]
190pub enum Commands {
191    /// Workspace onboarding & discovery: crawl paths for Git repositories and register them.
192    #[command(alias = "scan", alias = "onboard")]
193    #[command(long_about = help::INIT_LONG, after_long_help = help::INIT_EXAMPLES)]
194    Init {
195        /// Paths to scan for Git repositories (defaults to current directory).
196        #[arg(default_value = ".")]
197        paths: Vec<String>,
198    },
199
200    /// Register a single Git repository for pruning (defaults to current directory `.`).
201    #[command(long_about = help::LINK_LONG, after_long_help = help::LINK_EXAMPLES)]
202    Link {
203        /// Path to the Git repository to register.
204        #[arg(default_value = ".")]
205        path: String,
206
207        /// Suppress output and skip repos that set `disable_hooks`. Used by the Git hook.
208        #[arg(long)]
209        quiet: bool,
210    },
211
212    /// Remove a repository from the dev-prune registry (does not delete workspace files).
213    #[command(long_about = help::UNLINK_LONG, after_long_help = help::UNLINK_EXAMPLES)]
214    Unlink {
215        /// Path to the Git repository to unregister.
216        #[arg(default_value = ".")]
217        path: String,
218
219        /// Unregister every path that no longer exists, instead of one named repository.
220        #[arg(long, conflicts_with = "path")]
221        missing: bool,
222    },
223
224    /// Revert the most recent init or link action.
225    #[command(long_about = help::UNDO_LONG, after_long_help = help::UNDO_EXAMPLES)]
226    Undo,
227
228    /// Run a prune pass across all registered repositories or a target directory (`devp run .`).
229    #[command(long_about = help::RUN_LONG, after_long_help = help::RUN_EXAMPLES)]
230    Run {
231        /// Optional target workspace path. If omitted, runs across all registered repositories.
232        target_path: Option<String>,
233
234        /// Mark this as the scheduled background pass. Repositories that set
235        /// `disable_daemon` in `.devprune.json` are skipped. Set by the installed scheduler.
236        #[arg(long)]
237        daemon: bool,
238
239        /// Act only on these package managers (comma-separated),
240        /// e.g. `--only npm,pnpm`. Unknown names are an error.
241        #[arg(long, value_name = "ADAPTERS", conflicts_with = "skip")]
242        only: Option<String>,
243
244        /// Leave these package managers alone (comma-separated), e.g. `--skip cargo`.
245        #[arg(long, value_name = "ADAPTERS")]
246        skip: Option<String>,
247
248        /// Ignore bloat directories smaller than this many MiB. Overrides `min_size_mb`.
249        #[arg(long, value_name = "MIB")]
250        min_size: Option<u64>,
251
252        /// Prune everything except these repositories (comma-separated paths or names).
253        ///
254        /// The safe way to express "clean up but keep the API project": that project is
255        /// never verified, never deleted and never reinstalled, instead of being pruned
256        /// and then restored over the network.
257        #[arg(long, value_name = "REPOS")]
258        except: Option<String>,
259
260        /// Emit one JSON document instead of the human report. Implies non-interactive.
261        #[arg(long)]
262        json: bool,
263
264        /// Explain every decision instead of pruning: each repository and directory,
265        /// with the reason it would or would not be touched — including the states a
266        /// normal pass keeps quiet about (still active, opted out, under the size
267        /// floor). Read-only; nothing is verified or deleted.
268        #[arg(long, conflicts_with = "json")]
269        explain: bool,
270    },
271
272    /// View system dashboard: registered repos, background daemon, Git hooks & space metrics.
273    #[command(long_about = help::STATUS_LONG, after_long_help = help::STATUS_EXAMPLES)]
274    Status {
275        /// Show only the N repositories with the most reclaimable space.
276        ///
277        /// The dashboard lists every registered repository, which on a machine with a
278        /// hundred of them buries the handful actually worth pruning. Applies to the TUI,
279        /// the plain table and `--json` alike.
280        ///
281        /// Zero is rejected up front: "show the top 0" can only be a typo, and an empty
282        /// dashboard that looks like an empty registry is worse than a usage error.
283        #[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
284        top: Option<u64>,
285
286        /// Report lockfile drift instead of the dashboard: environments holding packages
287        /// their lockfile never recorded — the installs a prune would refuse to delete
288        /// because nothing could bring them back.
289        ///
290        /// A pure read: no package manager runs, nothing is written. Checked where a
291        /// file-level comparison exists — npm, uv and venv projects.
292        #[arg(long, conflicts_with = "top")]
293        drift: bool,
294
295        /// Emit the dashboard as one JSON document instead of the TUI or text table.
296        #[arg(long)]
297        json: bool,
298    },
299
300    /// Show lifetime space reclaimed, recent prune passes, and the biggest repositories.
301    #[command(long_about = help::STATS_LONG, after_long_help = help::STATS_EXAMPLES)]
302    Stats {
303        /// Emit the figures as one JSON document instead of the text report.
304        #[arg(long)]
305        json: bool,
306    },
307
308    /// Report what dev-prune is allowed to do on this machine, and what it has been given permission to do.
309    #[command(long_about = help::TRUST_LONG, after_long_help = help::TRUST_EXAMPLES)]
310    Trust {
311        /// Emit the report as one JSON document instead of the table.
312        #[arg(long)]
313        json: bool,
314
315        /// Let Git read registered repositories it currently refuses on ownership.
316        #[arg(long, conflicts_with = "json")]
317        fix_ownership: bool,
318
319        /// Answer yes to the confirmation `--fix-ownership` asks.
320        #[arg(long, requires = "fix_ownership")]
321        yes: bool,
322    },
323
324    /// Print a shell completion script for bash, zsh, fish, PowerShell or elvish.
325    #[command(long_about = help::COMPLETIONS_LONG, after_long_help = help::COMPLETIONS_EXAMPLES)]
326    Completions {
327        /// Shell to generate for.
328        shell: clap_complete::Shell,
329    },
330
331    /// Print or write man pages, generated from the same definitions `--help` prints.
332    #[command(long_about = help::MAN_LONG, after_long_help = help::MAN_EXAMPLES)]
333    Man {
334        /// The command whose page to read, e.g. `devp man run`. Omit for the
335        /// contents page.
336        command: Option<String>,
337
338        /// Write `devp.1` plus one `devp-<command>.1` per subcommand into this
339        /// directory, instead of rendering the main page to stdout.
340        #[arg(long, value_name = "DIR")]
341        dir: Option<String>,
342
343        /// Print the roff source even when stdout is a terminal, instead of the
344        /// readable manual.
345        #[arg(long)]
346        roff: bool,
347    },
348
349    /// Report the size of every package manager cache on this machine (read-only unless you ask for `clear`).
350    #[command(long_about = help::CACHES_LONG, after_long_help = help::CACHES_EXAMPLES)]
351    Caches {
352        /// Emit the report as one JSON document instead of the table.
353        ///
354        /// Global within `caches` so it can be written after the subcommand too —
355        /// `devp caches clear npm --json` is what everyone types.
356        #[arg(long, global = true)]
357        json: bool,
358
359        #[command(subcommand)]
360        action: Option<CachesAction>,
361    },
362
363    /// Manage global settings, background daemon, Git hooks, custom icons, or per-project .devprune.json.
364    #[command(long_about = help::CONFIG_LONG, after_long_help = help::CONFIG_EXAMPLES)]
365    Config {
366        #[command(subcommand)]
367        action: Option<ConfigAction>,
368    },
369
370    /// Restore dependencies in a project using its lockfile (npm ci, pnpm install, uv sync).
371    #[command(long_about = help::RESTORE_LONG, after_long_help = help::RESTORE_EXAMPLES)]
372    Restore {
373        /// Path to the project to restore (defaults to current directory).
374        path: Option<String>,
375
376        /// Put back exactly what the most recent prune pass deleted, in every repository
377        /// it touched. The undo for a `run`.
378        #[arg(long, conflicts_with = "path")]
379        last_run: bool,
380    },
381
382    /// Print the installed version, check for a newer release, and show how to upgrade.
383    #[command(long_about = help::UPDATE_LONG, after_long_help = help::UPDATE_EXAMPLES)]
384    Update {
385        /// Skip the release check for this run. The check is the only thing in dev-prune
386        /// that opens a network connection; `devp config set update_check false` turns
387        /// it off for good.
388        #[arg(long)]
389        offline: bool,
390
391        /// Download and install the newer release, through whichever package manager
392        /// installed this copy (cargo, npm, bun, pnpm, yarn, uv, pipx, or the installer
393        /// script). Needs the network, so it cannot be combined with `--offline`.
394        #[arg(long, conflicts_with = "offline")]
395        install: bool,
396
397        /// Print the upgrade command for every channel dev-prune ships through, instead
398        /// of only the one that installed this copy. Touches nothing and needs no
399        /// network — useful when the machine in front of you is not the one that has
400        /// the stale copy.
401        #[arg(long, conflicts_with_all = ["offline", "install"])]
402        channels: bool,
403    },
404
405    /// Export SKILL.md and display ready-to-copy AI Agent onboarding & skill import prompts.
406    #[command(long_about = help::SKILL_LONG, after_long_help = help::SKILL_EXAMPLES)]
407    Skill {
408        /// Write rules for one editor's agent into the current repository instead.
409        /// Each value below names the exact file it writes. Five of them —
410        /// `agents-md`, `copilot`, `gemini`, `junie`, `zed` — share a file with
411        /// other tools, so dev-prune owns a marked block inside it and leaves every
412        /// byte outside the markers as found. Claude Code needs no per-repo file:
413        /// plain `devp skill` installs its skill globally.
414        #[arg(long, value_enum, value_name = "EDITOR")]
415        agent: Option<commands::skill::AgentEditor>,
416    },
417
418    /// Install whatever dev-prune integration is missing: alias, SKILL.md, Git hooks, scheduler.
419    #[command(long_about = help::SETUP_LONG, after_long_help = help::SETUP_EXAMPLES)]
420    Setup {
421        /// Report what is installed without changing anything.
422        #[arg(long)]
423        status: bool,
424    },
425
426    /// Diagnose the installation, or one repository if given a path (`devp doctor .`).
427    #[command(long_about = help::DOCTOR_LONG, after_long_help = help::DOCTOR_EXAMPLES)]
428    Doctor {
429        /// Repository to diagnose. Omit to check the installation itself.
430        path: Option<String>,
431
432        /// Repair what the installation check finds broken: refresh a stale or missing
433        /// `devp` twin, re-export SKILL.md, re-register a scheduler or Git hooks whose
434        /// binary moved, and drop registry entries whose repository is gone.
435        ///
436        /// Repairs only what was installed and has since broken — it never installs an
437        /// integration that was never set up (that is `devp setup`), and it cannot fix a
438        /// corrupt registry file, which needs a human decision.
439        #[arg(long, conflicts_with = "path")]
440        fix: bool,
441    },
442
443    /// Move this install to another package manager: `devp install --channel uv`.
444    #[command(long_about = help::INSTALL_LONG, after_long_help = help::INSTALL_EXAMPLES)]
445    Install {
446        /// The package manager to move this installation to. Omit to print which one
447        /// owns the running copy, and the names this flag accepts.
448        #[arg(long, value_enum, value_name = "NAME")]
449        channel: Option<commands::install::TargetChannel>,
450
451        /// Print the commands that would run, and run none of them.
452        #[arg(long)]
453        dry_run: bool,
454    },
455
456    /// Remove dev-prune: scheduler, hooks, PATH entry, agent skill, and every copy of the binary.
457    #[command(long_about = help::UNINSTALL_LONG, after_long_help = help::UNINSTALL_EXAMPLES)]
458    Uninstall {
459        /// Perform a deep uninstall (wipe configuration folder and .devprune.json files).
460        #[arg(long)]
461        deep: bool,
462    },
463}
464
465impl Commands {
466    /// Whether this command's stdout is something another program reads.
467    ///
468    /// Two cases. `--json` promises stdout carries one document and nothing else, and
469    /// `completions` prints a script that gets sourced — a stray line in either is a
470    /// parse error rather than a nicety. `link --quiet` is the Git hook path, which runs
471    /// inside somebody's commit.
472    ///
473    /// Everything else defers to [`output::print_attribution`], which prints only when
474    /// stdout is a terminal. Neither function checks that the line is intact, and nothing
475    /// downstream depends on it having been printed.
476    fn suppresses_attribution(&self) -> bool {
477        match self {
478            Commands::Completions { .. } | Commands::Man { .. } => true,
479            Commands::Run { json, .. }
480            | Commands::Status { json, .. }
481            | Commands::Stats { json }
482            | Commands::Trust { json, .. }
483            | Commands::Caches { json, .. } => *json,
484            Commands::Link { quiet, .. } => *quiet,
485            _ => false,
486        }
487    }
488}
489
490#[derive(Subcommand, Debug)]
491pub enum CachesAction {
492    /// Empty one manager's cache, or every one of them, after showing what goes and asking.
493    #[command(long_about = help::CACHES_CLEAR_LONG, after_long_help = help::CACHES_CLEAR_EXAMPLES)]
494    Clear {
495        /// Which cache to empty: a manager name (npm, go, cargo, gradle, …) or `all`.
496        #[arg(value_name = "MANAGER")]
497        target: String,
498
499        /// Only empty caches that are over the size cap set for them in
500        /// `cache_max_gb`. Without a cap set for anything, this clears nothing.
501        #[arg(long)]
502        over_cap: bool,
503
504        /// Only empty caches that no registered repository uses. Refuses to run when
505        /// there are no registered repositories to check against.
506        #[arg(long)]
507        unused: bool,
508    },
509
510    /// What Docker is holding: images, containers, volumes and build cache (read-only).
511    #[command(long_about = help::CACHES_DOCKER_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
512    Docker,
513
514    /// What Podman is holding: images, containers, volumes and build cache (read-only).
515    #[command(long_about = help::CACHES_DOCKER_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
516    Podman,
517
518    /// The same report for every container engine found, or for the one you name.
519    #[command(long_about = help::CACHES_CONTAINERS_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
520    Containers {
521        /// Which engine: docker, podman or nerdctl. Omit for every one installed.
522        #[arg(value_name = "ENGINE")]
523        engine: Option<String>,
524    },
525}
526
527#[derive(Subcommand, Debug)]
528pub enum ConfigAction {
529    /// Display a global configuration value.
530    #[command(long_about = help::CONFIG_GET_LONG, after_long_help = help::CONFIG_GET_EXAMPLES)]
531    Get {
532        /// Any key `devp config show` lists — idle_days, min_size_mb, auto_update,
533        /// disabled_adapters and the rest. `devp config show` prints every key with
534        /// its current value.
535        key: String,
536    },
537    /// Set a global configuration value.
538    #[command(long_about = help::CONFIG_SET_LONG, after_long_help = help::CONFIG_SET_EXAMPLES)]
539    Set {
540        /// Configuration key.
541        key: String,
542        /// New value.
543        value: String,
544    },
545    /// Show all global configuration values or sync per-repo configurations.
546    #[command(long_about = help::CONFIG_SHOW_LONG, after_long_help = help::CONFIG_SHOW_EXAMPLES)]
547    Show {
548        /// Force update/sync pass across all registered repos.
549        #[arg(long, short)]
550        update: bool,
551    },
552    /// Turn on everything the first run recommends, in one command.
553    #[command(long_about = help::CONFIG_RECOMMENDED_LONG, after_long_help = help::CONFIG_RECOMMENDED_EXAMPLES)]
554    Recommended {
555        /// Include the recommendations that come with something to know first.
556        #[arg(long)]
557        with_cautious: bool,
558    },
559    /// Inspect or initialize per-repository config (.devprune.json) for a workspace path.
560    #[command(long_about = help::CONFIG_PROJECT_LONG, after_long_help = help::CONFIG_PROJECT_EXAMPLES)]
561    Project {
562        /// Path to the repository (defaults to current directory).
563        #[arg(default_value = ".")]
564        path: String,
565        /// Force update/sync pass on this project config.
566        #[arg(long, short)]
567        update: bool,
568        /// Act on the committed project.devprune.json instead of the personal file.
569        #[arg(long)]
570        team: bool,
571    },
572    /// Configure OS background daemon scheduler globally or for a workspace path.
573    #[command(long_about = help::CONFIG_DAEMON_LONG, after_long_help = help::CONFIG_DAEMON_EXAMPLES)]
574    Daemon {
575        /// Optional workspace path or sub-action (enable, disable, status).
576        target: Option<String>,
577        /// Sub-action if path was provided (enable, disable, status).
578        sub_action: Option<String>,
579    },
580    /// Configure non-blocking global Git background auto-registration hooks globally or for a workspace path.
581    #[command(long_about = help::CONFIG_HOOK_LONG, after_long_help = help::CONFIG_HOOK_EXAMPLES)]
582    Hook {
583        /// Optional workspace path or sub-action (enable, disable, status).
584        target: Option<String>,
585        /// Sub-action if path was provided (enable, disable, status).
586        sub_action: Option<String>,
587        /// Install in front of the hooks directory already configured, forwarding to it,
588        /// instead of refusing to take a slot another tool is using.
589        #[arg(long)]
590        chain: bool,
591    },
592    /// Register a file-manager icon for .devprune.json, and print an editor snippet.
593    #[command(long_about = help::CONFIG_ICON_LONG, after_long_help = help::CONFIG_ICON_EXAMPLES)]
594    Icon,
595    /// Walk through every global setting, confirming or changing each one.
596    #[command(long_about = help::CONFIG_WIZARD_LONG, after_long_help = help::CONFIG_WIZARD_EXAMPLES)]
597    Wizard {
598        /// Ask one question per line instead of opening the full-screen configurator.
599        #[arg(long)]
600        no_tui: bool,
601    },
602}
603
604/// Print rich version & system environment details for -v / -V / --version.
605///
606/// This, not clap, is what `devp --version` actually runs — [`normalize_args`] catches the
607/// flag first. The author and repository are printed here because a copy of this binary
608/// found on a machine with no package manager record should still be able to say where it
609/// came from, and `--version` is the first thing anyone runs on an unknown executable.
610pub fn print_version_info() {
611    use colored::Colorize;
612    output::print_banner();
613    println!(
614        "dev-prune (devp) {}",
615        format!("v{}", constants::VERSION).green().bold()
616    );
617    println!(
618        "  Binary Aliases:  {} | {}",
619        "dev-prune".cyan(),
620        "devp".cyan()
621    );
622    // These lines are facts, not status, so most of them stay in the terminal's own
623    // colour. The author line was turquoise and the OS and architecture yellow, which
624    // marked nothing and put five hues on one short screen; yellow now only ever means a
625    // warning, and cyan is reserved for the two things worth clicking.
626    println!("  Author:          {}", constants::AUTHOR);
627    println!(
628        "  Repository:      {}",
629        constants::REPO_URL.cyan().underline()
630    );
631    println!(
632        "  Homepage:        {}",
633        constants::HOMEPAGE_URL.cyan().underline()
634    );
635    println!("  Target OS:       {}", std::env::consts::OS);
636    match native_arch_if_emulated() {
637        // Without this the line reads as a statement about the machine, and a 32-bit
638        // build on a 64-bit laptop looks like the laptop is 32-bit.
639        Some(native) => println!(
640            "  Architecture:    {} {}",
641            std::env::consts::ARCH,
642            format!(
643                "(this build — the machine is {native}; `devp update` installs the native one)"
644            )
645            .yellow()
646        ),
647        None => println!("  Architecture:    {}", std::env::consts::ARCH),
648    }
649    println!(
650        "  Compiler:        Rust {}+ (edition 2024)",
651        constants::MSRV
652    );
653    println!("  License:         Apache-2.0");
654    println!();
655    let reg_path = config::Registry::registry_path()
656        .map(output::styled_path)
657        .unwrap_or_else(|_| "unknown".to_string());
658    println!("  Config Path:     {reg_path}");
659
660    if let Ok(exe) = std::env::current_exe()
661        && let Some(exe_dir) = exe.parent()
662    {
663        let exe_dir_str = output::clean_path(exe_dir);
664        // The same tolerant comparison the PATH writer uses — a trailing backslash or a
665        // case difference must not turn the audit line red on a healthy install.
666        let path_var = std::env::var("PATH").unwrap_or_default();
667        let exe_dir_entry = exe_dir.to_string_lossy();
668        let is_in_path = path_var
669            .split(if cfg!(windows) { ';' } else { ':' })
670            .any(|p| pathenv::entries_equal(p, &exe_dir_entry));
671
672        println!("  Binary Dir:      {}", exe_dir_str.cyan());
673        if is_in_path {
674            println!(
675                "  PATH Audit:      {}",
676                "✓ Executable directory is active in system PATH.".green()
677            );
678        } else {
679            println!(
680                "  PATH Audit:      {}",
681                "⚠ Executable directory is NOT in system PATH!".yellow()
682            );
683            println!(
684                "                   Add `{}` to Environment Variables.",
685                exe_dir_str.cyan()
686            );
687        }
688    }
689}
690
691/// Case-insensitive subcommand normalizer and status alias router.
692fn normalize_args() -> Vec<String> {
693    let args: Vec<String> = std::env::args().collect();
694    if args.len() == 2 && (args[1] == "-v" || args[1] == "-V" || args[1] == "--version") {
695        print_version_info();
696        std::process::exit(exit_code::OK);
697    }
698    if args.len() <= 1
699        || args
700            .iter()
701            .any(|a| a == "-h" || a == "--help" || a == "help")
702    {
703        output::print_banner();
704    }
705    if args.len() <= 1 {
706        return args;
707    }
708
709    let mut normalized = vec![args[0].clone()];
710    for (i, arg) in args.iter().enumerate().skip(1) {
711        if i == 1 && !arg.starts_with('-') {
712            normalized.push(arg.to_lowercase());
713        } else {
714            normalized.push(arg.clone());
715        }
716    }
717
718    // Map `devp daemon|hook|icon [ARGS...]` -> `devp config daemon|hook|icon [ARGS...]`
719    //
720    // These live under `config` because that is where the rest of the persistent
721    // settings live, but nobody types `devp config hook install` when they mean
722    // "install the hook" — and the tool's own output has always said `devp hook
723    // install`. Accepting both costs one insert and removes a papercut.
724    if matches!(normalized[1].as_str(), "daemon" | "hook" | "icon") {
725        normalized.insert(1, "config".to_string());
726    }
727
728    // Map `devp status [PATH] daemon` -> `devp config daemon [PATH] status`
729    // Map `devp status [PATH] hook`   -> `devp config hook [PATH] status`
730    //
731    // Exactly one optional PATH, and never a flag: `devp status --json daemon` must
732    // reach clap as typed and fail there, not be rewritten with `--json` as a path.
733    if normalized[1] == "status"
734        && (normalized.len() == 3 || (normalized.len() == 4 && !normalized[2].starts_with('-')))
735    {
736        let last = normalized
737            .last()
738            .map(|s| s.to_lowercase())
739            .unwrap_or_default();
740        if last == "daemon" || last == "hook" {
741            let mut rewrited = vec![normalized[0].clone(), "config".to_string(), last];
742            if normalized.len() > 3 {
743                rewrited.push(normalized[2].clone());
744            }
745            rewrited.push("status".to_string());
746            return rewrited;
747        }
748    }
749
750    // Map `devp config [PATH] daemon [ACTION]` -> `devp config daemon [PATH] [ACTION]`
751    // Map `devp config [PATH] hook [ACTION]`   -> `devp config hook [PATH] [ACTION]`
752    //
753    // Only when the second argument can actually be a path — a flag there means the
754    // user is talking to `config` itself and the rewrite would misfile it.
755    if normalized.len() >= 4 && normalized[1] == "config" && !normalized[2].starts_with('-') {
756        let third = normalized[3].to_lowercase();
757        if third == "daemon" || third == "hook" {
758            let mut rewrited = vec![
759                normalized[0].clone(),
760                "config".to_string(),
761                third,
762                normalized[2].clone(),
763            ];
764            for extra in &normalized[4..] {
765                rewrited.push(extra.clone());
766            }
767            return rewrited;
768        }
769    }
770
771    normalized
772}
773
774/// Whether the automatic setup pass may run for this invocation.
775///
776/// Two callers are excluded on purpose. The Git hook runs `link --quiet` with no
777/// terminal attached and inside someone's commit; the scheduler runs `run --daemon` the
778/// same way. An integration pass nobody can see is one nobody can refuse, so both wait
779/// for the next command a human types. `uninstall` is excluded for the obvious reason,
780/// and `setup` because it is the pass, run deliberately.
781fn auto_setup_allowed(args: &[String]) -> bool {
782    let subcommand = args.get(1).map(String::as_str).unwrap_or("");
783    // `--json` means a program is parsing stdout; the setup report and the first-run
784    // wizard would land inside the document. That invocation waits too.
785    !matches!(subcommand, "uninstall" | "setup")
786        && !args
787            .iter()
788            .any(|a| a == "--quiet" || a == "--daemon" || a == "--json")
789}
790
791/// Run the CLI application.
792pub fn run_cli() {
793    restore_sigpipe();
794
795    let args = normalize_args();
796    if auto_setup_allowed(&args) {
797        setup::auto_setup_if_due();
798    }
799    let cli = Cli::parse_from(args);
800
801    // After parsing, so `--version` and `--help` never pay for it, and before anything
802    // is printed, because every heading past this line is drawn in whatever it settles
803    // on. `Registry::load` is a pure read, and a registry that will not load is not a
804    // reason to refuse to print in English — the command below reports that failure
805    // properly.
806    i18n::init(
807        config::Registry::load()
808            .ok()
809            .map(|registry| registry.settings.language)
810            .as_deref(),
811    );
812
813    // Both spellings mean the same thing; the old one just says so first.
814    let ignore_idle = cli.ignore_idle || cli.force;
815    if cli.force {
816        print_force_help();
817    }
818
819    // Decided before the match, because that is where `cli.command` is consumed.
820    let credit_the_author = !cli.command.suppresses_attribution();
821
822    // Every path the user typed passes through `expand_tilde` on the way in. PowerShell
823    // and cmd hand us `~/Code` verbatim, so without this the documented one-liner
824    // registers a directory literally named `~`.
825    let result = match cli.command {
826        Commands::Init { paths } => {
827            let paths: Vec<String> = paths.iter().map(|p| config::expand_tilde(p)).collect();
828            commands::init::run(&paths, cli.dry_run)
829        }
830        Commands::Link { path, quiet } => {
831            commands::link::run_link(&config::expand_tilde(&path), quiet)
832        }
833        Commands::Unlink { path, missing } => {
834            if missing {
835                commands::link::run_unlink_missing()
836            } else {
837                commands::link::run_unlink(&config::expand_tilde(&path))
838            }
839        }
840        Commands::Undo => commands::undo::run(),
841        Commands::Run {
842            target_path,
843            daemon,
844            only,
845            skip,
846            min_size,
847            except,
848            json,
849            explain,
850        } => {
851            let target_path = target_path.map(|p| config::expand_tilde(&p));
852            commands::run::run(commands::run::RunArgs {
853                target_path: target_path.as_deref(),
854                dry_run: cli.dry_run,
855                force: ignore_idle,
856                yes: cli.yes,
857                daemon,
858                only: only.as_deref(),
859                skip: skip.as_deref(),
860                min_size_mb: min_size,
861                except: except.as_deref(),
862                json,
863                explain,
864            })
865        }
866        Commands::Status { top, drift, json } => {
867            commands::status::run(top.map(|n| n as usize), drift, json)
868        }
869        Commands::Stats { json } => commands::stats::run(json),
870        Commands::Completions { shell } => commands::completions::run(shell),
871        Commands::Man { command, dir, roff } => {
872            commands::man::run(command.as_deref(), dir.as_deref(), roff)
873        }
874        Commands::Trust {
875            json,
876            fix_ownership,
877            yes,
878        } => {
879            if fix_ownership {
880                commands::trust::fix_ownership(yes)
881            } else {
882                commands::trust::run(json)
883            }
884        }
885        Commands::Caches { json, action } => match action {
886            Some(CachesAction::Clear {
887                target,
888                over_cap,
889                unused,
890            }) => {
891                commands::caches::run_clear(&target, over_cap, unused, cli.yes, cli.dry_run, json)
892            }
893            Some(CachesAction::Docker) => commands::containers::run(Some("docker"), json),
894            Some(CachesAction::Podman) => commands::containers::run(Some("podman"), json),
895            Some(CachesAction::Containers { engine }) => {
896                commands::containers::run(engine.as_deref(), json)
897            }
898            None => commands::caches::run(json),
899        },
900        Commands::Config { action } => match action {
901            Some(ConfigAction::Get { key }) => commands::config::run_get(&key),
902            Some(ConfigAction::Set { key, value }) => commands::config::run_set(&key, &value),
903            Some(ConfigAction::Show { update: true }) => commands::config::run_global_update(),
904            Some(ConfigAction::Show { update: false }) | None => commands::config::run_show(),
905            Some(ConfigAction::Recommended { with_cautious }) => {
906                commands::config::run_recommended(with_cautious)
907            }
908            Some(ConfigAction::Project { path, update, team }) => {
909                commands::config::run_path_config(&config::expand_tilde(&path), update, team)
910            }
911            Some(ConfigAction::Daemon { target, sub_action }) => {
912                // A toggle word (`on`, `off`) never starts with `~`, so expanding the
913                // target before the match cannot turn one into a path.
914                let target = target.map(|t| config::expand_tilde(&t));
915                let (path, action) = match (target.as_deref(), sub_action.as_deref()) {
916                    (Some(t), Some(a)) => (Some(t), a),
917                    (Some(t), None) if commands::config::is_toggle_word(t) => (None, t),
918                    (Some(t), None) => (Some(t), "status"),
919                    (None, Some(a)) => (None, a),
920                    (None, None) => (None, "status"),
921                };
922                commands::config::run_daemon_toggle(path, action)
923            }
924            Some(ConfigAction::Hook {
925                target,
926                sub_action,
927                chain,
928            }) => {
929                let target = target.map(|t| config::expand_tilde(&t));
930                let (path, action) = match (target.as_deref(), sub_action.as_deref()) {
931                    (Some(t), Some(a)) => (Some(t), a),
932                    (Some(t), None) if commands::config::is_toggle_word(t) => (None, t),
933                    (Some(t), None) => (Some(t), "status"),
934                    (None, Some(a)) => (None, a),
935                    // `--chain` on its own is an install instruction, not a status query.
936                    (None, None) if chain => (None, "install"),
937                    (None, None) => (None, "status"),
938                };
939                commands::config::run_hook_toggle(path, action, chain)
940            }
941            Some(ConfigAction::Icon) => commands::icon::run_install(),
942            Some(ConfigAction::Wizard { no_tui }) => {
943                commands::config::run_wizard(no_tui, commands::config::Opened::ByRequest)
944            }
945        },
946        Commands::Restore { path, last_run } => {
947            if last_run {
948                commands::restore::run_last_run()
949            } else {
950                commands::restore::run(&config::expand_tilde(path.as_deref().unwrap_or(".")))
951            }
952        }
953        Commands::Update {
954            offline,
955            install,
956            channels,
957        } => commands::update::run(offline, install, channels),
958        Commands::Skill { agent } => commands::skill::run(agent),
959        Commands::Setup { status } => commands::setup::run(status),
960        Commands::Doctor { path, fix } => {
961            let path = path.map(|p| config::expand_tilde(&p));
962            commands::doctor::run(path.as_deref(), fix)
963        }
964        Commands::Install { channel, dry_run } => commands::install::run(channel, dry_run, cli.yes),
965        Commands::Uninstall { deep } => commands::uninstall::run(deep, cli.yes),
966    };
967
968    if let Err(e) = result {
969        if is_broken_pipe(&e) {
970            std::process::exit(exit_code::OK);
971        }
972        output::print_error(&format!("{e:#}"));
973        if e.downcast_ref::<UsageError>().is_some() {
974            std::process::exit(exit_code::USAGE);
975        }
976        std::process::exit(exit_code::FAILURE);
977    }
978
979    // Only on the way out of a successful run: nobody reading an error message needs a
980    // credit under it.
981    if credit_the_author {
982        output::print_attribution();
983    }
984}
985
986#[cfg(test)]
987mod tests {
988    use super::auto_setup_allowed;
989
990    fn args(rest: &[&str]) -> Vec<String> {
991        std::iter::once("devp")
992            .chain(rest.iter().copied())
993            .map(String::from)
994            .collect()
995    }
996
997    #[test]
998    fn ordinary_interactive_commands_may_auto_setup() {
999        assert!(auto_setup_allowed(&args(&["status"])));
1000        assert!(auto_setup_allowed(&args(&["run", "--dry-run"])));
1001        assert!(auto_setup_allowed(&args(&[])));
1002    }
1003
1004    #[test]
1005    fn unattended_and_machine_read_invocations_may_not() {
1006        // The Git hook, the scheduler, and any `--json` consumer: a setup pass nobody
1007        // can see is one nobody can refuse, and setup output inside a JSON document is
1008        // a parse error.
1009        assert!(!auto_setup_allowed(&args(&["link", ".", "--quiet"])));
1010        assert!(!auto_setup_allowed(&args(&["run", "--daemon"])));
1011        assert!(!auto_setup_allowed(&args(&["status", "--json"])));
1012        assert!(!auto_setup_allowed(&args(&["uninstall"])));
1013        assert!(!auto_setup_allowed(&args(&["setup"])));
1014    }
1015}