lific 2.8.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
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
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use tracing::{error, info, warn};

use crate::config::BackupConfig;
use crate::db::DbPool;
use crate::dump;

/// Start the background backup task. Returns the JoinHandle.
pub fn start_backup_task(
    pool: Arc<DbPool>,
    db_path: PathBuf,
    config: BackupConfig,
) -> tokio::task::JoinHandle<()> {
    let backup_dir = if config.dir.is_absolute() {
        config.dir.clone()
    } else if let Some(parent) = db_path.parent() {
        parent.join(&config.dir)
    } else {
        config.dir.clone()
    };

    let interval_minutes = checked_interval_minutes(config.interval_minutes);
    let interval = Duration::from_secs(interval_minutes * 60);
    let retain = checked_retain(config.retain);
    let audit_retention_days = config.audit_retention_days;

    tokio::spawn(async move {
        if let Err(e) = std::fs::create_dir_all(&backup_dir) {
            error!(dir = %backup_dir.display(), error = %e, "failed to create backup directory");
            return;
        }

        info!(
            dir = %backup_dir.display(),
            interval_min = interval_minutes,
            retain = retain,
            audit_retention_days = audit_retention_days.unwrap_or(0),
            "backup task started"
        );

        // Run initial backup after a short delay (let the server finish starting)
        tokio::time::sleep(Duration::from_secs(5)).await;
        run_backup_blocking(&pool, &db_path, &backup_dir, retain, audit_retention_days).await;

        // Then run on interval
        let mut interval_timer = tokio::time::interval(interval);
        interval_timer.tick().await; // skip first immediate tick
        loop {
            interval_timer.tick().await;
            // Awaited, so this task never has more than one backup in flight.
            // `tokio::time::interval` catches up by firing immediately after a
            // long tick rather than queueing them, so a backup that outruns
            // its interval delays the next one instead of stacking blocking
            // jobs on the pool.
            run_backup_blocking(&pool, &db_path, &backup_dir, retain, audit_retention_days).await;
        }
    })
}

/// Run one backup on the blocking pool and wait for it.
///
/// `run_backup` is synchronous, file-heavy work that takes the attachment
/// store lock, and under that lock it can wait on whatever else holds the
/// store. Calling it directly from the async task would park a Tokio worker
/// thread for that whole time, and workers are the threads serving every HTTP
/// request. `spawn_blocking` puts it on the pool meant for exactly this.
///
/// The `.await` is what bounds the work: one backup task drives one blocking
/// job at a time, so a slow backup can never accumulate a queue of them.
async fn run_backup_blocking(
    pool: &Arc<DbPool>,
    db_path: &Path,
    backup_dir: &Path,
    retain: usize,
    audit_retention_days: Option<u32>,
) {
    let pool = Arc::clone(pool);
    let db_path = db_path.to_path_buf();
    let backup_dir = backup_dir.to_path_buf();
    let result = tokio::task::spawn_blocking(move || {
        run_backup(&pool, &db_path, &backup_dir, retain, audit_retention_days);
    })
    .await;
    if let Err(e) = result {
        // A panic inside the backup must not kill the scheduling loop: the
        // next interval should still try.
        error!(error = %e, "backup job failed to run to completion");
    }
}

/// The configured backup interval, or the default when the config says `0`
/// (LIF-415).
///
/// Zero is never a schedule anyone wants: `tokio::time::interval` panics on a
/// zero period, and because the timer is built inside the spawned task the
/// panic kills backups silently while the server keeps serving. Falling back
/// to the default with a warning keeps the instance backed up and tells the
/// operator their value was ignored, which matches how the rest of the config
/// treats a value it cannot honor.
fn checked_interval_minutes(configured: u64) -> u64 {
    if configured == 0 {
        let fallback = BackupConfig::default().interval_minutes;
        warn!(
            fallback_minutes = fallback,
            "[backup] interval_minutes = 0 is not a valid schedule; using the default instead"
        );
        return fallback;
    }
    configured
}

