stagecrew 0.2.0

Disk usage management for shared or staging filesystems with automatic cleanup policies
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
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! File removal logic and approval workflow.

use std::path::{Path, PathBuf};

use crate::audit::{AuditAction, AuditActorSource, AuditEvent, AuditService};
use crate::db::Database;
use crate::error::{Error, Result};

/// Method for removing files from the filesystem.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RemovalMethod {
    /// Move to system trash (recoverable).
    #[default]
    Trash,
    /// Permanently delete (irreversible).
    PermanentDelete,
}

impl RemovalMethod {
    /// Past tense for status messages.
    #[must_use]
    pub const fn past_tense(self) -> &'static str {
        match self {
            Self::Trash => "Trashed",
            Self::PermanentDelete => "Deleted",
        }
    }
}

/// Check whether a path could be removed without actually removing it.
///
/// This is a best-effort preflight check that verifies the path exists on
/// disk. Permission errors and other filesystem failures are left to the
/// actual removal call, which already handles them gracefully.
///
/// # Errors
///
/// Returns [`Error::PathNotFound`] if the path does not exist.
pub fn check_removability(path: &Path) -> Result<()> {
    if !path.exists() {
        return Err(Error::PathNotFound(path.to_path_buf()));
    }

    Ok(())
}

/// Attempt to remove a path using the specified method.
///
/// Runs a preflight removability check before attempting the actual removal.
///
/// # Errors
///
/// Returns an error if:
/// - Permission is denied
/// - Path doesn't exist
/// - Other filesystem errors occur
pub fn remove(path: &Path, method: RemovalMethod) -> Result<RemovalOutcome> {
    check_removability(path)?;

    match method {
        RemovalMethod::Trash => trash(path),
        RemovalMethod::PermanentDelete => permanent_delete(path),
    }
}

/// Move a path to the system trash.
fn trash(path: &Path) -> Result<RemovalOutcome> {
    match trash::delete(path) {
        Ok(()) => {
            tracing::info!(?path, "Moved to trash successfully");
            Ok(RemovalOutcome::Trashed)
        }
        Err(e) => {
            tracing::warn!(?path, error = %e, "Failed to move to trash");
            Err(Error::Trash {
                path: path.to_path_buf(),
                message: e.to_string(),
            })
        }
    }
}

/// Permanently delete a path from the filesystem.
fn permanent_delete(path: &Path) -> Result<RemovalOutcome> {
    let result = if path.is_dir() {
        std::fs::remove_dir_all(path)
    } else {
        std::fs::remove_file(path)
    };

    match result {
        Ok(()) => {
            tracing::info!(?path, "Permanently deleted");
            Ok(RemovalOutcome::Deleted)
        }
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            tracing::warn!(?path, "Permission denied");
            Err(Error::PermissionDenied(path.to_path_buf()))
        }
        Err(e) => Err(Error::Filesystem {
            path: path.to_path_buf(),
            source: e,
        }),
    }
}

/// Outcome of a removal attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use = "removal outcome should be checked"]
#[non_exhaustive]
pub enum RemovalOutcome {
    /// File was moved to trash.
    Trashed,
    /// File was permanently deleted.
    Deleted,
}

/// A single entry that failed the dry run removability check.
#[derive(Debug, Clone)]
pub struct DryRunFailure {
    /// Absolute path of the entry that would fail removal.
    pub path: PathBuf,
    /// Human-readable reason the entry cannot be removed.
    pub reason: String,
}

/// Summary of a dry run preflight check for approved entries in a single root.
#[derive(Debug, Clone)]
#[must_use]
pub struct DryRunResult {
    /// Number of approved entries that passed the removability check.
    pub removable_count: usize,
    /// Total number of approved entries checked.
    pub total_count: usize,
    /// Entries that would fail removal, with reasons.
    pub failures: Vec<DryRunFailure>,
}

