dracon-system 0.112.42

Disk, process, storage, and service diagnostics for local development machines
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
//! Quarantine — hold-then-delete staging with a TTL.
//!
//! ADDED 2026-09-26 (space tiers, Phase 1): the middle tier between "working"
//! and "trash" for data kept for now but likely deleted later. `quarantine
//! move` relocates a path under the quarantine root with a manifest recording
//! its origin; `restore` moves it back; `expire` deletes entries older than
//! the TTL (dry-run unless `--apply`). A TTL of 0 disables expiry.

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::{
    check_safe_to_delete_guard, copy_tree, expand_tilde, human_bytes, load_system_policy,
    unique_backup_path, walk_stats, walk_stats_strict, QuarantineCommands,
};

const MANIFEST_NAME: &str = ".quarantine.json";

/// Manifest stored inside each quarantine entry.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct QuarantineManifest {
    pub(crate) name: String,
    pub(crate) origin: String,
    pub(crate) moved_at_unix: u64,
    pub(crate) bytes: u64,
    pub(crate) files: u64,
}

/// One listed entry (manifest may be missing for hand-placed dirs).
#[derive(Debug, Serialize)]
pub(crate) struct QuarantineEntry {
    pub(crate) name: String,
    pub(crate) origin: String,
    pub(crate) moved_at_unix: Option<u64>,
    pub(crate) age_days: Option<u64>,
    pub(crate) bytes: u64,
    pub(crate) expired: bool,
}

#[derive(Debug, Serialize)]
pub(crate) struct QuarantineList {
    pub(crate) root: String,
    pub(crate) ttl_days: u64,
    pub(crate) entries: Vec<QuarantineEntry>,
    pub(crate) total_bytes: u64,
    pub(crate) expired_bytes: u64,
}

pub(crate) fn now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Quarantine `origin` instead of deleting it. Returns the manifest plus the
/// bytes actually freed on the origin filesystem (0 for same-filesystem
/// moves — the win there is the TTL expiry later, not immediate space).
pub(crate) fn quarantine_first_remove(
    origin: &Path,
    root: &Path,
    user_protected: &[String],
) -> Result<(QuarantineManifest, u64)> {
    // Capture the origin device BEFORE the move (the path is gone after).
    // FIXED 2026-09-27 (clippy `option_and_then_some`): `.and_then(|m| Some(m.dev()))`
    // is `.map(|m| m.dev())`. Pre-existing lint, newly fatal under the CI
    // gate that now lints `--all-targets`.
    let origin_dev = fs::metadata(origin).ok().map(|m| {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            m.dev()
        }
        #[cfg(not(unix))]
        {
            let _ = m;
            0
        }
    });
    let manifest = quarantine_move(origin, root, user_protected)?;
    #[cfg(unix)]
    let same_dev = {
        use std::os::unix::fs::MetadataExt;
        fs::metadata(root)
            .ok()
            .is_some_and(|m| Some(m.dev()) == origin_dev)
    };
    #[cfg(not(unix))]
    let same_dev = false;
    // Unknown device comparison claims nothing (fail closed).
    let freed = if same_dev || origin_dev.is_none() {
        0
    } else {
        manifest.bytes
    };
    Ok((manifest, freed))
}

pub(crate) fn quarantine_root(guard: &crate::GuardPolicy) -> PathBuf {
    let raw = guard.quarantine_dir.trim();
    if raw.is_empty() {
        expand_tilde(&crate::default_quarantine_dir())
    } else {
        expand_tilde(raw)
    }
}

fn read_manifest(entry_dir: &Path) -> Option<QuarantineManifest> {
    let text = fs::read_to_string(entry_dir.join(MANIFEST_NAME)).ok()?;
    serde_json::from_str(&text).ok()
}

/// Entry dir name: `<basename>.<nanos>` with collision suffix, via the same
/// unique-name helper the link backup path uses.
fn entry_dir_for(root: &Path, origin: &Path) -> PathBuf {
    let base = origin
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "entry".to_string());
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    unique_backup_path(root, &format!("{base}.{ts}"))
}