/// The configured retention count, or the default when the config says `0`
/// (LIF-415).
///
/// `retain = 0` reads like "keep no old backups" but means "keep nothing at
/// all": rotation runs right after each archive is written, so every
/// successful backup is deleted seconds after it lands and the instance ends
/// up with no backups while reporting healthy ones. An operator who genuinely
/// wants no backups sets `enabled = false`.
fn checked_retain(configured: usize) -> usize {
    if configured == 0 {
        let fallback = BackupConfig::default().retain;
        warn!(
            fallback_retain = fallback,
            "[backup] retain = 0 would delete every backup as soon as it is written; using \
             the default instead (set [backup] enabled = false to turn backups off)"
        );
        return fallback;
    }
    configured
}

/// Whether we've already logged the one-time hint about the legacy mirrored
/// `attachments/` dir left behind by the pre-LIF-266 backup scheme.
static LEGACY_MIRROR_HINTED: AtomicBool = AtomicBool::new(false);

/// Perform a single backup: write one self-contained `.tar.gz` archive via the
/// shared dump code path (same artifact `lific dump` produces), then rotate.
///
/// LIF-266: this replaces the old bare-`.db` snapshot plus additive
/// attachments-mirror scheme. The mirror grew forever (blobs were never GC'd);
/// self-contained archives sidestep that (at the cost of duplicating blobs per
/// archive — acceptable at current scale).
fn run_backup(
    pool: &DbPool,
    db_path: &Path,
    backup_dir: &Path,
    retain: usize,
    audit_retention_days: Option<u32>,
) {
    let db_stem = db_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("lific");

    // Sweep staging leftovers from a previous crashed/failed run first, so
    // they get cleaned even if this run's backup fails too (LIF-329).
    sweep_stale_tmps(backup_dir, db_stem);

    let filename = dump::archive_filename(db_stem, &dump::archive_timestamp());
    let backup_path = backup_dir.join(&filename);

    match dump::write_dump(pool, db_path, &backup_path) {
        Ok(manifest) => {
            let size = std::fs::metadata(&backup_path).map_or(0, |m| m.len());
            info!(
                path = %backup_path.display(),
                size_kb = size / 1024,
                attachments = manifest.attachment_count,
                "backup archive written"
            );
        }
        Err(e) => {
            error!(error = %e, "backup archive failed");
            let _ = std::fs::remove_file(&backup_path);
            return;
        }
    }

    // One-time hint about the legacy mirrored attachments dir (old scheme). It
    // is no longer written to or read from; the operator can delete it.
    let legacy_mirror = backup_dir.join("attachments");
    if legacy_mirror.is_dir() && !LEGACY_MIRROR_HINTED.swap(true, Ordering::Relaxed) {
        info!(
            dir = %legacy_mirror.display(),
            "legacy mirrored attachments dir from the pre-archive backup scheme is no longer \
             used and can be deleted"
        );
    }

    rotate_backups(backup_dir, db_stem, retain);

    // Audit retention runs last, and only on a run that produced an archive:
    // the dump failure path above returns early, so history is never dropped
    // by a cycle that failed to preserve it first.
    prune_audit_log(pool, audit_retention_days);

    trim_retained_heap();
}

/// Hand freed heap back to the OS after each backup cycle (glibc only).
///
/// glibc's malloc never returns freed sub-128KB chunks to the kernel on its
/// own: each request burst (a project export, a sync-index bootstrap, an
/// attachment round-trip) ratchets some arena's high-water mark up, and the
/// freed memory then sits in that arena's free lists forever. Profiling the
/// production instance after six days of agent traffic found 448MB of
/// freed-but-retained heap across 22 arenas against 27MB of live objects.
///
/// `malloc_trim(0)` walks every arena and releases its free chunks back to
/// the kernel (`MADV_DONTNEED`), which is exactly the memory described above.
/// The backup task is a convenient heartbeat for it: every cycle, off the
/// request path, on a blocking thread. The call is process-wide, costs
/// milliseconds at this heap size, and is a no-op for whatever is actually
/// live.
///
/// Gated to `linux + gnu`: musl, macOS, and Windows allocators don't have the
/// arena-retention behavior (or the function).
fn trim_retained_heap() {
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    // SAFETY: malloc_trim has no preconditions; it takes the arena locks
    // itself and is safe to call from any thread at any time.
    unsafe {
        libc::malloc_trim(0);
    }
}

