dev-prune 1.1.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Machine-readable output for `--json`.
//
// This module is the whole contract. Every field an AI agent, CI step or script can rely
// on is built here, so there is exactly one place to look when asking "what does
// dev-prune emit?" and exactly one place to change when the answer moves.
//
// ## Stability
//
// `schema` is an integer that increases when a consumer would have to change to keep
// working: a field removed, renamed, or given a different meaning. *Adding* a field does
// not bump it, so parse permissively and ignore what you do not recognise.
//
// Paths are emitted through `output::clean_path`, which is what the human output shows,
// so the two never disagree about what a repository is called.

use serde_json::{Value, json};

use crate::config::{Registry, Settings};
use crate::constants;
use crate::engine::{PruneResult, PruneStatus, RepoStatusEntry, SkipReason};
use crate::output::clean_path;

/// Current output schema version. See the module docs before changing it.
pub const SCHEMA_VERSION: u32 = 1;

/// The stable machine name for a prune outcome.
///
/// Deliberately not the `Display` string: the human text is free to be reworded, these
/// are not. Keep them lowercase snake_case and never reuse a retired one.
fn status_tag(status: &PruneStatus) -> &'static str {
    match status {
        PruneStatus::Pruned => "pruned",
        PruneStatus::SkippedActive => "skipped_active",
        PruneStatus::SkippedDryRun => "skipped_dry_run",
        PruneStatus::LockfileError(_) => "lockfile_error",
        PruneStatus::ActivityCheckError(_) => "activity_check_error",
        PruneStatus::PathMissing => "path_missing",
        PruneStatus::NoBloat => "no_bloat",
        PruneStatus::Disabled => "disabled",
        PruneStatus::SkippedIgnored => "ignored",
        PruneStatus::DeleteError(_) => "delete_error",
        PruneStatus::ConfigError(_) => "config_error",
        PruneStatus::SkippedSymlink(_) => "skipped_symlink",
    }
}

/// The detail carried by the failure variants, if any.
fn status_message(status: &PruneStatus) -> Option<&str> {
    match status {
        PruneStatus::LockfileError(e)
        | PruneStatus::ActivityCheckError(e)
        | PruneStatus::DeleteError(e)
        | PruneStatus::ConfigError(e)
        | PruneStatus::SkippedSymlink(e) => Some(e.trim()),
        _ => None,
    }
}

/// The command an agent should run to fix a failed lockfile check, or `None` when the
/// failure is not of that kind.
///
/// This is the single reason an agent can act on a `lockfile_error` without a human:
/// the fix is mechanical and the same one the human report prints.
///
/// Each of these is the *writing* form of that adapter's verification — the one
/// [`crate::adapters::enforce_two_tier`] refuses to run on the user's behalf unless
/// they set `allow_manifest_rewrite`. It resyncs the lockfile with the manifest, which
/// is exactly what a failed read-only verification is complaining about.
pub fn lockfile_fix_command(adapter: &str) -> Option<&'static str> {
    Some(match adapter {
        "npm" => "npm install --package-lock-only --ignore-scripts",
        "pnpm" => "pnpm install --lockfile-only",
        "yarn" => "yarn install --mode update-lockfile",
        // bun has no resolve-only write mode; a plain install is what refreshes
        // `bun.lock`, and unlike the others it also populates `node_modules`.
        "bun" => "bun install",
        "uv" => "uv lock",
        "cargo" => "cargo generate-lockfile",
        "go" => "go mod tidy",
        // venv has no lockfile to regenerate — the fix is to write `requirements.txt`,
        // which is authoring work, not a command we can hand over.
        _ => return None,
    })
}

fn result_value(result: &PruneResult) -> Value {
    let mut obj = json!({
        "repository": clean_path(&result.repo_path),
        "adapter": result.adapter_name,
        "directory": result.bloat_dir,
        "status": status_tag(&result.status),
        "bytes": result.size_freed,
        "shared_bytes": result.shared_bytes,
    });

    if let Some(message) = status_message(&result.status) {
        obj["message"] = json!(message);
    }
    if matches!(result.status, PruneStatus::LockfileError(_)) {
        if let Some(fix) = lockfile_fix_command(&result.adapter_name) {
            obj["fix_command"] = json!(fix);
        }
    }
    obj
}