/// Move `origin` into quarantine. Uses rename when possible (same filesystem),
/// else copy + verify + remove. Refuses symlinks and protected paths.
pub(crate) fn quarantine_move(
    origin: &Path,
    root: &Path,
    user_protected: &[String],
) -> Result<QuarantineManifest> {
    let meta = fs::symlink_metadata(origin)
        .map_err(|e| anyhow::anyhow!("cannot inspect {}: {}", origin.display(), e))?;
    if meta.file_type().is_symlink() {
        anyhow::bail!("refusing to quarantine symlink {}", origin.display());
    }
    if !meta.is_dir() {
        anyhow::bail!("quarantine supports directories only: {}", origin.display());
    }
    let canon_origin = check_safe_to_delete_guard(origin, user_protected)?;
    fs::create_dir_all(root)?;
    let canon_root = root.canonicalize()?;
    if canon_origin.starts_with(&canon_root) || canon_root.starts_with(&canon_origin) {
        anyhow::bail!("origin and quarantine root nest — refusing");
    }

    let (files, bytes) = walk_stats_strict(&canon_origin)?;
    let entry_dir = entry_dir_for(&canon_root, &canon_origin);
    let name = entry_dir
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();

    match fs::rename(&canon_origin, &entry_dir) {
        Ok(()) => {}
        Err(_) => {
            let skipped = copy_tree(&canon_origin, &entry_dir).inspect_err(|_| {
                let _ = fs::remove_dir_all(&entry_dir);
            })?;
            if skipped > 0 {
                eprintln!(
                    "quarantine move: skipped {} special files (sockets, fifos) — not preserved",
                    skipped
                );
            }
            let (got_files, got_bytes) = walk_stats_strict(&entry_dir)?;
            if got_files != files || got_bytes != bytes {
                let _ = fs::remove_dir_all(&entry_dir);
                anyhow::bail!("copy verification failed — origin untouched");
            }
            fs::remove_dir_all(&canon_origin)?;
        }
    }

    let manifest = QuarantineManifest {
        name,
        origin: canon_origin.display().to_string(),
        moved_at_unix: now_unix(),
        bytes,
        files,
    };
    // Serialize before anything is unlinked: if the write below fails we
    // still have the bytes to report exactly where the data sits.
    let manifest_text = serde_json::to_string_pretty(&manifest)?;
    fs::write(entry_dir.join(MANIFEST_NAME), &manifest_text).map_err(|e| {
        // The data moved but has no manifest, which would orphan it (a
        // future restore refuses manifest-less entries). Move it back
        // rather than leave it unrecorded.
        if fs::rename(&entry_dir, &canon_origin).is_ok() {
            anyhow::anyhow!("quarantine manifest write failed — moved back to origin: {e}")
        } else {
            anyhow::anyhow!(
                "quarantine manifest write failed AND move-back failed: data is at {} with no manifest, origin {} is gone",
                entry_dir.display(),
                canon_origin.display()
            )
        }
    })?;
    Ok(manifest)
}

pub(crate) fn quarantine_list(root: &Path, ttl_days: u64) -> Result<QuarantineList> {
    let mut entries = Vec::new();
    let mut total_bytes = 0u64;
    let mut expired_bytes = 0u64;
    if fs::symlink_metadata(root).is_ok() {
        let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
        for dir in fs::read_dir(&canon_root)?.flatten() {
            let path = dir.path();
            if !path.is_dir() {
                continue;
            }
            let name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            let (_, bytes) = walk_stats(&path);
            let manifest = read_manifest(&path);
            let now = now_unix();
            let (origin, moved_at, age_days, expired) = match &manifest {
                Some(m) => {
                    let age = now.saturating_sub(m.moved_at_unix) / 86_400;
                    let exp = ttl_days > 0 && age > ttl_days;
                    (m.origin.clone(), Some(m.moved_at_unix), Some(age), exp)
                }
                None => ("unknown".to_string(), None, None, false),
            };
            total_bytes += bytes;
            if expired {
                expired_bytes += bytes;
            }
            entries.push(QuarantineEntry {
                name,
                origin,
                moved_at_unix: moved_at,
                age_days,
                bytes,
                expired,
            });
        }
        entries.sort_by(|a, b| a.name.cmp(&b.name));
    }
    Ok(QuarantineList {
        root: root.display().to_string(),
        ttl_days,
        entries,
        total_bytes,
        expired_bytes,
    })
}

