dev-prune 1.6.0

Universal, lockfile-safe workspace pruner and background dependency cleaner
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Handler for `dev-prune trust`.
//
// A tool that deletes directories on a schedule has to answer "what exactly is this
// allowed to do on my machine?", and until this command existed the honest answer was
// "read four documentation pages and three `devp config` keys". This prints it.
//
// Two kinds of row, and the distinction is the whole point:
//
//   - **Guarantees** are structural. They come from the code paths in `engine.rs`, they
//     have no setting and no flag, and a build where one of them did not hold would be a
//     bug rather than a configuration. They read the same on every machine.
//   - **This machine** is read live — the scheduler, the Git hooks, the settings that
//     widen what dev-prune may do. These differ per machine and are the reason the
//     command exists at all.
//
// Nothing here is a self-assessment. Every "this machine" row is a value read back from
// the registry or the OS, and the three rows that can lower the verdict are named
// individually so the report cannot congratulate itself in the abstract.

use anyhow::Result;

use crate::commands::hook::{self, HookState};
use crate::config::Registry;
use crate::constants;
use crate::daemon;
use crate::json;
use crate::output;

/// What one row says about the state it reports.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    /// Structural, with no setting and no flag that changes it.
    Guaranteed,
    /// True on this machine, and the safe answer.
    Safe,
    /// True on this machine, and something the reader should know about. Never a
    /// failure — every one of these is a choice someone made deliberately.
    Widened,
    /// Neither safe nor widened: a fact worth printing, like where the config lives.
    Neutral,
}

impl Verdict {
    /// The glyph in front of the row.
    fn mark(self) -> &'static str {
        match self {
            Verdict::Guaranteed | Verdict::Safe => "+",
            Verdict::Widened => "!",
            Verdict::Neutral => " ",
        }
    }

    /// The word `--json` uses. Separate from the prose so rewording a row never breaks
    /// a script reading the document.
    fn key(self) -> &'static str {
        match self {
            Verdict::Guaranteed => "guaranteed",
            Verdict::Safe => "safe",
            Verdict::Widened => "widened",
            Verdict::Neutral => "neutral",
        }
    }
}

/// One line of the report.
pub struct TrustRow {
    /// Stable identifier for `--json`.
    pub key: &'static str,
    /// What is being reported, for a human.
    pub subject: &'static str,
    /// The state it is in, in the user's terms.
    pub state: String,
    /// How to read that state.
    pub verdict: Verdict,
}

impl TrustRow {
    fn new(
        key: &'static str,
        subject: &'static str,
        state: impl Into<String>,
        verdict: Verdict,
    ) -> Self {
        Self {
            key,
            subject,
            state: state.into(),
            verdict,
        }
    }

    /// The `--json` word for this row's verdict.
    pub fn verdict_key(&self) -> &'static str {
        self.verdict.key()
    }
}

/// The whole report.
pub struct TrustReport {
    /// Structural guarantees. Identical on every machine.
    pub guarantees: Vec<TrustRow>,
    /// Live state, read from the registry and the OS.
    pub machine: Vec<TrustRow>,
}

impl TrustReport {
    /// Every setting on this machine that widens what dev-prune may do without asking.
    ///
    /// Not a score. A list, because "trust level: MEDIUM" tells nobody which switch to
    /// look at, and the only useful version of this answer is the names.
    pub fn widened(&self) -> Vec<&str> {
        self.machine
            .iter()
            .filter(|r| r.verdict == Verdict::Widened)
            .map(|r| r.subject)
            .collect()
    }
}

/// Run the `trust` command.
pub fn run(json_output: bool) -> Result<()> {
    let registry = Registry::load()?;
    let report = build(&registry);

    if json_output {
        return json::emit(&json::trust_document(&report));
    }

    print_report(&report);
    Ok(())
}