/// The document emitted by `devp run --json`.
///
/// `summary.errors` counts results whose status is one of the four failure tags; a
/// consumer that only wants to know "did anything go wrong" can read that alone.
pub fn run_document(results: &[PruneResult], dry_run: bool) -> Value {
    let bytes_freed: u64 = results
        .iter()
        .filter(|r| matches!(r.status, PruneStatus::Pruned))
        .map(|r| r.size_freed)
        .sum();
    let directories_pruned = results
        .iter()
        .filter(|r| matches!(r.status, PruneStatus::Pruned))
        .count();
    let bytes_reclaimable: u64 = results
        .iter()
        .filter(|r| matches!(r.status, PruneStatus::SkippedDryRun))
        .map(|r| r.size_freed)
        .sum();
    let errors = results
        .iter()
        .filter(|r| {
            matches!(
                r.status,
                PruneStatus::LockfileError(_)
                    | PruneStatus::ActivityCheckError(_)
                    | PruneStatus::DeleteError(_)
                    | PruneStatus::ConfigError(_)
            )
        })
        .count();

    json!({
        "schema": SCHEMA_VERSION,
        "version": constants::VERSION,
        "command": "run",
        "dry_run": dry_run,
        "results": results.iter().map(result_value).collect::<Vec<_>>(),
        "summary": {
            "bytes_freed": bytes_freed,
            "bytes_reclaimable": bytes_reclaimable,
            "directories_pruned": directories_pruned,
            "errors": errors,
        },
    })
}

/// The stable machine name for why a repository is or is not a candidate.
fn reason_tag(reason: &SkipReason) -> &'static str {
    match reason {
        SkipReason::Candidate => "candidate",
        SkipReason::Active => "active",
        SkipReason::Ignored => "ignored",
        SkipReason::NoBloat => "no_bloat",
        SkipReason::PathMissing => "path_missing",
        SkipReason::ConfigError(_) => "config_error",
    }
}

fn settings_value(settings: &Settings) -> Value {
    json!({
        "idle_days": settings.idle_days,
        "check_interval_days": settings.check_interval_days,
        "auto_setup": settings.auto_setup,
        "auto_hooks": settings.auto_hooks,
        "auto_daemon": settings.auto_daemon,
        "require_confirmation": settings.require_confirmation,
        "command_timeout_secs": settings.command_timeout_secs,
        "min_size_mb": settings.min_size_mb,
        "update_check": settings.update_check,
    })
}

fn repo_value(entry: &RepoStatusEntry) -> Value {
    let mut obj = json!({
        "path": clean_path(&entry.path),
        "state": reason_tag(&entry.reason),
        "enabled": entry.entry.enabled,
        "idle_days": entry.idle_days,
        "last_activity": entry.last_activity.map(|t| t.to_rfc3339()),
        "last_pruned_at": entry.entry.last_pruned_at.map(|t| t.to_rfc3339()),
        "added_at": entry.entry.added_at.to_rfc3339(),
        "adapters": entry.adapters,
        "reclaimable_bytes": entry.reclaimable_bytes,
        "directories": entry.bloat_dirs.iter().map(|b| json!({
            "name": b.name,
            "path": clean_path(&b.path),
            "bytes": b.size_bytes,
            "shared_bytes": b.shared_bytes,
        })).collect::<Vec<_>>(),
    });

    // Present only on `config_error`, and absent rather than null everywhere else — the
    // same rule `result_value` follows for `message`, so one parser handles both
    // documents. It carries the actual parse failure, so an agent can report what is
    // wrong with the file instead of only the state word.
    if let SkipReason::ConfigError(e) = &entry.reason {
        obj["error"] = json!(e);
    }
    obj
}