/// Restore an entry to its recorded origin. The origin must not exist.
///
/// The entry `name` is a single path component minted by `entry_dir_for`;
/// separators, parent components, and absolute paths are refused before
/// they can escape the quarantine root, and a smuggled symlink is refused
/// rather than followed. The manifest is kept until the move succeeds, so
/// a failed restore leaves the entry restorable instead of orphaning it.
pub(crate) fn quarantine_restore(root: &Path, name: &str) -> Result<PathBuf> {
    if name.is_empty()
        || name == "."
        || name == ".."
        || name.contains('/')
        || name.contains('\\')
        || name.contains('\0')
    {
        anyhow::bail!("invalid quarantine entry name: {name}");
    }
    let canon_root = root.canonicalize().map_err(|e| {
        anyhow::anyhow!(
            "cannot canonicalize quarantine root {}: {}",
            root.display(),
            e
        )
    })?;
    let entry_dir = canon_root.join(name);
    // symlink_metadata does not follow links: a smuggled symlink into an
    // entry-named path is refused here instead of being operated through.
    let meta = fs::symlink_metadata(&entry_dir)
        .map_err(|_| anyhow::anyhow!("no such quarantine entry: {name}"))?;
    if !meta.file_type().is_dir() {
        if meta.file_type().is_symlink() {
            anyhow::bail!("refusing to restore through symlink {name}");
        }
        anyhow::bail!("no such quarantine entry: {name}");
    }
    let manifest = read_manifest(&entry_dir)
        .ok_or_else(|| anyhow::anyhow!("entry {name} has no manifest — refusing blind restore"))?;
    let origin = PathBuf::from(&manifest.origin);
    if fs::symlink_metadata(&origin).is_ok() {
        anyhow::bail!("origin {} already exists — refusing", origin.display());
    }
    if let Some(parent) = origin.parent() {
        fs::create_dir_all(parent)?;
    }
    match fs::rename(&entry_dir, &origin) {
        Ok(()) => {
            // Drop the manifest only after the move, so the restored tree
            // is clean; a failure here is cosmetic, the data is home.
            let _ = fs::remove_file(origin.join(MANIFEST_NAME));
            Ok(origin)
        }
        Err(_) => {
            copy_tree(&entry_dir, &origin).inspect_err(|_| {
                let _ = fs::remove_dir_all(&origin);
            })?;
            // The copy carries the manifest along; drop it from the
            // restored tree BEFORE verifying, or its file+bytes break the
            // tally (the manifest was written after the source tally) and
            // a stray manifest leaks into the restored tree.
            let _ = fs::remove_file(origin.join(MANIFEST_NAME));
            let (got_files, got_bytes) = walk_stats_strict(&origin)?;
            if got_files != manifest.files || got_bytes != manifest.bytes {
                let _ = fs::remove_dir_all(&origin);
                anyhow::bail!("restore verification failed — quarantine entry kept");
            }
            fs::remove_dir_all(&entry_dir)?;
            Ok(origin)
        }
    }
}

/// Delete entries older than the TTL. Entries are validated to sit directly
/// under the quarantine root before removal. TTL 0 disables expiry.
pub(crate) fn quarantine_expire(root: &Path, ttl_days: u64, apply: bool) -> Result<Vec<String>> {
    if ttl_days == 0 {
        return Ok(Vec::new());
    }
    let list = quarantine_list(root, ttl_days)?;
    let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let mut removed = Vec::new();
    for entry in list.entries.iter().filter(|e| e.expired) {
        let dir = canon_root.join(&entry.name);
        // A directory that vanished between the list and the removal is
        // already gone; skip it rather than aborting the batch and losing
        // the removals already collected.
        let Ok(canon) = dir.canonicalize() else {
            eprintln!("quarantine expire: entry {} vanished, skipping", entry.name);
            continue;
        };
        if canon.parent() != Some(canon_root.as_path()) {
            // An escaped entry is a security signal, but aborting the
            // batch discards the removals already collected. Skip it
            // loudly instead; the warning names the entry for the operator.
            eprintln!(
                "quarantine expire: entry {} escaped quarantine root — refusing it, continuing batch",
                entry.name
            );
            continue;
        }
        if apply {
            fs::remove_dir_all(&canon)?;
        }
        removed.push(entry.name.clone());
    }
    Ok(removed)
}