/// Run a preflight removability check on all approved entries for a single root.
///
/// Iterates over every entry with status "approved" under the given root,
/// calling [`check_removability`] on each. Collects successes and failures
/// into a [`DryRunResult`] without modifying the filesystem or database.
///
/// # Errors
///
/// Returns an error if the database query fails. Individual removability
/// check failures are collected in the result (not propagated).
pub fn dry_run_approved(db: &Database, root_id: i64) -> Result<DryRunResult> {
    let approved = db.list_entries_by_root_and_status(root_id, "approved")?;

    let total_count = approved.len();
    let mut removable_count = 0;
    let mut failures = Vec::new();

    for entry in &approved {
        match check_removability(&entry.path) {
            Ok(()) => removable_count += 1,
            Err(e) => {
                failures.push(DryRunFailure {
                    path: entry.path.clone(),
                    reason: e.to_string(),
                });
            }
        }
    }

    Ok(DryRunResult {
        removable_count,
        total_count,
        failures,
    })
}

/// Process all approved entries for removal.
///
/// Queries the database for entries with status='approved', attempts to
/// remove each one, and updates the database with the outcome. On success,
/// the entry status is set to 'removed'. On error (permission denied or
/// other filesystem failure), the status is set to 'blocked' with details
/// logged in the audit trail.
///
/// This function never uses elevated permissions (no sudo). It operates with
/// the current user's permissions and handles errors gracefully.
///
/// # Returns
///
/// A summary containing the number of successfully removed entries,
/// blocked entries (due to errors), and total bytes freed.
///
/// # Errors
///
/// Returns an error if database operations fail. Individual removal failures
/// are handled gracefully and recorded in the summary (not propagated).
pub fn remove_approved(db: &Database) -> Result<RemovalSummary> {
    let audit = AuditService::new(db);
    let user = AuditService::current_user();

    // Query all approved entries
    let approved_entries = db.list_entries(Some("approved"))?;

    let mut removed_count = 0;
    let mut blocked_count = 0;
    let mut total_bytes_freed = 0i64;

    for entry in approved_entries {
        let path = entry.path.clone();

        tracing::debug!(path = ?entry.path, is_dir = entry.is_dir, "Processing approved entry for removal");

        // Daemon uses permanent delete for approved entries
        match remove(&path, RemovalMethod::PermanentDelete) {
            Ok(RemovalOutcome::Deleted) => {
                // Success: Update status to removed
                db.update_entry_status(entry.id, "removed")?;
                removed_count += 1;
                total_bytes_freed += entry.size_bytes;

                tracing::info!(path = ?entry.path, bytes = entry.size_bytes, "Entry removed successfully");

                // Record audit entry
                let details = format!("Permanently deleted {} bytes", entry.size_bytes);
                audit.record_event(&AuditEvent {
                    user: &user,
                    actor_source: AuditActorSource::Daemon,
                    action: AuditAction::Remove,
                    target_path: Some(entry.path.as_path()),
                    details: Some(&details),
                    entry_id: Some(entry.id),
                    root_id: Some(entry.root_id),
                    status_before: Some("approved"),
                    status_after: Some("removed"),
                    outcome: Some("removed"),
                })?;
            }
            Ok(RemovalOutcome::Trashed) => {
                // This shouldn't happen (we use PermanentDelete)
                tracing::warn!(path = ?entry.path, "Unexpected removal outcome: Trashed");
            }
            Err(Error::PermissionDenied(_)) => {
                // Permission error: Update status to blocked
                db.update_entry_status(entry.id, "blocked")?;
                blocked_count += 1;

                tracing::warn!(path = ?entry.path, "Removal blocked: permission denied");

                // Record audit entry with error details
                audit.record_event(&AuditEvent {
                    user: &user,
                    actor_source: AuditActorSource::Daemon,
                    action: AuditAction::Remove,
                    target_path: Some(entry.path.as_path()),
                    details: Some("Blocked: permission denied"),
                    entry_id: Some(entry.id),
                    root_id: Some(entry.root_id),
                    status_before: Some("approved"),
                    status_after: Some("blocked"),
                    outcome: Some("blocked"),
                })?;
            }
            Err(e) => {
                // Other error: Update status to blocked
                db.update_entry_status(entry.id, "blocked")?;
                blocked_count += 1;

                tracing::warn!(path = ?entry.path, error = %e, "Removal blocked: filesystem error");

                // Record audit entry with error details
                let details = format!("Blocked: {e}");
                audit.record_event(&AuditEvent {
                    user: &user,
                    actor_source: AuditActorSource::Daemon,
                    action: AuditAction::Remove,
                    target_path: Some(entry.path.as_path()),
                    details: Some(&details),
                    entry_id: Some(entry.id),
                    root_id: Some(entry.root_id),
                    status_before: Some("approved"),
                    status_after: Some("blocked"),
                    outcome: Some("blocked"),
                })?;
            }
        }
    }

    Ok(RemovalSummary {
        removed_count,
        blocked_count,
        total_bytes_freed,
    })
}