/// The document emitted by `devp status --json`.
///
/// `daemon` and `hooks` are the same strings the dashboard shows; they describe the
/// state of the machine's integrations, which is what an agent needs to decide whether
/// to suggest `devp setup`.
///
/// `top` trims the `repositories` array only. `totals` is always computed over every
/// registered repository, and `top` is echoed back so a consumer can tell a short list
/// from a tidy machine.
pub fn status_document(
    registry: &Registry,
    repos: &[RepoStatusEntry],
    daemon: &str,
    hooks: &str,
    top: Option<usize>,
) -> Value {
    let reclaimable: u64 = repos.iter().map(|r| r.reclaimable_bytes).sum();
    let candidates = repos
        .iter()
        .filter(|r| matches!(r.reason, SkipReason::Candidate))
        .count();
    let listed = crate::engine::take_top(repos, top);

    let mut doc = json!({
        "schema": SCHEMA_VERSION,
        "version": constants::VERSION,
        "command": "status",
        "config_path": Registry::registry_path().map(|p| clean_path(&p)).ok(),
        "integrations": { "daemon": daemon, "git_hooks": hooks },
        "settings": settings_value(&registry.settings),
        "totals": {
            "repositories": registry.repo_count(),
            "candidates": candidates,
            "reclaimable_bytes": reclaimable,
            "historical_bytes_freed": registry.total_freed_bytes,
            "prune_passes": registry.total_pruned_count,
        },
        "repositories": listed.iter().map(repo_value).collect::<Vec<_>>(),
    });

    // Absent rather than null when the whole list is present, the same rule `message`
    // and `note` follow elsewhere in this contract.
    if let Some(n) = top {
        doc["top"] = json!(n);
    }
    doc
}

/// The document emitted by `devp stats --json`.
///
/// Three different vintages of number live here, and the field names say which is which.
/// `lifetime` has been accumulating since 1.0.0. `recent_passes` and the `bytes_freed`
/// inside `repositories` are only recorded from 1.1.0 onward, so on an upgraded machine
/// they start near zero while `lifetime` does not — `history_starts_at` names the version
/// that changed, so a consumer can say so rather than reporting a regression.
pub fn stats_document(registry: &Registry) -> Value {
    let mut repos: Vec<(&std::path::PathBuf, &crate::config::RepoEntry)> =
        registry.repositories.iter().collect();
    repos.sort_by(|a, b| {
        b.1.total_freed_bytes
            .cmp(&a.1.total_freed_bytes)
            .then_with(|| a.0.cmp(b.0))
    });

    json!({
        "schema": SCHEMA_VERSION,
        "version": constants::VERSION,
        "command": "stats",
        "history_starts_at": constants::HISTORY_STARTS_AT,
        "lifetime": {
            "bytes_freed": registry.total_freed_bytes,
            // Same name and same number as `totals.prune_passes` in the status document.
            // One per pass that deleted something, wherever it was started from.
            "prune_passes": registry.total_pruned_count,
            "repositories": registry.repo_count(),
        },
        "last_prune": registry.last_prune.as_ref().map(|p| json!({
            "at": p.at.to_rfc3339(),
            "bytes_freed": p.dirs.iter().map(|d| d.size_freed).sum::<u64>(),
            "directories": p.dirs.len(),
        })),
        "recent_passes": registry.prune_history.iter().rev().map(|p| json!({
            "at": p.at.to_rfc3339(),
            "bytes_freed": p.bytes_freed,
            "directories": p.dirs_removed,
            "repositories": p.repos_touched,
        })).collect::<Vec<_>>(),
        "repositories": repos.iter().map(|(path, entry)| json!({
            "path": clean_path(path),
            "bytes_freed": entry.total_freed_bytes,
            "last_pruned_at": entry.last_pruned_at.map(|t| t.to_rfc3339()),
        })).collect::<Vec<_>>(),
    })
}

/// The document emitted by `devp caches --json`.
///
/// `clear_command` is the one field an agent can act on, and it is the only place in this
/// contract that carries a command dev-prune will not run itself: these caches are shared
/// by every project on the machine, so clearing one is a human's decision. `note` is
/// present only where there is a cost beyond time.
pub fn caches_document(reports: &[crate::commands::caches::CacheReport]) -> Value {
    let total: u64 = reports.iter().map(|r| r.bytes).sum();

    let caches: Vec<Value> = reports
        .iter()
        .map(|r| {
            let mut obj = json!({
                "manager": r.manager,
                "kind": r.kind,
                "path": clean_path(&r.path),
                "bytes": r.bytes,
                "clear_command": r.clear_command,
            });
            if let Some(note) = r.note {
                obj["note"] = json!(note);
            }
            obj
        })
        .collect();

    json!({
        "schema": SCHEMA_VERSION,
        "version": constants::VERSION,
        "command": "caches",
        "caches": caches,
        "summary": {
            "total_bytes": total,
            "count": reports.len(),
        },
    })
}

