dracon-system 0.112.45

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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! 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,
    /// Provenance: true when the guard's action tier moved this entry
    /// (`quarantine_first_remove`), false for a deliberate CLI `move`.
    /// Missing (pre-flag manifests) deserializes to false: unknown
    /// provenance fails closed to manual, so replace-on-re-quarantine
    /// never deletes an entry it cannot prove is auto-created.
    #[serde(default)]
    pub(crate) auto: bool,
}

/// 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,
    /// True when the manifest is unreadable, so the entry can never age out
    /// and can never be restored to a known location.
    pub(crate) pinned: bool,
    /// Why this entry is pinned, shown to the operator.
    pub(crate) pin_reason: Option<String>,
}

#[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,
    /// Names of entries the fail-safe is holding, and the bytes they hold.
    pub(crate) pinned: Vec<String>,
    pub(crate) pinned_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_inner(origin, root, user_protected, true)?;
    // Replace-on-re-quarantine (2026-10-04): the auto path re-quarantines
    // the same rebuilt target/ every cycle. Older AUTO generations of this
    // origin are superseded by the move that just landed, so they go now
    // instead of sitting until the TTL. Runs AFTER the new manifest is
    // published: the replacement copy is secured first, and a replacement
    // failure only costs disk until TTL expiry, never data.
    let replaced = replace_older_auto_generations(root, &manifest);
    for name in &replaced {
        eprintln!(
            "quarantine: replaced older auto generation {name} (origin {})",
            manifest.origin
        );
    }
    #[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.
///
/// This is the MANUAL entry point (CLI `move`): the manifest records
/// `auto: false` and no replacement happens — deliberate snapshots
/// accumulate and age out at the TTL.
pub(crate) fn quarantine_move(
    origin: &Path,
    root: &Path,
    user_protected: &[String],
) -> Result<QuarantineManifest> {
    quarantine_move_inner(origin, root, user_protected, false)
}

/// The shared move implementation. `auto` records provenance in the
/// manifest; replacement of older generations is NOT done here but by
/// the auto caller (`quarantine_first_remove`), so the manual path can
/// never trigger a delete no matter how it is invoked.
fn quarantine_move_inner(
    origin: &Path,
    root: &Path,
    user_protected: &[String],
    auto: bool,
) -> 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)?;
    match fs::symlink_metadata(canon_origin.join(MANIFEST_NAME)) {
        Ok(_) => anyhow::bail!(
            "refusing to quarantine {}: reserved metadata name {} already exists; source untouched",
            canon_origin.display(),
            MANIFEST_NAME
        ),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(e.into()),
    }
    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
                );
            }
            // FIXED 2026-10-01 (audit): the verification walk propagated with `?`
            // while the two paths beside it clean the entry dir up. A read error
            // here (EIO, or a concurrent chmod on the tree just copied) left a
            // fully copied entry directory with NO manifest: `restore` refuses a
            // manifest-less entry and `expire` pins it as unknown data, so the
            // bytes were held forever. Clean up on this path too — the origin is
            // untouched, so nothing is lost and a retry can start over.
            let (got_files, got_bytes) = match walk_stats_strict(&entry_dir) {
                Ok(stats) => stats,
                Err(verify_err) => {
                    let _ = fs::remove_dir_all(&entry_dir);
                    anyhow::bail!(
                        "copy verification could not read the copied entry ({verify_err:#}) — \
                             entry directory removed, origin untouched"
                    );
                }
            };
            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,
        auto,
    };
    // 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)?;
    let publish_manifest = || -> Result<()> {
        use std::io::Write;
        // Publish without replacement or symlink following, including if a
        // source writer introduced the reserved name after the preflight.
        let mut staged = tempfile::NamedTempFile::new_in(&canon_root)?;
        staged.write_all(manifest_text.as_bytes())?;
        staged.as_file().sync_all()?;
        staged.persist_noclobber(entry_dir.join(MANIFEST_NAME))?;
        Ok(())
    };
    publish_manifest().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)
}

/// Delete older AUTO generations of `new.origin`, keeping `new` itself.
/// Returns the deleted entry names.
///
/// Every filter here fails closed: an entry is deleted only when its
/// manifest is readable AND records `auto: true` AND names this origin
/// AND is not the entry that just landed. Manual snapshots, pre-flag
/// manifests (unknown provenance), other origins, unreadable manifests,
/// and anything outside the canonical root are all kept. A deletion
/// failure is loud but non-fatal — the TTL expiry is the backstop.
pub(crate) fn replace_older_auto_generations(root: &Path, new: &QuarantineManifest) -> Vec<String> {
    let mut replaced = Vec::new();
    let entries = match fs::read_dir(root) {
        Ok(entries) => entries,
        Err(e) => {
            eprintln!(
                "quarantine: cannot scan {} for older generations: {e} — keeping everything",
                root.display()
            );
            return replaced;
        }
    };
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if name == new.name {
            continue;
        }
        let entry_dir = entry.path();
        let Some(manifest) = read_manifest(&entry_dir) else {
            continue;
        };
        if !manifest.auto || manifest.origin != new.origin {
            continue;
        }
        // Containment + symlink refusal, same as purge/restore.
        let dir = match resolve_entry_dir(root, &name) {
            Ok(dir) => dir,
            Err(e) => {
                eprintln!("quarantine: skipping unresolvable older generation {name}: {e:#}");
                continue;
            }
        };
        match fs::remove_dir_all(&dir) {
            Ok(()) => replaced.push(name),
            Err(e) => eprintln!(
                "quarantine: could not remove older auto generation {name}: {e} — TTL expiry remains the backstop"
            ),
        }
    }
    replaced.sort();
    replaced
}