/// Summary of removal operations.
///
/// This struct provides read-only access to removal statistics. It cannot be
/// constructed directly by external code; instances are returned by
/// [`remove_approved`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
#[non_exhaustive]
pub struct RemovalSummary {
    removed_count: usize,
    blocked_count: usize,
    total_bytes_freed: i64,
}

impl RemovalSummary {
    /// Number of entries successfully removed.
    #[must_use]
    pub const fn removed_count(&self) -> usize {
        self.removed_count
    }

    /// Number of entries that could not be removed (blocked).
    #[must_use]
    pub const fn blocked_count(&self) -> usize {
        self.blocked_count
    }

    /// Total bytes freed from successful removals.
    #[must_use]
    pub const fn total_bytes_freed(&self) -> i64 {
        self.total_bytes_freed
    }

    /// Create an empty summary with all counts at zero.
    ///
    /// Primarily useful for testing or initialization.
    // Allow: Used in tests for creating empty summaries. Part of the public API
    // for testing and initialization scenarios.
    #[allow(dead_code)]
    pub const fn empty() -> Self {
        Self {
            removed_count: 0,
            blocked_count: 0,
            total_bytes_freed: 0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::AuditService;
    use crate::db::Database;
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;
    use tempfile::TempDir;

    /// Helper to create a temporary database for testing.
    fn temp_database() -> (Database, TempDir) {
        let temp_dir = TempDir::with_prefix("stagecrew-removal-test-").expect(
            "failed to create temp directory for removal test - check disk space and permissions",
        );
        let db_path = temp_dir.path().join("test.db");
        let db = Database::open(&db_path)
            .expect("failed to open test database - check permissions and disk space");
        (db, temp_dir)
    }

    /// Helper to create a directory with test files.
    fn create_test_directory(root: &Path, name: &str, file_count: usize) -> (PathBuf, i64) {
        let dir_path = root.join(name);
        fs::create_dir(&dir_path)
            .expect("failed to create test directory structure - check disk space and permissions");

        let mut total_size = 0i64;
        for i in 0..file_count {
            let file_path = dir_path.join(format!("file{i}.txt"));
            let content = format!("Test content {i}");
            fs::write(&file_path, &content)
                .expect("failed to write test data to file - disk may be full");
            // Allow: content.len() is small test data, will never exceed i64::MAX.
            // In production, file sizes come from fs::metadata which returns u64.
            #[allow(clippy::cast_possible_wrap)]
            {
                total_size += content.len() as i64;
            }
        }

        (dir_path, total_size)
    }

    #[test]
    fn remove_approved_processes_approved_entries() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-removal-files-").expect(
            "failed to create temp directory for removal test - check disk space and permissions",
        );

        // Create two test directories with files
        let (dir1_path, dir1_size) = create_test_directory(test_root.path(), "dir1", 3);
        let (dir2_path, dir2_size) = create_test_directory(test_root.path(), "dir2", 2);

        // Insert root and entries into database
        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let entry1_id = db
            .upsert_entry(
                root_id,
                &dir1_path,
                test_root.path(),
                true,
                dir1_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        let entry2_id = db
            .upsert_entry(
                root_id,
                &dir2_path,
                test_root.path(),
                true,
                dir2_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");

        // Approve both entries
        db.update_entry_status(entry1_id, "approved")
            .expect("failed to update entry status - database connection may be lost");
        db.update_entry_status(entry2_id, "approved")
            .expect("failed to update entry status - database connection may be lost");

        // Verify directories exist
        assert!(dir1_path.exists());
        assert!(dir2_path.exists());

        // Remove approved entries
        let summary = remove_approved(&db)
            .expect("failed to remove approved entries - check permissions and disk space");

        // Verify summary
        assert_eq!(summary.removed_count(), 2, "Expected 2 entries removed");
        assert_eq!(summary.blocked_count(), 0, "Expected no blocked entries");
        assert_eq!(
            summary.total_bytes_freed(),
            dir1_size + dir2_size,
            "Expected total bytes freed to match sum of entry sizes"
        );

        // Verify directories are gone
        assert!(!dir1_path.exists(), "Directory should be removed");
        assert!(!dir2_path.exists(), "Directory should be removed");

        // Verify database status updated
        let entry1 = db
            .get_entry_by_path(&dir1_path)
            .expect("failed to query entry from database - connection may be lost")
            .expect("expected entry to exist after insertion - verify test database is working");
        assert_eq!(entry1.status, "removed", "Status should be 'removed'");

        let entry2 = db
            .get_entry_by_path(&dir2_path)
            .expect("failed to query entry from database - connection may be lost")
            .expect("expected entry to exist after insertion - verify test database is working");
        assert_eq!(entry2.status, "removed", "Status should be 'removed'");

        // Verify audit entries
        let audit = AuditService::new(&db);
        let entries = audit
            .list_recent(10)
            .expect("failed to query recent audit entries - database connection may be lost");
        assert_eq!(entries.len(), 2, "Expected 2 audit entries");

        for entry in &entries {
            assert_eq!(entry.action, "remove");
            assert!(entry.details.is_some());
            assert!(
                entry
                    .details
                    .as_ref()
                    .expect("expected audit entry to have details - verify audit trail is working")
                    .contains("Permanently deleted")
            );
        }
    }

    #[test]
    fn remove_approved_handles_permission_denied() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-removal-files-").expect(
            "failed to create temp directory for removal test - check disk space and permissions",
        );

        // Create test directory with files
        let (dir_path, dir_size) = create_test_directory(test_root.path(), "protected", 2);

        // Make directory read-only to trigger permission error
        let mut perms = fs::metadata(&dir_path)
            .expect("failed to read file permissions - check file exists and is accessible")
            .permissions();
        perms.set_mode(0o444); // Read-only
        fs::set_permissions(&dir_path, perms)
            .expect("failed to set file permissions for test - check filesystem support");

        // Insert root and entry into database and approve
        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let entry_id = db
            .upsert_entry(
                root_id,
                &dir_path,
                test_root.path(),
                true,
                dir_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(entry_id, "approved")
            .expect("failed to update entry status - database connection may be lost");

        // Attempt removal
        let summary = remove_approved(&db)
            .expect("failed to remove approved entries - check permissions and disk space");

        // Verify summary
        assert_eq!(summary.removed_count(), 0, "Expected no entries removed");
        assert_eq!(summary.blocked_count(), 1, "Expected 1 blocked entry");
        assert_eq!(summary.total_bytes_freed(), 0, "Expected no bytes freed");

        // Verify directory still exists
        assert!(dir_path.exists(), "Directory should still exist");

        // Verify database status updated to blocked
        let entry = db
            .get_entry_by_path(&dir_path)
            .expect("failed to query entry from database - connection may be lost")
            .expect("expected entry to exist after insertion - verify test database is working");
        assert_eq!(entry.status, "blocked", "Status should be 'blocked'");

        // Verify audit entry
        let audit = AuditService::new(&db);
        let entries = audit
            .list_recent(10)
            .expect("failed to query recent audit entries - database connection may be lost");
        assert_eq!(entries.len(), 1, "Expected 1 audit entry");
        assert_eq!(entries[0].action, "remove");
        assert!(
            entries[0]
                .details
                .as_ref()
                .expect("expected audit entry to have details - verify audit trail is working")
                .contains("permission denied")
        );

        // Cleanup: restore permissions so tempdir can be removed
        let mut perms = fs::metadata(&dir_path)
            .expect("failed to read file permissions - check file exists and is accessible")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&dir_path, perms)
            .expect("failed to set file permissions for test - check filesystem support");
    }