/// The document emitted by `devp status --drift --json`.
///
/// A separate document from plain `status` because it answers a different question:
/// not "what could a prune reclaim" but "what would a prune refuse, and why". An empty
/// `drift` array means nothing was *detected*, across the adapters that can compare an
/// environment against its lockfile from files alone.
pub fn drift_document(findings: &[crate::commands::status::ProjectDrift]) -> Value {
    let unrecorded_total: usize = findings.iter().map(|f| f.report.unrecorded.len()).sum();

    json!({
        "schema": SCHEMA_VERSION,
        "version": constants::VERSION,
        "command": "status --drift",
        "drift": findings.iter().map(|f| json!({
            "repository": clean_path(&f.repository),
            "project": f.project,
            "adapter": f.adapter,
            "directory": f.report.directory,
            "unrecorded": f.report.unrecorded,
            "record_command": f.report.record_command,
        })).collect::<Vec<_>>(),
        "summary": {
            "projects_with_drift": findings.len(),
            "unrecorded_packages": unrecorded_total,
        },
    })
}

/// Print a document to stdout as pretty JSON with a trailing newline.
///
/// Pretty rather than compact because a human reads this output far more often than a
/// parser does, and `jq` does not care either way.
pub fn emit(document: &Value) -> anyhow::Result<()> {
    println!("{}", serde_json::to_string_pretty(document)?);
    Ok(())
}

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

    fn result(status: PruneStatus, bytes: u64) -> PruneResult {
        PruneResult {
            repo_path: PathBuf::from("/tmp/repo"),
            adapter_name: "pnpm".to_string(),
            bloat_dir: "node_modules".to_string(),
            size_freed: bytes,
            shared_bytes: 0,
            status,
        }
    }

    #[test]
    fn every_status_has_a_distinct_stable_tag() {
        let all = [
            PruneStatus::Pruned,
            PruneStatus::SkippedActive,
            PruneStatus::SkippedDryRun,
            PruneStatus::LockfileError("x".into()),
            PruneStatus::ActivityCheckError("x".into()),
            PruneStatus::PathMissing,
            PruneStatus::NoBloat,
            PruneStatus::Disabled,
            PruneStatus::SkippedIgnored,
            PruneStatus::DeleteError("x".into()),
            PruneStatus::ConfigError("x".into()),
            PruneStatus::SkippedSymlink("x".into()),
        ];
        let mut tags: Vec<&str> = all.iter().map(status_tag).collect();
        let count = tags.len();
        tags.sort_unstable();
        tags.dedup();
        assert_eq!(tags.len(), count, "two statuses share a JSON tag");
    }

    #[test]
    fn every_repository_state_has_a_distinct_stable_tag() {
        let all = [
            SkipReason::Candidate,
            SkipReason::Active,
            SkipReason::Ignored,
            SkipReason::NoBloat,
            SkipReason::PathMissing,
            SkipReason::ConfigError("x".into()),
        ];
        let mut tags: Vec<&str> = all.iter().map(reason_tag).collect();
        let count = tags.len();
        tags.sort_unstable();
        tags.dedup();
        assert_eq!(tags.len(), count, "two repository states share a JSON tag");
    }

    #[test]
    fn only_an_unreadable_config_carries_an_error_field() {
        let entry = |reason| RepoStatusEntry {
            path: PathBuf::from("/tmp/repo"),
            entry: crate::config::RepoEntry::new(),
            reason,
            adapters: Vec::new(),
            bloat_dirs: Vec::new(),
            reclaimable_bytes: 0,
            last_activity: None,
            idle_days: 15,
        };

        let broken = repo_value(&entry(SkipReason::ConfigError("bad json".into())));
        assert_eq!(broken["state"], "config_error");
        assert_eq!(broken["error"], "bad json");

        // Absent, not null — the same shape rule `message` follows in the run document.
        let healthy = repo_value(&entry(SkipReason::Candidate));
        assert!(healthy.get("error").is_none());
    }

    #[test]
    fn run_summary_counts_only_real_deletions() {
        let doc = run_document(
            &[
                result(PruneStatus::Pruned, 100),
                result(PruneStatus::Pruned, 50),
                result(PruneStatus::SkippedActive, 0),
                result(PruneStatus::LockfileError("nope".into()), 0),
            ],
            false,
        );
        assert_eq!(doc["summary"]["bytes_freed"], 150);
        assert_eq!(doc["summary"]["directories_pruned"], 2);
        assert_eq!(doc["summary"]["errors"], 1);
    }

    #[test]
    fn dry_run_bytes_land_in_reclaimable_not_freed() {
        // A dry run must never claim to have freed anything — a CI step that adds up
        // `bytes_freed` across runs would otherwise report space that still exists.
        let doc = run_document(&[result(PruneStatus::SkippedDryRun, 4096)], true);
        assert_eq!(doc["summary"]["bytes_freed"], 0);
        assert_eq!(doc["summary"]["bytes_reclaimable"], 4096);
        assert_eq!(doc["dry_run"], true);
    }

    #[test]
    fn lockfile_errors_carry_the_fix_command() {
        let doc = run_document(
            &[result(PruneStatus::LockfileError("boom".into()), 0)],
            false,
        );
        assert_eq!(doc["results"][0]["message"], "boom");
        assert_eq!(
            doc["results"][0]["fix_command"],
            "pnpm install --lockfile-only"
        );
    }

    #[test]
    fn a_successful_result_carries_no_message_or_fix() {
        let doc = run_document(&[result(PruneStatus::Pruned, 1)], false);
        assert!(doc["results"][0].get("message").is_none());
        assert!(doc["results"][0].get("fix_command").is_none());
    }

    #[test]
    fn venv_has_no_mechanical_lockfile_fix() {
        // There is no command that writes a requirements.txt, so offering one would be
        // a lie an agent would then run.
        assert!(lockfile_fix_command("venv").is_none());
        assert!(lockfile_fix_command("nonsense").is_none());
    }

    #[test]
    fn the_cache_report_totals_what_it_lists() {
        use crate::commands::caches::CacheReport;

        let doc = caches_document(&[
            CacheReport {
                manager: "go",
                kind: "module cache",
                path: PathBuf::from("/home/dev/go/pkg/mod"),
                bytes: 4_000,
                clear_command: "go clean -modcache",
                note: None,
            },
            CacheReport {
                manager: "pnpm",
                kind: "store",
                path: PathBuf::from("/home/dev/.pnpm-store"),
                bytes: 1_000,
                clear_command: "pnpm store prune",
                note: Some("hardlinked"),
            },
        ]);

        assert_eq!(doc["command"], "caches");
        assert_eq!(doc["summary"]["total_bytes"], 5_000);
        assert_eq!(doc["summary"]["count"], 2);
        // Absent rather than null where there is nothing to say, matching every other
        // optional field in this contract.
        assert!(doc["caches"][0].get("note").is_none());
        assert_eq!(doc["caches"][1]["note"], "hardlinked");
        assert_eq!(doc["caches"][0]["clear_command"], "go clean -modcache");
    }

    #[test]
    fn an_empty_cache_report_is_still_a_document() {
        // A machine with no package manager installed must produce a parseable zero, not
        // an absent `summary` a consumer would have to special-case.
        let doc = caches_document(&[]);
        assert_eq!(doc["summary"]["total_bytes"], 0);
        assert_eq!(doc["caches"].as_array().unwrap().len(), 0);
    }

    #[test]
    fn every_adapter_with_a_lockfile_has_a_fix_command() {
        for adapter in crate::adapters::get_all_adapters() {
            if adapter.name() == "venv" {
                continue;
            }
            assert!(
                lockfile_fix_command(adapter.name()).is_some(),
                "{} has no fix command",
                adapter.name()
            );
        }
    }
}