/// Ask the OS its two questions at the same time.
///
/// These are the only two rows that shell out — `schtasks` and `git config` — and
/// together they were most of the second this report took to build. That second was
/// spent before the configurator drew anything at all, which read as a slow tool rather
/// than as two processes being waited on one after the other.
fn machine_answers() -> (String, String) {
    let scheduler = std::thread::spawn(scheduler_state);
    let hooks = hook_state();
    // A panic in the probe must not take the report down with it: the row's whole
    // purpose is to say what is unknown.
    let scheduler = scheduler
        .join()
        .unwrap_or_else(|_| "Unknown (the check did not finish)".to_string());
    (scheduler, hooks)
}

/// Say what is happening while [`machine_answers`] blocks, and erase it afterwards.
///
/// Asking Windows for a scheduled task costs a second on its own, and it happens before
/// the first screen of the configurator can be drawn — so without this the wizard opens
/// on an empty terminal for long enough to look hung. Stderr, so a piped `--json` run is
/// unaffected, and only when stderr is a terminal, so a log file never collects it.
fn with_progress<T>(work: impl FnOnce() -> T) -> T {
    use std::io::{IsTerminal, Write};

    let mut err = std::io::stderr();
    let show = err.is_terminal();
    if show {
        let _ = write!(err, "{}", constants::READING_MACHINE);
        let _ = err.flush();
    }
    let value = work();
    if show {
        // Carriage return and overwrite rather than an erase sequence: this runs before
        // the alternate screen is entered, on terminals that predate it.
        let _ = write!(
            err,
            "\r{:width$}\r",
            "",
            width = constants::READING_MACHINE.chars().count()
        );
        let _ = err.flush();
    }
    value
}

/// Assemble the report from the code's own guarantees and this machine's actual state.
///
/// `pub(crate)` because the first-run configurator opens on this same report: the
/// declaration a new user reads and what `devp trust` prints later must be the same
/// text, or one of them is a marketing claim.
pub(crate) fn build(registry: &Registry) -> TrustReport {
    TrustReport {
        guarantees: guarantees(),
        machine: machine_state(registry),
    }
}

/// The seven safety invariants plus the two promises that are not invariants but are
/// asked about just as often: no telemetry, and build outputs are never touched.
///
/// Every string here restates something enforced in `src/engine.rs` or `src/adapters/`.
/// [`docs/SAFETY_INVARIANTS.md`](../../docs/SAFETY_INVARIANTS.md) is the long form.
fn guarantees() -> Vec<TrustRow> {
    use Verdict::Guaranteed as G;
    vec![
        TrustRow::new(
            "filesystem_scope",
            "Filesystem scope",
            "Registered Git repositories only",
            G,
        ),
        TrustRow::new(
            "lockfile_verification",
            "Lockfile verification",
            "Required before every delete",
            G,
        ),
        TrustRow::new("symlinks", "Symlinks and junctions", "Refused", G),
        TrustRow::new(
            "nested_repositories",
            "Nested repositories",
            "Refused — no lockfile rebuilds someone else's history",
            G,
        ),
        TrustRow::new(
            "build_outputs",
            "Build outputs",
            "Never deleted — no dist/, no .next/, no .gitignore rules",
            G,
        ),
        TrustRow::new(
            "deletion_bypass",
            "Deletion bypass",
            "None — no flag disables a safety check",
            G,
        ),
        TrustRow::new(
            "state_writes",
            "State writes",
            "Atomic — temp file, then rename",
            G,
        ),
        TrustRow::new("telemetry", "Telemetry", "None — there is no endpoint", G),
        TrustRow::new(
            "restore",
            "Restore",
            "`devp restore --last-run` rebuilds the last pass",
            G,
        ),
    ]
}