    #[test]
    fn remove_approved_handles_nonexistent_path() {
        let (db, _temp_dir) = temp_database();

        // Insert root and entry that doesn't exist on filesystem
        let root_id = db
            .insert_root(Path::new("/nonexistent"))
            .expect("failed to insert root - database connection may be lost");
        let entry_path = Path::new("/nonexistent/path/to/directory");
        let now = jiff::Timestamp::now().as_second();
        let entry_id = db
            .upsert_entry(
                root_id,
                entry_path,
                Path::new("/nonexistent/path/to"),
                true,
                1024,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(entry_id, "approved")
            .expect("failed to update entry status - database connection may be lost");

        // Attempt removal
        let summary = remove_approved(&db)
            .expect("failed to remove approved entries - check permissions and disk space");

        // Verify summary
        assert_eq!(summary.removed_count(), 0, "Expected no entries removed");
        assert_eq!(summary.blocked_count(), 1, "Expected 1 blocked entry");
        assert_eq!(summary.total_bytes_freed(), 0, "Expected no bytes freed");

        // Verify database status updated to blocked
        let entry = db
            .get_entry_by_path(entry_path)
            .expect("failed to query entry from database - connection may be lost")
            .expect("expected entry to exist after insertion - verify test database is working");
        assert_eq!(entry.status, "blocked", "Status should be 'blocked'");

        // Verify audit entry
        let audit = AuditService::new(&db);
        let entries = audit
            .list_recent(10)
            .expect("failed to query recent audit entries - database connection may be lost");
        assert_eq!(entries.len(), 1, "Expected 1 audit entry");
        assert_eq!(entries[0].action, "remove");
        assert!(entries[0].details.is_some());
    }

    #[test]
    fn remove_approved_handles_mixed_success_and_failure() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-removal-files-").expect(
            "failed to create temp directory for removal test - check disk space and permissions",
        );