/// Why a fail-safe pin is reported to the operator.
///
/// Re-examined 2026-09-29 (DECIDE #3 follow-up). The fail-safe is KEPT.
/// The manifest is the only record of where the entry came from; without it
/// the entry is permanently unrestorable, so expiring it would convert
/// "recoverable by hand" into "gone". Nothing is gained by taking that risk
/// on a timer: the quarantine root is written only by this daemon, so an
/// unreadable manifest means corruption or outside interference, not a
/// routine condition that a TTL is there to bound — and a genuinely
/// transient read error (EACCES, EIO) resolves itself, after which the entry
/// ages normally.
///
/// The cost of that choice is that bytes can be held indefinitely, so the
/// pin is never silent: it is listed, counted, and explained, and
/// `quarantine purge <name>` is the documented operator escape hatch for a
/// specific entry the operator has inspected.
pub(crate) const PIN_REASON: &str =
    "manifest unreadable — cannot age out or restore; clear with `quarantine purge <name> --apply`";

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;
    let mut pinned = Vec::new();
    let mut pinned_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),
            };
            let is_pinned = manifest.is_none();
            total_bytes += bytes;
            if expired {
                expired_bytes += bytes;
            }
            if is_pinned {
                pinned.push(name.clone());
                pinned_bytes += bytes;
            }
            entries.push(QuarantineEntry {
                name,
                origin,
                moved_at_unix: moved_at,
                age_days,
                bytes,
                expired,
                pinned: is_pinned,
                pin_reason: is_pinned.then(|| PIN_REASON.to_string()),
            });
        }
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        pinned.sort();
    }
    Ok(QuarantineList {
        root: root.display().to_string(),
        ttl_days,
        entries,
        total_bytes,
        expired_bytes,
        pinned,
        pinned_bytes,
    })
}

/// Resolve a caller-supplied entry name to a real directory inside the
/// quarantine root.
///
/// The 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. Shared by `restore` and `purge` so the escape hatch
/// inherits exactly the same containment checks as the safe path — a purge
/// that validated names differently would be the weakest link in the module.
pub(crate) fn resolve_entry_dir(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 operate on symlink entry {name}");
        }
        anyhow::bail!("no such quarantine entry: {name}");
    }
    Ok(entry_dir)
}

/// Delete one named quarantine entry, whatever state its manifest is in.
///
/// This is the documented escape hatch for an entry the fail-safe is pinning
/// (see `PIN_REASON`): the operator names ONE entry they have inspected and
/// accepts that it cannot be restored. It is deliberately not a bulk
/// "delete everything unreadable" switch — that would reintroduce exactly the
/// timer-driven, unaccountable deletion the fail-safe exists to prevent, and
/// a manifest that is unreadable for one entry is often unreadable because
/// something is wrong with the whole root.
///
/// Dry-run unless `apply`, and it reports the size it would reclaim so the
/// operator sees what they are about to give up before giving it up.
pub(crate) fn quarantine_purge(
    root: &Path,
    name: &str,
    apply: bool,
) -> Result<(String, u64, bool)> {
    let entry_dir = resolve_entry_dir(root, name)?;
    let (files, bytes) = walk_stats(&entry_dir);
    let pinned = read_manifest(&entry_dir).is_none();
    if apply {
        fs::remove_dir_all(&entry_dir)?;
    }
    Ok((
        format!("{files} files, {}", human_bytes(bytes)),
        bytes,
        pinned,
    ))
}

/// Restore an entry to its recorded origin. The origin must not exist.
///
/// Uses the shared `resolve_entry_dir` containment check, and 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> {
    let entry_dir = resolve_entry_dir(root, 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)
        }
    }
}

/// One entry removed (or, in a dry run, that would be removed) by an expiry
/// pass. Carries the origin and size so a caller can log a deletion an
/// operator could act on, rather than a bare name.
#[derive(Debug)]
pub(crate) struct ExpiredEntry {
    pub(crate) name: String,
    pub(crate) origin: String,
    pub(crate) bytes: u64,
}

/// Everything one expiry pass did, so a caller does not have to walk the
/// quarantine root a second time to learn what was removed and what could not
/// be.
pub(crate) struct ExpireOutcome {
    pub(crate) removed: Vec<ExpiredEntry>,
    /// Entries with an unreadable manifest. They can never age out, because
    /// there is no timestamp to age — reported on every pass so they cannot
    /// accumulate silently in a directory whose whole purpose is bounded
    /// growth.
    pub(crate) pinned: Vec<String>,
    pub(crate) pinned_bytes: u64,
}