/// Delete `audit_log` rows older than the configured retention window
/// (LIF-158).
///
/// `None` and `Some(0)` both mean "keep forever" and do nothing, so the
/// default install keeps the append-only history it has always kept. Anything
/// larger deletes rows whose `ts` predates the cutoff.
///
/// The cutoff is computed by SQLite itself (`datetime('now', '-N days')`)
/// rather than in Rust: `audit_log.ts` is written by the migration-018
/// triggers as `datetime('now')`, so comparing against a value from the same
/// clock and the same format is the only way the comparison is honest. The
/// negative-modifier-as-bind-parameter shape matches
/// `queries::attachments::find_orphans`.
fn prune_audit_log(pool: &DbPool, audit_retention_days: Option<u32>) {
    let Some(days) = audit_retention_days.filter(|d| *d > 0) else {
        return;
    };

    let conn = match pool.write() {
        Ok(conn) => conn,
        Err(e) => {
            warn!(error = %e, "could not acquire write connection for audit log pruning");
            return;
        }
    };

    let cutoff = format!("-{days} days");
    match conn.execute(
        "DELETE FROM audit_log WHERE ts < datetime('now', ?1)",
        rusqlite::params![cutoff],
    ) {
        Ok(0) => {}
        Ok(deleted) => info!(
            deleted,
            retention_days = days,
            "pruned old audit log entries"
        ),
        Err(e) => warn!(error = %e, "audit log pruning failed"),
    }
}

/// How old a dump staging file must be before the sweep considers it stale.
/// A live dump finishes in seconds; anything an hour old is a crash leftover.
const STALE_TMP_AGE: Duration = Duration::from_secs(60 * 60);

/// Delete stale dump staging files leaked by a crash mid-backup (LIF-329).
///
/// `write_dump` stages a private `.lific-dump-*` directory beside the output
/// archive and cleans it itself on success or error. Age-gated so an
/// in-flight dump's staging directory is never swept.
fn sweep_stale_tmps(backup_dir: &Path, db_stem: &str) {
    let prefix = format!("{db_stem}_");
    let entries = match std::fs::read_dir(backup_dir) {
        Ok(entries) => entries,
        Err(e) => {
            warn!(error = %e, "failed to read backup directory for tmp sweep");
            return;
        }
    };
    for entry in entries.filter_map(|e| e.ok()) {
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        let is_new_staging_dir = name.starts_with(".lific-dump-");
        let is_legacy_tmp = name.starts_with(&prefix)
            && (name.ends_with(".dbsnapshot.tmp") || name.ends_with(".archive.tmp"));
        if !is_new_staging_dir && !is_legacy_tmp {
            continue;
        }
        let age_path = if is_new_staging_dir {
            path.join("activity")
        } else {
            path.clone()
        };
        let stale = std::fs::symlink_metadata(&age_path)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|modified| modified.elapsed().ok())
            .is_some_and(|age| age > STALE_TMP_AGE);
        if !stale {
            continue;
        }
        if is_new_staging_dir {
            if dump::staging_is_locked(&path) {
                continue;
            }
            let activity = path.join("activity");
            let active = std::fs::symlink_metadata(&activity)
                .and_then(|metadata| metadata.modified())
                .ok()
                .and_then(|modified| modified.elapsed().ok())
                .is_some_and(|age| age <= STALE_TMP_AGE);
            if active {
                continue;
            }
        }
        let result = if is_new_staging_dir {
            std::fs::remove_dir_all(&path)
        } else {
            std::fs::remove_file(&path)
        };
        match result {
            Ok(()) => info!(path = %path.display(), "removed stale backup staging file"),
            Err(e) => {
                warn!(path = %path.display(), error = %e, "failed to remove stale staging file")
            }
        }
    }
}