        // Create two directories: one normal, one protected
        let (dir1_path, dir1_size) = create_test_directory(test_root.path(), "normal", 2);
        let (dir2_path, dir2_size) = create_test_directory(test_root.path(), "protected", 2);

        // Make second directory read-only
        let mut perms = fs::metadata(&dir2_path)
            .expect("failed to read file permissions - check file exists and is accessible")
            .permissions();
        perms.set_mode(0o444);
        fs::set_permissions(&dir2_path, perms)
            .expect("failed to set file permissions for test - check filesystem support");

        // Insert root and approve both entries
        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let entry1_id = db
            .upsert_entry(
                root_id,
                &dir1_path,
                test_root.path(),
                true,
                dir1_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        let entry2_id = db
            .upsert_entry(
                root_id,
                &dir2_path,
                test_root.path(),
                true,
                dir2_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(entry1_id, "approved")
            .expect("failed to update entry status - database connection may be lost");
        db.update_entry_status(entry2_id, "approved")
            .expect("failed to update entry status - database connection may be lost");

        // Attempt removal
        let summary = remove_approved(&db)
            .expect("failed to remove approved entries - check permissions and disk space");

        // Verify summary
        assert_eq!(summary.removed_count(), 1, "Expected 1 entry removed");
        assert_eq!(summary.blocked_count(), 1, "Expected 1 blocked entry");
        assert_eq!(
            summary.total_bytes_freed(),
            dir1_size,
            "Expected bytes freed from successful removal only"
        );

        // Verify first directory removed, second still exists
        assert!(!dir1_path.exists());
        assert!(dir2_path.exists());

        // Verify database statuses
        let entry1 = db
            .get_entry_by_path(&dir1_path)
            .expect("failed to query entry from database - connection may be lost")
            .expect("expected entry to exist after insertion - verify test database is working");
        assert_eq!(entry1.status, "removed");

        let entry2 = db
            .get_entry_by_path(&dir2_path)
            .expect("failed to query entry from database - connection may be lost")
            .expect("expected entry to exist after insertion - verify test database is working");
        assert_eq!(entry2.status, "blocked");

        // Cleanup
        let mut perms = fs::metadata(&dir2_path)
            .expect("failed to read file permissions - check file exists and is accessible")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&dir2_path, perms)
            .expect("failed to set file permissions for test - check filesystem support");
    }

