cargo-cleanme 0.2.13

Safely clean inactive Cargo build artifacts through Cargo
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
use std::{
    path::PathBuf,
    time::{Duration, SystemTime},
};

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScanRequest {
    pub cli_root: Option<PathBuf>,
    pub full: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ScanScope {
    Explicit(PathBuf),
    /// Multiple explicit roots forming one discovery boundary (cleanup only).
    ExplicitRoots(Vec<PathBuf>),
    Global(Vec<PathBuf>),
    Routine(Vec<PathBuf>),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DiscoveryFilters {
    Active {
        ignore: Vec<String>,
        unignore: Vec<PathBuf>,
    },
    Bypassed,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectiveScanPolicy {
    pub recency: Duration,
    pub scope: ScanScope,
    pub discovery_filters: DiscoveryFilters,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiscoveredProject {
    pub project_root: PathBuf,
    pub manifest_path: PathBuf,
    pub target_path: PathBuf,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ActivityState {
    Active,
    Inactive,
    Uncertain,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SizeMetric {
    Allocated,
    Apparent,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiagnosticSeverity {
    Info,
    Warning,
    Error,
}

impl DiagnosticSeverity {
    /// Stable machine label; the JSON contract must not depend on `Debug`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
        }
    }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiagnosticCategory {
    PermissionDenied,
    Vanished,
    Metadata,
    InvalidEntry,
    PlatformRoot,
    CandidateUncertain,
    /// ADR 007: an unprovable participant outside the selected proof
    /// boundary. Reported, never blocking. Informational by construction.
    OutOfScope,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScanDiagnostic {
    pub severity: DiagnosticSeverity,
    pub category: DiagnosticCategory,
    pub path: Option<PathBuf>,
    pub message: String,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ScanReport {
    pub groups: Vec<EligibleOutputGroup>,
    pub diagnostics: Vec<ScanDiagnostic>,
    pub discovered: u64,
    pub visited_entries: u64,
    pub counters: ScanCounters,
}

/// Stable workspace identity: canonical workspace root directory.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct WorkspaceId(pub PathBuf);

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceMember {
    pub manifest_path: PathBuf,
    pub source_root: PathBuf,
}

/// Cargo package identity retained for selector validation; package specs are
/// never resolved by filesystem substring or target-directory inference.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct WorkspacePackage {
    pub id: String,
    pub name: String,
    pub version: String,
    pub manifest_path: PathBuf,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CargoBuildDirCapability {
    /// Pre-1.91 metadata without `build_directory` and no env evidence.
    Unavailable,
    /// Modern Cargo reports equal target/build.
    Equal,
    /// Modern Cargo reports distinct target/build.
    Distinct,
    /// Malformed, unknown, or env-only evidence; conservative handling.
    Unknown,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CargoCapabilities {
    pub build_dir: CargoBuildDirCapability,
    pub metadata_had_build_directory: bool,
    pub env_build_dir_set: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct CargoCleanCapabilities {
    pub profile_selector: bool,
    pub package_selector: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OutputRootKind {
    Target,
    Build,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OutputRoot {
    pub kind: OutputRootKind,
    pub logical_path: PathBuf,
    pub physical_path: Option<PathBuf>,
    pub exists: bool,
    pub is_symlink: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OutputSet {
    pub target: OutputRoot,
    pub build: OutputRoot,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedWorkspace {
    pub id: WorkspaceId,
    pub root: PathBuf,
    pub root_manifest: PathBuf,
    pub members: Vec<WorkspaceMember>,
    pub packages: Vec<WorkspacePackage>,
    pub output: OutputSet,
    pub capability: CargoCapabilities,
    /// Package directories inside this workspace that Cargo refused to treat
    /// as members ("current package believes it's in a workspace when it's
    /// not") and named this workspace as their owner.
    ///
    /// They are not members, so metadata never lists a target directory for
    /// them. A conventional `<package>/target` that exists is still Cargo
    /// output of this workspace: `cargo clean` on the package manifest fails,
    /// and `cargo clean` of the workspace target does not reach it.
    pub nested_package_roots: Vec<PathBuf>,
}

/// What an unresolved manifest proves about its own byte-ownership (M015).
///
/// The proof-island certificate distinguishes unknowns Cargo itself refused —
/// no Cargo command can place output for them, so they merge nothing — from
/// unknowns whose byte-capability is unproven and therefore merge every
/// island. The class is recorded where the failure is classified, never
/// re-parsed from message text: a copy-edit to a diagnostic must not silently
/// reclassify an unknown from merging to non-merging.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UnknownCapability {
    /// `cargo locate-project` ran and refused the manifest (nonzero exit):
    /// the manifest is in no workspace Cargo can see, so it owns no bytes.
    /// Transport failures, unparseable output, and lost workers are *not*
    /// this class — Cargo never examined the manifest there.
    RefusedByCargo,
    /// Byte-capability unproven: transport, unparseable output, lost worker,
    /// metadata, identity, and discovery-hole unknowns. Merges everything.
    Unproven,
}

/// Why a discovered manifest did not receive authoritative Cargo coverage.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnresolvedOwnershipParticipant {
    pub manifest: PathBuf,
    pub stage: &'static str,
    pub reason: String,
    pub capability: UnknownCapability,
}

/// Workspace resolution plus explicit coverage of the discovered manifest set.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ResolutionCoverage {
    pub workspaces: Vec<ResolvedWorkspace>,
    pub unresolved: Vec<UnresolvedOwnershipParticipant>,
    pub discovered_manifest_count: usize,
}

/// The coverage verdict for one walk root.
///
/// M018: the Full cleanup's proof boundary is the learned root. A root is
/// *proven* when its own traversal completed with no traversal error and no
/// unusable-root condition, and *unproven* otherwise. The verdict is per root
/// because the granularity of the underlying failure is the whole root:
/// `dua-core`'s error event carries a bare `io::Error` with no child path,
/// only the root index — so a subtree's incompleteness cannot be attributed
/// below the root that contains it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RootCoverage {
    /// The root as it was spelled for the walk.
    pub root: PathBuf,
    /// The canonical identity of the root, used to match a learned root to its
    /// verdict.
    pub canonical_root: PathBuf,
    /// Whether this root's own traversal completed.
    pub complete: bool,
    /// Traversal errors attributed to this root.
    pub error_events: u64,
    /// Of those, the ones that were permission-denied.
    pub permission_denied: u64,
    /// Of those, the ones that were "vanished" (not found).
    pub vanished: u64,
    /// Why the root is not complete, in operator-facing words. `None` when it
    /// is complete.
    pub detail: Option<String>,
}

/// A learned root whose coverage could not be proven.
///
/// M018: the Full cleanup cleans the learned roots it can prove and reports
/// the ones it cannot. An unproven root's workspaces stay in the discovery
/// universe — discovered, resolved, sized and classified like every other
/// unit — but they are removed from the *candidate* set, so a shared output
/// between a proven root and an unproven one stays `Shared` and stays
/// inventory-only.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnprovenRoot {
    /// The learned root as the discovery state recorded it.
    pub root: PathBuf,
    /// Why the root's coverage could not be proven, in operator-facing words.
    pub detail: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OutputOwnershipClass {
    PrivateBounded,
    ExternalUnproven,
    Shared,
    Uncertain,
}

impl OutputOwnershipClass {
    pub fn label(self) -> &'static str {
        match self {
            Self::PrivateBounded => "private",
            Self::ExternalUnproven => "external-unproven",
            Self::Shared => "shared",
            Self::Uncertain => "uncertain",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PhysicalOutputGroup {
    /// Minimal covering canonical roots for measurement (outermost only).
    pub covering_roots: Vec<PathBuf>,
    /// All canonical physical paths contributing to the group.
    pub physical_paths: Vec<PathBuf>,
    /// Primary display path (first covering root, deterministic).
    pub display_path: PathBuf,
    pub owners: Vec<WorkspaceId>,
    pub ownership: OutputOwnershipClass,
    pub bytes: u64,
    pub metric: SizeMetric,
    pub newest_mtime: Option<SystemTime>,
    pub artifact_entries: u64,
    pub uncertain: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EligibleOutputGroup {
    pub display_path: PathBuf,
    pub workspace_roots: Vec<PathBuf>,
    pub physical_paths: Vec<PathBuf>,
    pub bytes: u64,
    pub metric: SizeMetric,
    pub newest_mtime: Option<SystemTime>,
    pub artifact_entries: u64,
    pub ownership: OutputOwnershipClass,
}

/// Fail-fast gate instrumentation. Counts workspaces/groups exiting at each gate.
///
/// Timing fields (`*_nanos`) accumulate wall time spent in each phase/process
/// (C002 §7.7). They are `u64` nanosecond counts to preserve `Eq`.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ScanCounters {
    pub directories_visited: u64,
    pub directories_pruned: u64,
    pub platform_system_prunes: u64,
    pub cargo_home_prunes: u64,
    pub rustup_home_prunes: u64,
    pub target_vcs_prunes: u64,
    pub user_ignore_prunes: u64,
    pub manifests_found: u64,
    pub unique_workspaces: u64,
    pub cargo_locate_calls: u64,
    pub cargo_metadata_calls: u64,
    pub cargo_failures: u64,
    /// Discovered cleanup-scope manifests not authoritatively covered by
    /// Cargo workspace metadata. Kept separate from subprocess failures.
    pub unresolved_ownership: u64,
    pub empty_no_output_skipped: u64,
    pub active_skipped: u64,
    pub groups_measured: u64,
    pub bytes_measured: u64,
    pub reportable_groups: u64,
    pub deduped_workspace_hits: u64,
    pub missing_output_skipped: u64,
    pub uncertain_skipped: u64,
    pub discovery_nanos: u64,
    pub cargo_locate_nanos: u64,
    pub cargo_metadata_nanos: u64,
    pub source_activity_nanos: u64,
    pub output_sizing_nanos: u64,
    /// C003 §7.6: final-proof ownership-universe re-resolution work, kept
    /// separate from the initial discovery counters so `--stats` cannot hide it.
    pub proof_workspaces_refreshed: u64,
    pub proof_metadata_peak_concurrency: u64,
    pub proof_cargo_locate_calls: u64,
    pub proof_cargo_metadata_calls: u64,
    pub proof_cargo_locate_nanos: u64,
    pub proof_cargo_metadata_nanos: u64,
    pub proof_source_activity_nanos: u64,
    pub proof_output_sizing_nanos: u64,
}

/// Elapsed time as a counter value, saturating instead of truncating (L20).
///
/// A `Duration` cannot actually reach u64 nanoseconds (~584 years), so this is
/// defensive; a truncating cast on a user-visible counter is still a
/// silent-wrong-number bug waiting for a slow machine.
pub fn elapsed_nanos(elapsed: std::time::Duration) -> u64 {
    u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
}

/// Whether `name` is a manifest-shaped file name.
///
/// Cargo opens the manifest of a package directory as `Cargo.toml`. A file
/// stored as `cargo.toml` is opened by Cargo exactly as `Cargo.toml` on a
/// case-insensitive volume, and on a case-sensitive volume it is still a
/// manifest-shaped file that a cleanup would take with it, so the spelling
/// does not decide the question.
///
/// This is deliberately broader than the discovery's own rule
/// (`discovery::is_manifest_name`), which answers a different question - would
/// Cargo *open* this file - and therefore follows the platform's resolution
/// rules. The ownership proof has to answer would a cleanup *lose* this file,
/// and it may only ever withhold a cleanup, never authorize one. A directory
/// the discovery calls a package directory is therefore always one this rule
/// protects.
pub fn is_manifest_shaped_name(name: &std::ffi::OsStr) -> bool {
    name.to_str()
        .is_some_and(|name| name.eq_ignore_ascii_case("Cargo.toml"))
}

impl ScanCounters {
    /// One-line semantic counters for `--stats` stderr output.
    pub fn stats_line(&self) -> String {
        format!(
            "visited_directories={} pruned_directories={} platform_prunes={} cargo_home_prunes={} rustup_prunes={} target_vcs_prunes={} user_ignore_prunes={} manifests={} workspaces={} locate={} metadata={} failures={} unresolved_ownership={} empty_skipped={} active_skipped={} groups_measured={} bytes={} reportable={} deduped_hits={} uncertain_skipped={}",
            self.directories_visited,
            self.directories_pruned,
            self.platform_system_prunes,
            self.cargo_home_prunes,
            self.rustup_home_prunes,
            self.target_vcs_prunes,
            self.user_ignore_prunes,
            self.manifests_found,
            self.unique_workspaces,
            self.cargo_locate_calls,
            self.cargo_metadata_calls,
            self.cargo_failures,
            self.unresolved_ownership,
            self.empty_no_output_skipped + self.missing_output_skipped,
            self.active_skipped,
            self.groups_measured,
            self.bytes_measured,
            self.reportable_groups,
            self.deduped_workspace_hits,
            self.uncertain_skipped,
        )
    }

    /// Phase/process timing line for `--stats` stderr output.
    pub fn timings_line(&self) -> String {
        format!(
            "discovery={:.2}ms locate={:.2}ms metadata={:.2}ms source_activity={:.2}ms output_sizing={:.2}ms",
            self.discovery_nanos as f64 / 1_000_000.0,
            self.cargo_locate_nanos as f64 / 1_000_000.0,
            self.cargo_metadata_nanos as f64 / 1_000_000.0,
            self.source_activity_nanos as f64 / 1_000_000.0,
            self.output_sizing_nanos as f64 / 1_000_000.0,
        )
    }

    /// Merge final-proof counters into the dedicated proof fields.
    ///
    /// C003-F4: final ownership-universe re-resolution work is real work that
    /// `--stats` must account for. It is merged into separate `proof_*` fields
    /// (never into the initial-scan counters) so the extra bounded Cargo cost
    /// at the destructive boundary stays visible.
    ///
    /// `proof_workspaces_refreshed` counts workspace re-resolutions, never
    /// Cargo subprocess calls: the universe is refreshed once per run and each
    /// candidate re-resolves its own workspace, so the number is a count of
    /// workspaces, not of processes.
    pub fn merge_proof(&mut self, proof: &ScanCounters) {
        self.proof_cargo_locate_calls = self
            .proof_cargo_locate_calls
            .saturating_add(proof.cargo_locate_calls);
        self.proof_cargo_metadata_calls = self
            .proof_cargo_metadata_calls
            .saturating_add(proof.cargo_metadata_calls);
        self.proof_cargo_locate_nanos = self
            .proof_cargo_locate_nanos
            .saturating_add(proof.cargo_locate_nanos);
        self.proof_cargo_metadata_nanos = self
            .proof_cargo_metadata_nanos
            .saturating_add(proof.cargo_metadata_nanos);
        self.proof_source_activity_nanos = self
            .proof_source_activity_nanos
            .saturating_add(proof.source_activity_nanos);
        self.proof_output_sizing_nanos = self
            .proof_output_sizing_nanos
            .saturating_add(proof.output_sizing_nanos);
    }

    /// Final-proof counter line for `cleanup --stats` stderr output.
    pub fn proof_stats_line(&self) -> String {
        format!(
            "proof_workspaces_refreshed={} proof_locate={} proof_metadata={} proof_metadata_peak={}",
            self.proof_workspaces_refreshed,
            self.proof_cargo_locate_calls,
            self.proof_cargo_metadata_calls,
            self.proof_metadata_peak_concurrency,
        )
    }

    /// Final-proof timing line for `cleanup --stats` stderr output.
    pub fn proof_timings_line(&self) -> String {
        format!(
            "proof_locate={:.2}ms proof_metadata={:.2}ms proof_source_activity={:.2}ms proof_output_sizing={:.2}ms",
            self.proof_cargo_locate_nanos as f64 / 1_000_000.0,
            self.proof_cargo_metadata_nanos as f64 / 1_000_000.0,
            self.proof_source_activity_nanos as f64 / 1_000_000.0,
            self.proof_output_sizing_nanos as f64 / 1_000_000.0,
        )
    }
}

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

    /// Premise: a counter that wraps is not a large number, it is a *wrong*
    /// number that still looks plausible. A `Duration` cannot reach u64
    /// nanoseconds in production, so the fixtures below are unreachable by
    /// construction — which is the point. The value each one takes under a
    /// truncating `as u64` cast is the specific false reading the saturating
    /// conversion exists to prevent.
    #[test]
    fn elapsed_nanos_saturates_instead_of_wrapping() {
        assert_eq!(elapsed_nanos(Duration::ZERO), 0);
        assert_eq!(elapsed_nanos(Duration::from_secs(3)), 3_000_000_000);
        // Sub-second precision has to survive too: these counters are summed and
        // rendered in milliseconds, so a conversion that dropped the remainder
        // would read as zero elapsed work.
        assert_eq!(elapsed_nanos(Duration::new(1, 500)), 1_000_000_500);

        // `u64::MAX` seconds is ~584 years. Truncated, it reads as
        // 2^64 - 10^9 nanoseconds, i.e. about 9.2 seconds — a believable
        // measurement, which is the failure mode the cast invites.
        assert_eq!(elapsed_nanos(Duration::new(u64::MAX, 0)), u64::MAX);
        // 2^63 seconds is exactly 2^63 * 10^9 nanoseconds, and 10^9 carries
        // nine factors of two, so this duration is a whole multiple of 2^64:
        // the truncating cast reports *zero* elapsed time for it.
        assert_eq!(elapsed_nanos(Duration::new(1 << 63, 0)), u64::MAX);
    }
}