/// Keep only the N most recent backup archives, delete the rest.
///
/// LIF-266: rotation candidates are the new `.tar.gz` archives AND legacy
/// bare-`.db` snapshots from the old scheme (both share the `{stem}_` prefix
/// and a sortable timestamp), so old snapshots age out naturally alongside new
/// archives. The legacy mirrored `attachments/` dir is left alone (it isn't a
/// per-run artifact); a one-time hint in `run_backup` notes it can be deleted.
fn rotate_backups(backup_dir: &Path, db_stem: &str, retain: usize) {
    let prefix = format!("{db_stem}_");
    let mut backups: Vec<PathBuf> = match std::fs::read_dir(backup_dir) {
        Ok(entries) => entries
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| {
                let name = match p.file_name().and_then(|n| n.to_str()) {
                    Some(n) => n,
                    None => return false,
                };
                if !name.starts_with(&prefix) {
                    return false;
                }
                // New archives (`.tar.gz`) or legacy snapshots (`.db`).
                name.ends_with(".tar.gz") || p.extension().and_then(|e| e.to_str()) == Some("db")
            })
            .collect(),
        Err(e) => {
            warn!(error = %e, "failed to read backup directory for rotation");
            return;
        }
    };

    // Sort by filename (timestamps sort lexicographically)
    backups.sort();

    // Remove oldest backups beyond retention
    if backups.len() > retain {
        let to_remove = backups.len() - retain;
        for path in backups.iter().take(to_remove) {
            match std::fs::remove_file(path) {
                Ok(()) => info!(path = %path.display(), "removed old backup"),
                Err(e) => warn!(path = %path.display(), error = %e, "failed to remove old backup"),
            }
        }
    }
}