/// Everything read back from this machine rather than asserted.
fn machine_state(registry: &Registry) -> Vec<TrustRow> {
    let s = &registry.settings;
    let (scheduler, hooks) = with_progress(machine_answers);
    let mut rows = vec![
        TrustRow::new(
            "network",
            "Network requests",
            if s.update_check {
                format!(
                    "Release check against GitHub, every {} days",
                    s.update_check_interval_days
                )
            } else {
                "None — the release check is off".to_string()
            },
            Verdict::Safe,
        ),
        TrustRow::new(
            "auto_update",
            "Auto-update",
            if s.auto_update {
                "On — dev-prune replaces its own binary"
            } else {
                "Off — updates only when you run `devp update`"
            },
            if s.auto_update {
                Verdict::Widened
            } else {
                Verdict::Safe
            },
        ),
        TrustRow::new(
            "confirmation",
            "Confirmation before deleting",
            if s.require_confirmation {
                "Required, except where you pass `--yes`"
            } else {
                "Off — `require_confirmation` is false"
            },
            if s.require_confirmation {
                Verdict::Safe
            } else {
                Verdict::Widened
            },
        ),
        TrustRow::new(
            "lockfile_rewrite",
            "Lockfile rewriting",
            if s.allow_manifest_rewrite {
                "Allowed — a stale lockfile is regenerated instead of refused"
            } else {
                "Refused — verification is read-only"
            },
            if s.allow_manifest_rewrite {
                Verdict::Widened
            } else {
                Verdict::Safe
            },
        ),
        TrustRow::new(
            "scheduler",
            "Background scheduler",
            scheduler,
            Verdict::Neutral,
        ),
        TrustRow::new("git_hooks", "Git hooks", hooks, Verdict::Neutral),
    ];

    // Opt-in adapters delete compiled output, which every other adapter refuses to do.
    // Someone reading this report to find out what is deletable on their machine needs
    // to see that they turned that on.
    let opt_in = opt_in_adapters(registry);
    rows.push(TrustRow::new(
        "opt_in_adapters",
        "Opt-in adapters",
        if opt_in.is_empty() {
            "None — only dependency directories are deletable".to_string()
        } else {
            format!("{} — build trees are deletable too", opt_in.join(", "))
        },
        if opt_in.is_empty() {
            Verdict::Safe
        } else {
            Verdict::Widened
        },
    ));

    rows.push(TrustRow::new(
        "repositories",
        "Registered repositories",
        format!(
            "{} — nothing outside them is ever read or written",
            registry.repositories.len()
        ),
        Verdict::Neutral,
    ));
    rows.push(TrustRow::new(
        "idle_window",
        "Idle window",
        format!(
            "{} days of no commits and no file changes ({} for build trees, before any per-adapter window)",
            s.idle_days,
            s.build_idle_days.max(s.idle_days)
        ),
        Verdict::Neutral,
    ));
    // The managed path, not `current_exe()`: on Windows the scheduler runs a patched
    // twin and `devp update` replaces the managed copy, so the path that matters to
    // someone asking what runs on this machine is the one dev-prune owns.
    rows.push(TrustRow::new(
        "binary",
        "Managed binary",
        output::clean_path(daemon::get_exe_path()),
        Verdict::Neutral,
    ));

    rows
}

/// Which opt-in adapters are switched on, in the order the report should name them.
fn opt_in_adapters(registry: &Registry) -> Vec<&'static str> {
    let s = &registry.settings;
    [
        ("cargo", s.enable_cargo),
        ("gradle", s.enable_gradle),
        ("maven", s.enable_maven),
        ("swift", s.enable_swift),
        ("dart", s.enable_dart),
    ]
    .into_iter()
    .filter_map(|(name, on)| on.then_some(name))
    .collect()
}

/// Whether anything prunes on its own on this machine.
fn scheduler_state() -> String {
    match daemon::daemon_status() {
        Ok(daemon::DaemonStatus::Installed) => "Installed — prunes on its own".to_string(),
        Ok(daemon::DaemonStatus::NotInstalled) => {
            "Not installed — nothing runs unless you run it".to_string()
        }
        Ok(daemon::DaemonStatus::Unknown(why)) => format!("Unknown ({why})"),
        Err(e) => format!("Unknown ({e})"),
    }
}