/// Delete entries older than the TTL, returning one record per removal.
/// Entries are validated to sit directly under the quarantine root before
/// removal. TTL 0 disables expiry.
///
/// A pinned entry (unreadable manifest) is `expired = false` by construction in
/// `quarantine_list`, so it can never reach the removal loop. That is the only
/// thing standing between a corrupt manifest and an un-datable deletion, so it
/// is pinned by a test rather than by this comment.
pub(crate) fn quarantine_expire_detailed(
    root: &Path,
    ttl_days: u64,
    apply: bool,
) -> Result<ExpireOutcome> {
    // FIXED 2026-10-02 (audit advisory): this used to return early when
    // ttl_days == 0, which skipped the directory walk and therefore also
    // skipped reporting pinned entries. Nothing is deleted either way —
    // `quarantine_list` already computes `expired = ttl_days > 0 && age > ttl`,
    // so no entry can be removed when the TTL is 0 — but an operator who
    // disables expiry still has entries sitting there, and one of them may be
    // pinned with no way to age out. The report is about existing state, not
    // about the deletion decision, so it is now produced in both cases.
    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(ExpiredEntry {
            name: entry.name.clone(),
            origin: entry.origin.clone(),
            bytes: entry.bytes,
        });
    }
    Ok(ExpireOutcome {
        removed,
        pinned: list.pinned,
        pinned_bytes: list.pinned_bytes,
    })
}

/// Delete entries older than the TTL, returning the names removed.
/// 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>> {
    Ok(quarantine_expire_detailed(root, ttl_days, apply)?
        .removed
        .into_iter()
        .map(|e| e.name)
        .collect())
}

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"),
                        Cell::new("NOTE"),
                    ]);
                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 { "" }),
                        Cell::new(if e.pinned { "PINNED" } else { "" }),
                    ]);
                }
                println!("{table}");
                println!(
                    "{} entries, {} total ({} expired, TTL {}d)",
                    list.entries.len(),
                    human_bytes(list.total_bytes),
                    human_bytes(list.expired_bytes),
                    ttl
                );
                // The fail-safe is not allowed to be silent: an entry held
                // forever because its manifest is unreadable would otherwise
                // look exactly like a quarantine that has nothing to expire.
                if !list.pinned.is_empty() {
                    println!(
                        "⚠ {} entr{} pinned by the fail-safe ({}): {PIN_REASON}",
                        list.pinned.len(),
                        if list.pinned.len() == 1 {
                            "y is"
                        } else {
                            "ies are"
                        },
                        human_bytes(list.pinned_bytes)
                    );
                    println!("   {}", list.pinned.join(", "));
                }
            }
        }
        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 } => {
            // Captured BEFORE the expiry runs. After an --apply the entries
            // are gone, so re-listing would report an empty pinned set and
            // the warning would be suppressed by the very deletion it is
            // warning about.
            let pinned = quarantine_list(&root, ttl)?.pinned;
            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,
                        "pinned": pinned,
                    }))?
                );
            } 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.");
            }
            // Reported whether or not anything expired. An operator who
            // just ran a successful expire must still learn that data is
            // being HELD, or the run looks like the queue is now empty.
            //
            // In --json the warning goes to stderr: stdout must stay exactly
            // one JSON document, and the pinned set is already carried in the
            // payload above for a machine to read.
            if !pinned.is_empty() {
                if json {
                    eprintln!(
                        "⚠ {} entr{} held by the fail-safe (unreadable manifest) and NOT expired: {}",
                        pinned.len(),
                        if pinned.len() == 1 { "y is" } else { "ies are" },
                        pinned.join(", ")
                    );
                } else {
                    println!(
                        "⚠ {} entr{} held by the fail-safe (unreadable manifest) and NOT expired: {}",
                        pinned.len(),
                        if pinned.len() == 1 { "y is" } else { "ies are" },
                        pinned.join(", ")
                    );
                    println!("   clear one with: quarantine purge <name> --apply");
                }
            }
        }
        QuarantineCommands::Purge { name, apply, json } => {
            let (contents, bytes, was_pinned) = quarantine_purge(&root, &name, apply)?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "entry": name,
                        "contents": contents,
                        "bytes": bytes,
                        "pinned_by_fail_safe": was_pinned,
                        "applied": apply,
                    }))?
                );
            } else if apply {
                println!("🗑 Purged {name} ({contents})");
                if was_pinned {
                    println!(
                        "   This entry had an unreadable manifest, so it could not be \
                         restored. It is now gone for good."
                    );
                }
            } else {
                println!("Would purge {name} ({contents})");
                if was_pinned {
                    println!(
                        "   Its manifest is unreadable, so it cannot be restored — \
                         purging discards it permanently."
                    );
                }
                println!("Dry-run: pass --apply to delete.");
            }
        }
    }
    Ok(())
}