/// Checkpoint the WAL into the main database file.
/// Call this on clean shutdown so the .db file is fully self-contained.
pub fn checkpoint_wal(pool: &DbPool) {
    match pool.write() {
        Ok(conn) => match conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);") {
            Ok(()) => info!("WAL checkpointed on shutdown"),
            Err(e) => warn!(error = %e, "WAL checkpoint failed"),
        },
        Err(e) => warn!(error = %e, "could not acquire write connection for checkpoint"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Scratch directory for one test. The returned guard removes the
    /// directory on Drop, including while a failing assertion unwinds, so a
    /// panicking test cannot leave stale state behind for a later run.
    fn make_temp_dir() -> TempDir {
        tempfile::tempdir().unwrap()
    }

    fn make_backup_dir(parent: &Path) -> PathBuf {
        let backup_dir = parent.join("backups");
        fs::create_dir_all(&backup_dir).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&backup_dir, fs::Permissions::from_mode(0o700)).unwrap();
        }
        backup_dir
    }

    #[test]
    fn rotate_keeps_only_retain_count() {
        let tmp = make_temp_dir();
        let dir = tmp.path();

        // Create 5 fake archive files with lexicographic timestamps
        for i in 1..=5 {
            fs::write(dir.join(format!("lific_2026010{i}_120000.tar.gz")), "fake").unwrap();
        }

        rotate_backups(dir, "lific", 3);

        let remaining: Vec<_> = fs::read_dir(dir).unwrap().filter_map(|e| e.ok()).collect();
        assert_eq!(remaining.len(), 3);

        // Oldest two (01, 02) should be gone, newest three (03, 04, 05) kept
        assert!(!dir.join("lific_20260101_120000.tar.gz").exists());
        assert!(!dir.join("lific_20260102_120000.tar.gz").exists());
        assert!(dir.join("lific_20260103_120000.tar.gz").exists());
        assert!(dir.join("lific_20260105_120000.tar.gz").exists());
    }

    #[test]
    fn rotate_does_nothing_under_retain() {
        let tmp = make_temp_dir();
        let dir = tmp.path();

        fs::write(dir.join("lific_20260101_120000.tar.gz"), "fake").unwrap();
        fs::write(dir.join("lific_20260102_120000.tar.gz"), "fake").unwrap();

        rotate_backups(dir, "lific", 5);

        let count = fs::read_dir(dir).unwrap().count();
        assert_eq!(count, 2);
    }

    #[test]
    fn rotate_ignores_other_files() {
        let tmp = make_temp_dir();
        let dir = tmp.path();

        // These should be ignored (wrong prefix / extension)
        fs::write(dir.join("other_20260101_120000.tar.gz"), "x").unwrap();
        fs::write(dir.join("lific_20260101_120000.txt"), "x").unwrap();
        // These are real archives
        fs::write(dir.join("lific_20260101_120000.tar.gz"), "x").unwrap();
        fs::write(dir.join("lific_20260102_120000.tar.gz"), "x").unwrap();

        rotate_backups(dir, "lific", 1);

        // Only 1 backup kept, non-matching files untouched
        assert!(dir.join("other_20260101_120000.tar.gz").exists());
        assert!(dir.join("lific_20260101_120000.txt").exists());
        assert!(!dir.join("lific_20260101_120000.tar.gz").exists()); // oldest removed
        assert!(dir.join("lific_20260102_120000.tar.gz").exists()); // kept
    }

    #[test]
    fn rotate_ages_out_legacy_db_snapshots_alongside_archives() {
        // LIF-266: pre-archive `.db` snapshots from the old scheme are
        // rotation candidates too, so they age out naturally instead of
        // accumulating forever next to the new `.tar.gz` archives.
        let tmp = make_temp_dir();
        let dir = tmp.path();
        // Two legacy .db snapshots (older timestamps) + two new archives.
        fs::write(dir.join("lific_20260101_120000.db"), "old1").unwrap();
        fs::write(dir.join("lific_20260102_120000.db"), "old2").unwrap();
        fs::write(dir.join("lific_20260103_120000.tar.gz"), "new1").unwrap();
        fs::write(dir.join("lific_20260104_120000.tar.gz"), "new2").unwrap();

        rotate_backups(dir, "lific", 2);

        // The two oldest (legacy .db) are gone; the two newest archives kept.
        assert!(!dir.join("lific_20260101_120000.db").exists());
        assert!(!dir.join("lific_20260102_120000.db").exists());
        assert!(dir.join("lific_20260103_120000.tar.gz").exists());
        assert!(dir.join("lific_20260104_120000.tar.gz").exists());
    }

    /// Backdate a file's mtime so the sweep sees it as stale.
    #[tokio::test]
    async fn a_scheduled_backup_does_not_park_the_async_runtime() {
        // A `#[tokio::test]` runs on a single-threaded runtime, so this is a
        // real discriminator: if the backup ran inline on the async task, the
        // counter task below could not tick at all while it worked. It has to
        // be on the blocking pool for both to make progress.
        use std::sync::Arc;
        use std::sync::atomic::AtomicUsize;

        let tmp = make_temp_dir();
        let dir = tmp.path();
        let db_path = dir.join("lific.db");
        let backup_dir = make_backup_dir(dir);
        let pool = Arc::new(crate::db::open(&db_path).expect("open test db"));

        // Hold the attachment store lock briefly, so the backup has something
        // real to wait on inside its blocking job.
        let store = crate::storage::AttachmentStore::from_db_path(&db_path);
        let (holding_tx, holding_rx) = std::sync::mpsc::sync_channel::<()>(1);
        let holder = std::thread::spawn(move || {
            store
                .with_lock(|_| {
                    holding_tx.send(()).unwrap();
                    std::thread::sleep(Duration::from_millis(200));
                    Ok(())
                })
                .unwrap();
        });
        holding_rx.recv_timeout(Duration::from_secs(10)).unwrap();

        let ticks = Arc::new(AtomicUsize::new(0));
        let counter = tokio::spawn({
            let ticks = Arc::clone(&ticks);
            async move {
                loop {
                    tokio::time::sleep(Duration::from_millis(5)).await;
                    ticks.fetch_add(1, Ordering::Relaxed);
                }
            }
        });

        run_backup_blocking(&pool, &db_path, &backup_dir, 5, None).await;
        counter.abort();
        holder.join().unwrap();

        assert!(
            ticks.load(Ordering::Relaxed) > 0,
            "async work must keep running while a backup is in flight"
        );
        let archives = fs::read_dir(&backup_dir)
            .unwrap()
            .filter_map(|entry| entry.ok())
            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tar.gz"))
            .count();
        assert_eq!(archives, 1, "and the backup still produced its archive");
    }

    fn backdate(path: &Path, by: Duration) {
        let f = if cfg!(unix) && path.is_dir() {
            fs::File::open(path).unwrap()
        } else {
            fs::File::options().write(true).open(path).unwrap()
        };
        f.set_modified(std::time::SystemTime::now() - by).unwrap();
    }

    #[test]
    fn sweep_removes_stale_staging_tmps_keeps_fresh_and_unrelated() {
        // LIF-329: crash leftovers (`*.dbsnapshot.tmp` / `*.archive.tmp`)
        // older than the stale threshold are swept; fresh staging files (a
        // possibly in-flight dump) and unrelated files are untouched.
        let tmp = make_temp_dir();
        let dir = tmp.path();
        let old = STALE_TMP_AGE + Duration::from_secs(60);

        let stale_snap = dir.join("lific_20260101_120000.tar.dbsnapshot.tmp");
        let stale_arch = dir.join("lific_20260101_120000.tar.archive.tmp");
        let fresh_arch = dir.join("lific_20260714_120000.tar.archive.tmp");
        let other_stem = dir.join("other_20260101_120000.tar.archive.tmp");
        let real_backup = dir.join("lific_20260101_120000.tar.gz");
        let stale_dir = dir.join(".lific-dump-stale");
        for p in [
            &stale_snap,
            &stale_arch,
            &fresh_arch,
            &other_stem,
            &real_backup,
        ] {
            fs::write(p, "x").unwrap();
        }
        fs::create_dir(&stale_dir).unwrap();
        fs::write(stale_dir.join("activity"), "stale").unwrap();
        backdate(&stale_snap, old);
        backdate(&stale_arch, old);
        backdate(&other_stem, old);
        backdate(&real_backup, old);
        backdate(&stale_dir.join("activity"), old);

        sweep_stale_tmps(dir, "lific");

        assert!(!stale_snap.exists(), "stale snapshot tmp must be swept");
        assert!(!stale_arch.exists(), "stale archive tmp must be swept");
        assert!(fresh_arch.exists(), "fresh staging tmp must survive");
        assert!(other_stem.exists(), "other stems are not ours to sweep");
        assert!(
            real_backup.exists(),
            "real archives are rotation's job, not the sweep's"
        );
        assert!(
            !stale_dir.exists(),
            "stale dump staging directory must be swept"
        );
    }

    #[test]
    fn sweep_keeps_stale_directory_while_dump_lock_is_held() {
        use fs2::FileExt;

        let tmp = make_temp_dir();
        let dir = tmp.path();
        let staging = dir.join(".lific-dump-active");
        fs::create_dir(&staging).unwrap();
        fs::write(staging.join("activity"), "active").unwrap();
        let lock = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(staging.join("lock"))
            .unwrap();
        lock.try_lock_exclusive().unwrap();
        backdate(
            &staging.join("activity"),
            STALE_TMP_AGE + Duration::from_secs(60),
        );

        sweep_stale_tmps(dir, "lific");

        assert!(staging.exists(), "a locked dump must not be swept");
        drop(lock);
    }

    #[test]
    fn run_backup_sweeps_stale_tmps_even_when_it_writes_nothing_new() {
        // The sweep runs at the top of run_backup, so leftovers age out on
        // the next interval even if that run's dump were to fail.
        let tmp = make_temp_dir();
        let dir = tmp.path();
        let db_path = dir.join("lific.db");
        let backup_dir = make_backup_dir(dir);
        let pool = crate::db::open(&db_path).expect("open test db");

        let stale = backup_dir.join("lific_20260101_120000.tar.archive.tmp");
        fs::write(&stale, "partial").unwrap();
        backdate(&stale, STALE_TMP_AGE + Duration::from_secs(60));

        run_backup(&pool, &db_path, &backup_dir, 5, None);

        assert!(!stale.exists(), "run_backup must sweep stale staging files");
    }

    #[test]
    fn run_backup_emits_tar_gz_archive_with_data_and_blobs() {
        // LIF-266: the interval task now emits a single self-contained
        // `.tar.gz` archive (same artifact as `lific dump`) carrying the DB
        // snapshot and every non-.tmp attachment blob.
        let tmp = make_temp_dir();
        let dir = tmp.path();
        let db_path = dir.join("lific.db");
        let backup_dir = make_backup_dir(dir);

        // Seed the DB and an attachments sidecar dir next to it.
        let pool = crate::db::open(&db_path).expect("open test db");
        {
            let conn = pool.write().unwrap();
            crate::db::queries::create_project(
                &conn,
                &crate::db::models::CreateProject {
                    name: "BackupTest".into(),
                    identifier: "BKP".into(),
                    description: String::new(),
                    emoji: None,
                    lead_user_id: None,
                },
            )
            .unwrap();
        }
        let att_dir = dir.join("attachments");
        fs::create_dir_all(&att_dir).unwrap();
        // The name must be the content's real hash: a dump verifies every blob
        // against its content address while archiving it.
        let blob_name = crate::storage::AttachmentStore::hash_bytes(b"blob contents");
        fs::write(att_dir.join(&blob_name), b"blob contents").unwrap();
        fs::write(att_dir.join("deadbeefsha.tmp"), b"partial").unwrap();

        run_backup(&pool, &db_path, &backup_dir, 5, None);

        // Exactly one `.tar.gz` archive, no bare `.db` snapshot.
        let archives: Vec<_> = fs::read_dir(&backup_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().to_string())
            .filter(|n| n.ends_with(".tar.gz"))
            .collect();
        assert_eq!(archives.len(), 1, "expected one archive, got {archives:?}");

        // Its contents: db + manifest + the blob, excluding the .tmp write.
        let archive_path = backup_dir.join(&archives[0]);
        let file = fs::File::open(&archive_path).unwrap();
        let dec = flate2::read::GzDecoder::new(file);
        let mut tar = tar::Archive::new(dec);
        let names: Vec<String> = tar
            .entries()
            .unwrap()
            .map(|e| e.unwrap().path().unwrap().to_string_lossy().to_string())
            .collect();
        assert!(names.iter().any(|n| n == crate::dump::ARCHIVE_DB_NAME));
        assert!(
            names
                .iter()
                .any(|n| n == crate::dump::ARCHIVE_MANIFEST_NAME)
        );
        assert!(
            names
                .iter()
                .any(|n| n == &format!("attachments/{blob_name}"))
        );
        assert!(
            !names.iter().any(|n| n.ends_with(".tmp")),
            "in-progress .tmp writes must not be archived: {names:?}"
        );
    }

    // ── LIF-415: backup config validation ─────────────────────────────────

    /// `interval_minutes = 0` builds a zero-period `tokio::time::interval`,
    /// which panics inside the spawned task and takes backups down without
    /// stopping the server. The value is replaced instead.
    #[test]
    fn zero_interval_falls_back_to_the_default_schedule() {
        assert_eq!(
            checked_interval_minutes(0),
            BackupConfig::default().interval_minutes
        );
        // Real values pass through untouched.
        assert_eq!(checked_interval_minutes(1), 1);
        assert_eq!(checked_interval_minutes(30), 30);
    }

    /// `retain = 0` means "delete every archive right after writing it", not
    /// "keep no history": rotation runs at the end of each cycle.
    #[test]
    fn zero_retain_falls_back_to_the_default_count() {
        assert_eq!(checked_retain(0), BackupConfig::default().retain);
        assert_eq!(checked_retain(1), 1);
        assert_eq!(checked_retain(48), 48);
    }

    /// What the clamp prevents: rotation with `retain = 0` removes the
    /// archive the same cycle just produced.
    #[test]
    fn rotate_with_zero_retain_would_delete_everything() {
        let tmp = make_temp_dir();
        let dir = tmp.path();
        fs::write(dir.join("lific_20260101_120000.tar.gz"), "fake").unwrap();
        fs::write(dir.join("lific_20260102_120000.tar.gz"), "fake").unwrap();

        rotate_backups(dir, "lific", 0);
        assert_eq!(fs::read_dir(dir).unwrap().count(), 0);

        // With the clamped value the same directory keeps its archives.
        fs::write(dir.join("lific_20260101_120000.tar.gz"), "fake").unwrap();
        fs::write(dir.join("lific_20260102_120000.tar.gz"), "fake").unwrap();
        rotate_backups(dir, "lific", checked_retain(0));
        assert_eq!(fs::read_dir(dir).unwrap().count(), 2);
    }

    // ── LIF-158: audit log retention ──────────────────────────────────────

    /// Insert one audit row aged `days_ago` days, and return its label so the
    /// assertions can name what survived.
    fn seed_audit_row(pool: &DbPool, label: &str, days_ago: i64) {
        let conn = pool.write().unwrap();
        conn.execute(
            "INSERT INTO audit_log (ts, transport, entity_type, entity_id, entity_label, action)
             VALUES (datetime('now', ?1), 'system', 'issue', 1, ?2, 'create')",
            rusqlite::params![format!("-{days_ago} days"), label],
        )
        .unwrap();
    }

    fn audit_labels(pool: &DbPool) -> Vec<String> {
        let conn = pool.read().unwrap();
        let mut stmt = conn
            .prepare("SELECT entity_label FROM audit_log ORDER BY entity_label")
            .unwrap();
        stmt.query_map([], |row| row.get::<_, String>(0))
            .unwrap()
            .map(|r| r.unwrap())
            .collect()
    }

    #[test]
    fn prune_audit_log_deletes_rows_past_the_window_and_keeps_recent_ones() {
        let pool = crate::db::open_memory().unwrap();
        seed_audit_row(&pool, "ancient", 400);
        seed_audit_row(&pool, "old", 31);
        seed_audit_row(&pool, "recent", 29);
        seed_audit_row(&pool, "today", 0);

        prune_audit_log(&pool, Some(30));

        assert_eq!(audit_labels(&pool), vec!["recent", "today"]);
    }

    #[test]
    fn prune_audit_log_keeps_everything_when_retention_is_unset_or_zero() {
        let pool = crate::db::open_memory().unwrap();
        seed_audit_row(&pool, "ancient", 4000);
        seed_audit_row(&pool, "today", 0);
        let before = audit_labels(&pool);

        // Unset: the default, and the pre-LIF-158 behavior.
        prune_audit_log(&pool, None);
        assert_eq!(audit_labels(&pool), before);

        // Explicit 0 means the same thing, not "delete everything".
        prune_audit_log(&pool, Some(0));
        assert_eq!(audit_labels(&pool), before);
    }

    /// A one-day window must not take today's rows with it: the cutoff is
    /// `now - N days`, so a row written moments ago always survives.
    #[test]
    fn prune_audit_log_one_day_window_spares_todays_rows() {
        let pool = crate::db::open_memory().unwrap();
        seed_audit_row(&pool, "yesterday", 2);
        seed_audit_row(&pool, "now", 0);

        prune_audit_log(&pool, Some(1));

        assert_eq!(audit_labels(&pool), vec!["now"]);
    }

    #[test]
    fn run_backup_prunes_audit_log_only_when_retention_is_configured() {
        let tmp = make_temp_dir();
        let dir = tmp.path();
        let db_path = dir.join("lific.db");
        let backup_dir = make_backup_dir(dir);
        let pool = crate::db::open(&db_path).expect("open test db");
        seed_audit_row(&pool, "ancient", 400);
        seed_audit_row(&pool, "today", 0);

        // Retention off: the backup cycle leaves the audit log alone.
        run_backup(&pool, &db_path, &backup_dir, 5, None);
        assert_eq!(audit_labels(&pool), vec!["ancient", "today"]);

        // Retention on: the same cycle prunes past the window.
        run_backup(&pool, &db_path, &backup_dir, 5, Some(30));
        assert_eq!(audit_labels(&pool), vec!["today"]);
    }
}