    #[test]
    fn remove_approved_returns_empty_summary_when_no_approved() {
        let (db, _temp_dir) = temp_database();

        // Insert root and entries with non-approved statuses
        let root_id = db
            .insert_root(Path::new("/data"))
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let entry1_id = db
            .upsert_entry(
                root_id,
                Path::new("/data/path1"),
                Path::new("/data"),
                false,
                1024,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        let entry2_id = db
            .upsert_entry(
                root_id,
                Path::new("/data/path2"),
                Path::new("/data"),
                false,
                2048,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");

        db.update_entry_status(entry1_id, "tracked")
            .expect("failed to update entry status - database connection may be lost");
        db.update_entry_status(entry2_id, "pending")
            .expect("failed to update entry status - database connection may be lost");

        // Attempt removal
        let summary = remove_approved(&db)
            .expect("failed to remove approved entries - check permissions and disk space");

        // Verify empty summary
        assert_eq!(summary.removed_count(), 0);
        assert_eq!(summary.blocked_count(), 0);
        assert_eq!(summary.total_bytes_freed(), 0);

        // Verify no audit entries
        let audit = AuditService::new(&db);
        let entries = audit
            .list_recent(10)
            .expect("failed to query recent audit entries - database connection may be lost");
        assert_eq!(entries.len(), 0, "Expected no audit entries");
    }

    #[test]
    fn remove_approved_records_audit_entries_with_entry_id() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-removal-files-").expect(
            "failed to create temp directory for removal test - check disk space and permissions",
        );

        let (dir_path, dir_size) = create_test_directory(test_root.path(), "dir", 2);
        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let entry_id = db
            .upsert_entry(
                root_id,
                &dir_path,
                test_root.path(),
                true,
                dir_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(entry_id, "approved")
            .expect("failed to update entry status - database connection may be lost");

        let _summary = remove_approved(&db)
            .expect("failed to remove approved entries - check permissions and disk space");

        // Verify audit entry has entry_id
        let audit = AuditService::new(&db);
        let entries = audit
            .list_recent(10)
            .expect("failed to query recent audit entries - database connection may be lost");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].entry_id, Some(entry_id));
        assert_eq!(
            entries[0].target_path,
            Some(dir_path.to_string_lossy().into_owned())
        );
    }

    #[test]
    fn check_removability_succeeds_for_existing_file() {
        let temp_dir = TempDir::with_prefix("stagecrew-removability-test-").expect(
            "failed to create temp directory for removability test - check disk space and permissions",
        );
        let file_path = temp_dir.path().join("exists.txt");
        fs::write(&file_path, "test content")
            .expect("failed to write test file - disk may be full");

        assert!(
            check_removability(&file_path).is_ok(),
            "Existing file should pass removability check"
        );
    }

    #[test]
    fn check_removability_succeeds_for_existing_directory() {
        let temp_dir = TempDir::with_prefix("stagecrew-removability-test-").expect(
            "failed to create temp directory for removability test - check disk space and permissions",
        );
        let dir_path = temp_dir.path().join("subdir");
        fs::create_dir(&dir_path)
            .expect("failed to create test directory - check disk space and permissions");

        assert!(
            check_removability(&dir_path).is_ok(),
            "Existing directory should pass removability check"
        );
    }

    #[test]
    fn check_removability_fails_for_nonexistent_path() {
        let result = check_removability(Path::new("/nonexistent/path/to/file.txt"));
        assert!(result.is_err(), "Nonexistent path should fail");
        assert!(
            matches!(result, Err(Error::PathNotFound(_))),
            "Error should be PathNotFound"
        );
    }

    #[test]
    fn dry_run_approved_with_no_approved_entries() {
        let (db, _temp_dir) = temp_database();
        let root_id = db
            .insert_root(Path::new("/data"))
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let entry_id = db
            .upsert_entry(
                root_id,
                Path::new("/data/file.txt"),
                Path::new("/data"),
                false,
                1024,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(entry_id, "tracked")
            .expect("failed to update entry status - database connection may be lost");

        let result = dry_run_approved(&db, root_id)
            .expect("dry run should succeed even with no approved entries");
        assert_eq!(result.total_count, 0);
        assert_eq!(result.removable_count, 0);
        assert!(result.failures.is_empty());
    }

    #[test]
    fn dry_run_approved_all_entries_exist() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-dryrun-test-").expect(
            "failed to create temp directory for dry run test - check disk space and permissions",
        );

        let (dir1_path, dir1_size) = create_test_directory(test_root.path(), "dir1", 2);
        let (dir2_path, dir2_size) = create_test_directory(test_root.path(), "dir2", 2);

        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let id1 = db
            .upsert_entry(
                root_id,
                &dir1_path,
                test_root.path(),
                true,
                dir1_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        let id2 = db
            .upsert_entry(
                root_id,
                &dir2_path,
                test_root.path(),
                true,
                dir2_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(id1, "approved")
            .expect("failed to update entry status - database connection may be lost");
        db.update_entry_status(id2, "approved")
            .expect("failed to update entry status - database connection may be lost");

        let result = dry_run_approved(&db, root_id)
            .expect("dry run should succeed when entries exist on disk");
        assert_eq!(result.total_count, 2);
        assert_eq!(result.removable_count, 2);
        assert!(result.failures.is_empty());
    }

    #[test]
    fn dry_run_approved_mixed_existing_and_nonexistent() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-dryrun-test-").expect(
            "failed to create temp directory for dry run test - check disk space and permissions",
        );

        let (dir_path, dir_size) = create_test_directory(test_root.path(), "exists", 2);
        let missing_path = test_root.path().join("gone");

        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let id1 = db
            .upsert_entry(
                root_id,
                &dir_path,
                test_root.path(),
                true,
                dir_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        let id2 = db
            .upsert_entry(root_id, &missing_path, test_root.path(), true, 0, Some(now))
            .expect("failed to insert test entry - database connection may be lost");
        db.update_entry_status(id1, "approved")
            .expect("failed to update entry status - database connection may be lost");
        db.update_entry_status(id2, "approved")
            .expect("failed to update entry status - database connection may be lost");

        let result =
            dry_run_approved(&db, root_id).expect("dry run should succeed even with mixed results");
        assert_eq!(result.total_count, 2);
        assert_eq!(result.removable_count, 1);
        assert_eq!(result.failures.len(), 1);
        assert_eq!(result.failures[0].path, missing_path);
    }

    #[test]
    fn dry_run_approved_ignores_non_approved_entries() {
        let (db, _temp_dir) = temp_database();
        let test_root = TempDir::with_prefix("stagecrew-dryrun-test-").expect(
            "failed to create temp directory for dry run test - check disk space and permissions",
        );

        let (dir_path, dir_size) = create_test_directory(test_root.path(), "dir", 2);

        let root_id = db
            .insert_root(test_root.path())
            .expect("failed to insert root - database connection may be lost");
        let now = jiff::Timestamp::now().as_second();
        let id1 = db
            .upsert_entry(
                root_id,
                &dir_path,
                test_root.path(),
                true,
                dir_size,
                Some(now),
            )
            .expect("failed to insert test entry - database connection may be lost");
        // Leave as "tracked" — should not appear in dry run
        let _ = id1;

        let result = dry_run_approved(&db, root_id)
            .expect("dry run should succeed with no approved entries");
        assert_eq!(
            result.total_count, 0,
            "Tracked entries should not be checked"
        );
    }
}