/// Whether Git hooks auto-register repositories on this machine.
fn hook_state() -> String {
    if !hook::git_available() {
        return "Not installed — git is not on PATH".to_string();
    }
    match hook::state() {
        Ok(HookState::Active) => "Installed — new repositories register themselves".to_string(),
        Ok(HookState::Absent) => {
            "Not installed — repositories register only when you say so".to_string()
        }
        Ok(HookState::Chained { previous, .. }) => {
            format!("Installed, chained to `{previous}`")
        }
        Ok(HookState::Foreign(p)) => format!("Not ours — `core.hooksPath` belongs to `{p}`"),
        Err(e) => format!("Unknown ({e})"),
    }
}

fn print_report(report: &TrustReport) {
    output::print_header(&format!("What dev-prune {} may do", constants::VERSION));

    println!();
    println!("  Guaranteed by the code, on every machine");
    println!();
    for row in &report.guarantees {
        print_row(row);
    }

    println!();
    println!("  On this machine");
    println!();
    for row in &report.machine {
        print_row(row);
    }

    println!();
    let widened = report.widened();
    if widened.is_empty() {
        output::print_success(
            "Nothing on this machine widens what dev-prune may do without asking.",
        );
    } else {
        output::print_info(&format!(
            "{} {} what dev-prune may do without asking: {}. Each was switched on \
             deliberately; `devp config show` has them.",
            widened.len(),
            if widened.len() == 1 {
                "setting widens"
            } else {
                "settings widen"
            },
            widened.join(", ")
        ));
    }
    output::print_info(
        "The guarantees above are enforced in `src/engine.rs` and described in full at \
         docs/SAFETY_INVARIANTS.md. None of them has a bypass flag.",
    );
}

fn print_row(row: &TrustRow) {
    println!(
        "  {}  {:<30} {}",
        row.verdict.mark(),
        row.subject,
        row.state
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_default_machine_widens_nothing() {
        let registry = Registry::default();
        let report = build(&registry);
        assert!(
            report.widened().is_empty(),
            "a fresh install reports {:?} as widened",
            report.widened()
        );
    }

    #[test]
    fn every_widening_setting_shows_up_by_name() {
        let mut registry = Registry::default();
        registry.settings.auto_update = true;
        registry.settings.require_confirmation = false;
        registry.settings.allow_manifest_rewrite = true;
        registry.settings.enable_gradle = true;

        let report = build(&registry);
        let widened = report.widened();
        assert_eq!(widened.len(), 4, "got {widened:?}");
        // Named, not counted: a report that says "3 settings" and stops is a report
        // nobody can act on.
        assert!(widened.contains(&"Auto-update"));
        assert!(widened.contains(&"Opt-in adapters"));
    }

    #[test]
    fn opt_in_adapters_are_listed_in_a_stable_order() {
        let mut registry = Registry::default();
        registry.settings.enable_swift = true;
        registry.settings.enable_gradle = true;
        assert_eq!(opt_in_adapters(&registry), vec!["gradle", "swift"]);
    }

    #[test]
    fn every_row_key_is_unique() {
        // The keys are the `--json` contract; two rows sharing one silently drops a
        // fact from the document.
        let report = build(&Registry::default());
        let mut keys: Vec<&str> = report
            .guarantees
            .iter()
            .chain(report.machine.iter())
            .map(|r| r.key)
            .collect();
        let total = keys.len();
        keys.sort_unstable();
        keys.dedup();
        assert_eq!(keys.len(), total);
    }

    #[test]
    fn guarantees_never_depend_on_settings() {
        // If a "guarantee" could be turned off it would not be one, and the report would
        // be claiming something the code does not enforce.
        let mut registry = Registry::default();
        registry.settings.allow_manifest_rewrite = true;
        registry.settings.auto_update = true;
        let with = build(&registry);
        let without = build(&Registry::default());

        let states = |r: &TrustReport| -> Vec<String> {
            r.guarantees.iter().map(|g| g.state.clone()).collect()
        };
        assert_eq!(states(&with), states(&without));
    }
}