pub(crate) fn cmd_quarantine(cmd: QuarantineCommands) -> Result<()> {
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, ContentArrangement, Table};

    let (_, policy) = load_system_policy()?;
    let root = quarantine_root(&policy.guard);
    let ttl = policy.guard.quarantine_ttl_days;
    match cmd {
        QuarantineCommands::Move { path, apply, json } => {
            if !apply {
                let meta = fs::symlink_metadata(&path)
                    .map_err(|e| anyhow::anyhow!("cannot inspect {}: {}", path.display(), e))?;
                if !meta.is_dir() || meta.file_type().is_symlink() {
                    anyhow::bail!("quarantine move supports real directories only");
                }
                let (files, bytes) = walk_stats(&path);
                if json {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&serde_json::json!({
                            "origin": path.display().to_string(),
                            "root": root.display().to_string(),
                            "files": files,
                            "bytes": bytes,
                        }))?
                    );
                } else {
                    println!(
                        "Would quarantine {} ({} in {} files) → {}",
                        path.display(),
                        human_bytes(bytes),
                        files,
                        root.display()
                    );
                    println!("Dry-run: pass --apply to move.");
                }
                return Ok(());
            }
            let manifest = quarantine_move(&path, &root, &policy.guard.protected_paths)?;
            if json {
                println!("{}", serde_json::to_string_pretty(&manifest)?);
            } else {
                println!(
                    "✅ Quarantined {} ({} in {} files) as {}",
                    manifest.origin,
                    human_bytes(manifest.bytes),
                    manifest.files,
                    manifest.name
                );
            }
        }
        QuarantineCommands::List { json } => {
            let list = quarantine_list(&root, ttl)?;
            if json {
                println!("{}", serde_json::to_string_pretty(&list)?);
            } else if list.entries.is_empty() {
                println!("Quarantine {} is empty", root.display());
            } else {
                let mut table = Table::new();
                table
                    .load_preset(UTF8_FULL_CONDENSED)
                    .set_content_arrangement(ContentArrangement::Dynamic)
                    .set_header(vec![
                        Cell::new("ENTRY"),
                        Cell::new("ORIGIN"),
                        Cell::new("AGE"),
                        Cell::new("SIZE"),
                        Cell::new("EXPIRED"),
                    ]);
                for e in &list.entries {
                    table.add_row(vec![
                        Cell::new(&e.name),
                        Cell::new(&e.origin),
                        Cell::new(
                            e.age_days
                                .map(|d| format!("{d}d"))
                                .unwrap_or_else(|| "?".to_string()),
                        ),
                        Cell::new(human_bytes(e.bytes)),
                        Cell::new(if e.expired { "yes" } else { "" }),
                    ]);
                }
                println!("{table}");
                println!(
                    "{} entries, {} total ({} expired, TTL {}d)",
                    list.entries.len(),
                    human_bytes(list.total_bytes),
                    human_bytes(list.expired_bytes),
                    ttl
                );
            }
        }
        QuarantineCommands::Restore { name, json } => {
            let origin = quarantine_restore(&root, &name)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "entry": name,
                        "restored_to": origin.display().to_string(),
                    }))?
                );
            } else {
                println!("✅ Restored {name} → {}", origin.display());
            }
        }
        QuarantineCommands::Expire { apply, json } => {
            let expired = quarantine_expire(&root, ttl, apply)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "ttl_days": ttl,
                        "apply": apply,
                        "expired": expired,
                    }))?
                );
            } else if expired.is_empty() {
                println!("No expired entries (TTL {}d)", ttl);
            } else if apply {
                println!(
                    "🗑 Expired {} entries: {}",
                    expired.len(),
                    expired.join(", ")
                );
            } else {
                println!(
                    "Would expire {} entries: {}",
                    expired.len(),
                    expired.join(", ")
                );
                println!("Dry-run: pass --apply to delete.");
            }
        }
    }
    Ok(())
}