cargo-port 0.2.0

A TUI for inspecting and managing Rust projects
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
//! Reads per-project lint state from cache-rooted JSON artifacts.

mod constants;

mod cache_size_index;
mod history;
mod paths;
mod read_write;
mod reclaim;
mod run;
mod runs;
mod runtime;
mod status;
mod trigger;

pub use history::CacheUsage;
pub use history::read_history;
pub use history::retained_cache_usage;
#[cfg(test)]
pub use paths::latest_path_under;
pub use paths::project_dir;
pub(crate) fn reclaim_project_cache(project_root: &Path) {
    reclaim::reclaim_project_cache(project_root);
}

#[cfg(test)]
pub(super) fn reclaim_project_cache_under(cache_root: &Path, project_root: &Path) {
    reclaim::reclaim_project_cache_under(cache_root, project_root);
}
use std::path::Path;

#[cfg(test)]
pub use run::LintCommand;
#[cfg(test)]
pub use run::LintCommandStatus;
pub use run::LintRun;
pub use run::LintRunOrigin;
pub use run::LintRunStatus;
pub use runs::LintRuns;
pub use runtime::RegisterProjectRequest;
pub use runtime::RuntimeHandle;
pub use runtime::project_is_eligible;
pub use runtime::spawn;
pub use status::CachedLintStatus;
pub use status::LintStatus;
pub use status::LintStatusKind;
pub(crate) use status::parse_timestamp;
pub(crate) use trigger::CargoMetadataTriggerKind;
pub(crate) use trigger::classify_cargo_metadata_basename;
pub(crate) use trigger::classify_cargo_metadata_event_path;
pub(crate) use trigger::classify_event_path;

#[cfg(test)]
#[allow(
    clippy::expect_used,
    clippy::unreachable,
    reason = "tests should panic on unexpected values"
)]
mod tests {
    use std::collections::HashMap;
    use std::path::Path;
    use std::sync::Arc;
    use std::sync::Mutex;
    use std::time::Duration;
    use std::time::SystemTime;

    use chrono::DateTime;
    use chrono::FixedOffset;
    use chrono::Utc;

    use super::history;
    use super::history::PruneStats;
    use super::paths;
    use super::read_write;
    use super::run::LintCommand;
    use super::run::LintCommandStatus;
    use super::runtime;
    use super::runtime::RunFinalizeGuard;
    use super::status;
    use super::*;
    use crate::cache_paths;
    use crate::channel;
    use crate::config::DiscoveryLint;
    use crate::constants::LINTS_CACHE_DIR;

    fn run(status: LintRunStatus) -> LintRun {
        LintRun {
            run_id: "run-1".to_string(),
            started_at: "2026-03-30T14:22:01-05:00".to_string(),
            finished_at: Some("2026-03-30T14:22:18-05:00".to_string()),
            duration_ms: Some(17_000),
            status,
            commands: Vec::new(),
            archive_bytes: 0,
        }
    }

    // ── parse_run ───────────────────────────────────────────────────

    #[test]
    fn parse_run_cases() {
        let mut running = run(LintRunStatus::Running);
        running.started_at = Utc::now().format("%+").to_string();
        running.finished_at = None;

        let mut stale = run(LintRunStatus::Running);
        stale.started_at = "2020-01-01T00:00:00+00:00".to_string();
        stale.finished_at = None;

        let mut garbage = run(LintRunStatus::Passed);
        garbage.started_at = "not a valid timestamp".to_string();
        garbage.finished_at = Some("not a valid timestamp".to_string());

        let mut empty = run(LintRunStatus::Passed);
        empty.started_at.clear();
        empty.finished_at = None;

        let cases = [
            ("passed", run(LintRunStatus::Passed)),
            ("failed", run(LintRunStatus::Failed)),
            ("running", running),
            ("stale", stale),
            ("garbage", garbage),
            ("empty", empty),
        ];

        for (name, run) in cases {
            let status = status::parse_run(&run);
            match name {
                "passed" => assert!(matches!(status, LintStatus::Passed(_)), "{name}"),
                "failed" => assert!(matches!(status, LintStatus::Failed(_)), "{name}"),
                "running" => assert!(matches!(status, LintStatus::Running(_)), "{name}"),
                "stale" => assert!(matches!(status, LintStatus::Stale), "{name}"),
                "garbage" | "empty" => assert!(matches!(status, LintStatus::NoLog), "{name}"),
                _ => unreachable!("unexpected case"),
            }
        }
    }

    #[test]
    fn aggregate_prefers_highest_severity() {
        let ts = DateTime::parse_from_rfc3339("2026-03-30T14:22:18-05:00").expect("timestamp");
        let status = LintStatus::aggregate([
            LintStatus::Passed(ts),
            LintStatus::Stale,
            LintStatus::Running(ts),
            LintStatus::Failed(ts),
        ]);
        assert!(matches!(status, LintStatus::Failed(_)));
    }

    #[test]
    fn aggregate_keeps_latest_timestamp_within_variant() {
        let older = DateTime::parse_from_rfc3339("2026-03-30T14:22:18-05:00").expect("older");
        let newer = DateTime::parse_from_rfc3339("2026-03-30T15:22:18-05:00").expect("newer");
        let status = LintStatus::aggregate([LintStatus::Passed(older), LintStatus::Passed(newer)]);
        assert_eq!(status, LintStatus::Passed(newer));
    }

    // ── read_status (end-to-end) ────────────────────────────────────

    fn write_latest(cache_root: &Path, project_root: &Path, run: &LintRun) {
        read_write::write_latest_under(cache_root, project_root, run).expect("write latest");
    }

    #[test]
    fn read_status_reads_latest_and_reports_missing_log() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let dir = tempfile::tempdir().expect("tempdir");
        write_latest(cache_dir.path(), dir.path(), &run(LintRunStatus::Passed));
        assert!(matches!(
            status::read_status_under(cache_dir.path(), dir.path()),
            LintStatus::Passed(_)
        ));

        let missing = tempfile::tempdir().expect("tempdir");
        assert!(matches!(
            status::read_status_under(cache_dir.path(), missing.path()),
            LintStatus::NoLog
        ));
    }

    #[test]
    fn read_status_uses_latest_over_history() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let dir = tempfile::tempdir().expect("tempdir");
        history::append_history_under(
            cache_dir.path(),
            dir.path(),
            &run(LintRunStatus::Failed),
            None,
        )
        .expect("append history");
        write_latest(cache_dir.path(), dir.path(), &run(LintRunStatus::Passed));
        assert!(
            matches!(
                status::read_status_under(cache_dir.path(), dir.path()),
                LintStatus::Passed(_)
            ),
            "should read latest.json, not older history"
        );
    }

    #[test]
    fn cache_latest_path_does_not_live_under_project_dir() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let dir = tempfile::tempdir().expect("tempdir");
        let path = latest_path_under(cache_dir.path(), dir.path());
        assert!(
            !path.starts_with(dir.path()),
            "cache latest path should not recreate project directories"
        );
    }

    #[test]
    #[should_panic(expected = "tests must write lint artifacts under a temp cache root")]
    fn test_lint_writes_reject_default_user_cache_root() {
        let project_dir = tempfile::tempdir().expect("tempdir");
        let default_lint_root = cache_paths::default_app_cache_root().join(LINTS_CACHE_DIR);

        read_write::write_latest_under(
            default_lint_root.as_path(),
            project_dir.path(),
            &run(LintRunStatus::Passed),
        )
        .expect("guard should panic before write_latest returns");
    }

    #[test]
    fn history_reads_newest_first_and_excludes_running_records() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        let completed = LintRun {
            run_id:        "completed".to_string(),
            started_at:    "2026-04-01T18:00:00-04:00".to_string(),
            finished_at:   Some("2026-04-01T18:00:10-04:00".to_string()),
            duration_ms:   Some(10_000),
            status:        LintRunStatus::Passed,
            commands:      Vec::new(),
            archive_bytes: 0,
        };
        let running = LintRun {
            run_id:        "running".to_string(),
            started_at:    "2026-04-01T18:05:00-04:00".to_string(),
            finished_at:   None,
            duration_ms:   None,
            status:        LintRunStatus::Running,
            commands:      Vec::new(),
            archive_bytes: 0,
        };

        history::append_history_under(cache_dir.path(), project_dir.path(), &completed, None)
            .expect("append history");
        history::append_history_under(cache_dir.path(), project_dir.path(), &running, None)
            .expect("append running history");
        read_write::write_latest_under(cache_dir.path(), project_dir.path(), &running)
            .expect("write latest");

        let runs = history::read_history_under(cache_dir.path(), project_dir.path());
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].run_id, "completed");
    }

    #[test]
    fn clear_latest_if_running_removes_running_latest() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        let running = LintRun {
            run_id:        "running".to_string(),
            started_at:    Utc::now().format("%+").to_string(),
            finished_at:   None,
            duration_ms:   None,
            status:        LintRunStatus::Running,
            commands:      Vec::new(),
            archive_bytes: 0,
        };
        read_write::write_latest_under(cache_dir.path(), project_dir.path(), &running)
            .expect("write latest");

        let cleared =
            read_write::clear_latest_if_running_under(cache_dir.path(), project_dir.path())
                .expect("clear");

        assert!(cleared);
        assert!(!latest_path_under(cache_dir.path(), project_dir.path()).exists());
    }

    #[test]
    fn hydration_clears_stranded_running_and_falls_back_to_history() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        history::append_history_under(
            cache_dir.path(),
            project_dir.path(),
            &run(LintRunStatus::Failed),
            None,
        )
        .expect("append history");
        read_write::write_latest_under(
            cache_dir.path(),
            project_dir.path(),
            &run(LintRunStatus::Running),
        )
        .expect("write latest");

        let status = runtime::read_status_from_disk(cache_dir.path(), project_dir.path());

        assert!(
            matches!(status, CachedLintStatus::Failed(_)),
            "history fallback"
        );
        assert!(
            !latest_path_under(cache_dir.path(), project_dir.path()).exists(),
            "a dead app's running marker should be cleared from disk on hydration"
        );
    }

    #[test]
    fn run_finalize_guard_clears_only_unfinished_running() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        read_write::write_latest_under(
            cache_dir.path(),
            project_dir.path(),
            &run(LintRunStatus::Running),
        )
        .expect("write running");
        let status_cache = Arc::new(Mutex::new(HashMap::new()));
        let (background_tx, _background_rx) = channel::unbounded();
        drop(RunFinalizeGuard {
            cache_root:    cache_dir.path(),
            project_root:  project_dir.path(),
            status_cache:  &status_cache,
            background_tx: &background_tx,
            origin:        LintRunOrigin::Normal,
        });
        assert!(
            !latest_path_under(cache_dir.path(), project_dir.path()).exists(),
            "an interrupted running marker should be cleared when the guard drops"
        );

        read_write::write_latest_under(
            cache_dir.path(),
            project_dir.path(),
            &run(LintRunStatus::Passed),
        )
        .expect("write passed");
        drop(RunFinalizeGuard {
            cache_root:    cache_dir.path(),
            project_root:  project_dir.path(),
            status_cache:  &status_cache,
            background_tx: &background_tx,
            origin:        LintRunOrigin::Normal,
        });
        assert!(
            latest_path_under(cache_dir.path(), project_dir.path()).exists(),
            "a completed marker should survive the guard"
        );
    }

    #[test]
    fn latest_final_run_does_not_duplicate_completed_history() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        let completed = LintRun {
            run_id:        "same-run".to_string(),
            started_at:    "2026-04-01T18:00:00-04:00".to_string(),
            finished_at:   Some("2026-04-01T18:00:10-04:00".to_string()),
            duration_ms:   Some(10_000),
            status:        LintRunStatus::Passed,
            commands:      Vec::new(),
            archive_bytes: 0,
        };

        history::append_history_under(cache_dir.path(), project_dir.path(), &completed, None)
            .expect("append history");
        read_write::write_latest_under(cache_dir.path(), project_dir.path(), &completed)
            .expect("write latest");

        let runs = history::read_history_under(cache_dir.path(), project_dir.path());
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].run_id, "same-run");
    }

    #[test]
    fn retained_cache_usage_counts_latest_and_history_bytes() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        let completed = run(LintRunStatus::Passed);

        read_write::write_latest_under(cache_dir.path(), project_dir.path(), &completed)
            .expect("write latest");
        history::append_history_under(cache_dir.path(), project_dir.path(), &completed, None)
            .expect("append history");

        let usage = history::retained_cache_usage_under(cache_dir.path(), Some(1024));
        assert!(usage.bytes > 0);
        assert_eq!(usage.cache_size_bytes, Some(1024));
    }

    // ── run archival ────────────────────────────────────────────────

    fn run_with_commands(run_id: &str, started_at: &str) -> LintRun {
        LintRun {
            run_id:        run_id.to_string(),
            started_at:    started_at.to_string(),
            finished_at:   Some(started_at.to_string()),
            duration_ms:   Some(5_000),
            status:        LintRunStatus::Passed,
            commands:      vec![
                LintCommand {
                    name:        "clippy".to_string(),
                    command:     "cargo clippy".to_string(),
                    status:      LintCommandStatus::Passed,
                    duration_ms: Some(3_000),
                    exit_code:   Some(0),
                    log_file:    "clippy-latest.log".to_string(),
                },
                LintCommand {
                    name:        "mend".to_string(),
                    command:     "cargo mend".to_string(),
                    status:      LintCommandStatus::Passed,
                    duration_ms: Some(2_000),
                    exit_code:   Some(0),
                    log_file:    "mend-latest.log".to_string(),
                },
            ],
            archive_bytes: 0,
        }
    }

    fn write_fake_logs(cache_root: &Path, project_root: &Path, content: &str) {
        let output_dir = paths::output_dir_under(cache_root, project_root);
        std::fs::create_dir_all(&output_dir).expect("create output dir");
        std::fs::write(
            output_dir.join("clippy-latest.log"),
            format!("clippy: {content}\n"),
        )
        .expect("write clippy log");
        std::fs::write(
            output_dir.join("mend-latest.log"),
            format!("mend: {content}\n"),
        )
        .expect("write mend log");
    }

    fn archive_run_with_logs(
        cache_root: &Path,
        project_root: &Path,
        run_id: &str,
        started_at: &str,
        content: &str,
    ) -> LintRun {
        let run = run_with_commands(run_id, started_at);
        write_fake_logs(cache_root, project_root, content);
        history::archive_run_output(cache_root, project_root, &run).expect("archive run")
    }

    fn append_archived_run(
        cache_root: &Path,
        project_root: &Path,
        run: &LintRun,
        cache_size: Option<u64>,
    ) -> PruneStats {
        history::append_history_under(cache_root, project_root, run, cache_size)
            .expect("append run")
    }

    #[test]
    fn archive_run_copies_logs_to_run_id_directory() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        let completed = run_with_commands("run-abc", "2026-04-04T10:00:00-04:00");

        write_fake_logs(cache_dir.path(), project_dir.path(), "test output");
        let archived =
            history::archive_run_output(cache_dir.path(), project_dir.path(), &completed)
                .expect("archive");

        // Archived run should have updated log_file paths pointing at runs/{run_id}/
        assert_eq!(archived.commands.len(), 2);
        assert_eq!(archived.commands[0].log_file, "runs/run-abc/clippy.log");
        assert_eq!(archived.commands[1].log_file, "runs/run-abc/mend.log");

        // Archived files should exist on disk
        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        let run_dir = project_cache.join("runs/run-abc");
        assert!(run_dir.join("clippy.log").exists());
        assert!(run_dir.join("mend.log").exists());

        // Content should match originals
        let clippy_content = std::fs::read_to_string(run_dir.join("clippy.log")).expect("read");
        assert_eq!(clippy_content, "clippy: test output\n");

        // The archived run carries the total bytes of its copied logs, summed
        // once at archive time so reading history never walks the directory.
        let clippy_bytes = std::fs::metadata(run_dir.join("clippy.log"))
            .expect("clippy meta")
            .len();
        let mend_bytes = std::fs::metadata(run_dir.join("mend.log"))
            .expect("mend meta")
            .len();
        assert!(clippy_bytes > 0 && mend_bytes > 0);
        assert_eq!(archived.archive_bytes, clippy_bytes + mend_bytes);

        // Latest logs should still exist (convenience copies)
        let output_dir = paths::output_dir_under(cache_dir.path(), project_dir.path());
        assert!(output_dir.join("clippy-latest.log").exists());
        assert!(output_dir.join("mend-latest.log").exists());
    }

    #[test]
    fn archive_run_with_missing_logs_still_succeeds() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");
        let completed = run_with_commands("run-missing", "2026-04-04T10:00:00-04:00");

        // Don't write any log files — archive should still succeed gracefully
        let archived =
            history::archive_run_output(cache_dir.path(), project_dir.path(), &completed)
                .expect("archive");

        // Paths updated even if files don't exist
        assert_eq!(archived.commands[0].log_file, "runs/run-missing/clippy.log");

        // No archived file on disk (nothing to copy)
        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        let run_dir = project_cache.join("runs/run-missing");
        assert!(!run_dir.join("clippy.log").exists());

        // Nothing copied, so the persisted archive size is zero.
        assert_eq!(archived.archive_bytes, 0);
    }

    // ── run-based pruning ──────────────────────────────────────────

    #[test]
    fn prune_removes_oldest_run_directory_and_history_line() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        let older = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-older",
            "2026-04-01T18:00:00-04:00",
            "older output with padding to exceed batch size",
        );
        append_archived_run(cache_dir.path(), project_dir.path(), &older, None);

        let newer = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-newer",
            "2026-04-01T19:00:00-04:00",
            "newer output with padding to exceed batch size",
        );

        // Measure total bytes with both runs fully on disk. The cache size must be
        // small enough that keeping both exceeds it, but large enough that the
        // newer run alone fits. We subtract the older run's archived log bytes
        // to create that pressure.
        let total_before_append = history::total_bytes_under(cache_dir.path());
        let newer_line_bytes = serde_json::to_string(&newer).expect("serialize").len() as u64 + 1;
        let cache_size = total_before_append + newer_line_bytes - 1;

        append_archived_run(
            cache_dir.path(),
            project_dir.path(),
            &newer,
            Some(cache_size),
        );

        // Only newer run should remain in history
        let runs = history::read_history_under(cache_dir.path(), project_dir.path());
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].run_id, "run-newer");

        // Older run's archived directory should be deleted
        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        assert!(
            !project_cache.join("runs/run-older").exists(),
            "older run directory should be pruned"
        );

        // Newer run's archived directory should still exist
        assert!(
            project_cache.join("runs/run-newer").exists(),
            "newer run directory should survive"
        );
    }

    #[test]
    fn prune_across_projects_removes_globally_oldest() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_a = tempfile::tempdir().expect("tempdir");
        let project_b = tempfile::tempdir().expect("tempdir");

        let old_a = archive_run_with_logs(
            cache_dir.path(),
            project_a.path(),
            "run-old-a",
            "2026-04-01T17:00:00-04:00",
            "project-a output with padding to exceed batch size",
        );
        append_archived_run(cache_dir.path(), project_a.path(), &old_a, None);

        let new_b = archive_run_with_logs(
            cache_dir.path(),
            project_b.path(),
            "run-new-b",
            "2026-04-01T20:00:00-04:00",
            "project-b output with padding to exceed batch size",
        );

        // Budget: total with both archived + room for B's history line, minus 1
        // byte so the pruner must delete A's run to fit.
        let total_before_append = history::total_bytes_under(cache_dir.path());
        let new_b_line_bytes = serde_json::to_string(&new_b).expect("serialize").len() as u64 + 1;
        let cache_size = total_before_append + new_b_line_bytes - 1;

        append_archived_run(cache_dir.path(), project_b.path(), &new_b, Some(cache_size));

        // Project A's older run should be pruned
        let runs_a = history::read_history_under(cache_dir.path(), project_a.path());
        assert!(runs_a.is_empty(), "older project A run should be pruned");

        // Project B's newer run should survive
        let runs_b = history::read_history_under(cache_dir.path(), project_b.path());
        assert_eq!(runs_b.len(), 1);
        assert_eq!(runs_b[0].run_id, "run-new-b");

        // Project A's archived directory should be deleted
        let cache_a = paths::project_dir_under(cache_dir.path(), project_a.path());
        assert!(
            !cache_a.join("runs/run-old-a").exists(),
            "pruned run directory should be deleted"
        );
    }

    #[test]
    fn prune_no_op_when_under_cache_size() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        let completed = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-keep",
            "2026-04-01T18:00:00-04:00",
            "keep this output",
        );

        // Generous cache size — nothing should be pruned
        append_archived_run(
            cache_dir.path(),
            project_dir.path(),
            &completed,
            Some(10 * 1024 * 1024),
        );

        let runs = history::read_history_under(cache_dir.path(), project_dir.path());
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].run_id, "run-keep");

        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        assert!(project_cache.join("runs/run-keep").exists());
    }

    #[test]
    fn prune_returns_stats_about_evicted_runs() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        let older = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-older",
            "2026-04-01T18:00:00-04:00",
            "older output with padding to exceed batch size",
        );
        append_archived_run(cache_dir.path(), project_dir.path(), &older, None);

        let newer = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-newer",
            "2026-04-01T19:00:00-04:00",
            "newer output with padding to exceed batch size",
        );

        let total_before = history::total_bytes_under(cache_dir.path());
        let newer_line = serde_json::to_string(&newer).expect("serialize").len() as u64 + 1;
        let cache_size = total_before + newer_line - 1;

        let stats = append_archived_run(
            cache_dir.path(),
            project_dir.path(),
            &newer,
            Some(cache_size),
        );

        assert_eq!(stats.runs_evicted, 1);
        assert!(stats.bytes_reclaimed > 0);
    }

    #[test]
    fn prune_protects_just_appended_run_even_when_larger_than_cache() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        let older = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-older",
            "2026-04-01T18:00:00-04:00",
            "older output",
        );
        append_archived_run(cache_dir.path(), project_dir.path(), &older, None);

        // Newer run whose archived logs alone far exceed the cache budget.
        let huge_content = "x".repeat(10_000);
        let newer = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-newer",
            "2026-04-01T19:00:00-04:00",
            &huge_content,
        );

        // Tiny cache forces eviction; even wiping the older run cannot get
        // below cache_size because the newer run alone is far larger. The
        // newer run should survive because it was just appended.
        let stats = append_archived_run(cache_dir.path(), project_dir.path(), &newer, Some(500));

        let runs = history::read_history_under(cache_dir.path(), project_dir.path());
        assert_eq!(runs.len(), 1);
        assert_eq!(runs[0].run_id, "run-newer");

        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        assert!(
            project_cache.join("runs/run-newer").exists(),
            "just-appended run directory should survive"
        );
        assert!(
            !project_cache.join("runs/run-older").exists(),
            "older run directory should be evicted"
        );
        assert_eq!(stats.runs_evicted, 1);
    }

    #[test]
    fn no_prune_returns_zero_stats() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        let completed = archive_run_with_logs(
            cache_dir.path(),
            project_dir.path(),
            "run-keep",
            "2026-04-01T18:00:00-04:00",
            "keep this",
        );

        let stats = append_archived_run(
            cache_dir.path(),
            project_dir.path(),
            &completed,
            Some(10 * 1024 * 1024),
        );

        assert_eq!(stats.runs_evicted, 0);
        assert_eq!(stats.bytes_reclaimed, 0);
    }

    #[test]
    fn no_cache_size_returns_zero_stats() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        let completed = run_with_commands("run-unlimited", "2026-04-01T18:00:00-04:00");

        let stats =
            history::append_history_under(cache_dir.path(), project_dir.path(), &completed, None)
                .expect("append");

        assert_eq!(stats.runs_evicted, 0);
        assert_eq!(stats.bytes_reclaimed, 0);
    }

    // ── reclaim_project_cache ───────────────────────────────────────

    #[test]
    fn reclaim_project_cache_removes_existing_directory() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        history::append_history_under(
            cache_dir.path(),
            project_dir.path(),
            &run(LintRunStatus::Passed),
            None,
        )
        .expect("append history");
        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        assert!(
            project_cache.as_path().is_dir(),
            "project cache directory must exist before reclamation",
        );

        super::reclaim_project_cache_under(cache_dir.path(), project_dir.path());

        assert!(
            !project_cache.as_path().exists(),
            "project cache directory must be removed after reclamation",
        );
        assert!(
            cache_dir.path().is_dir(),
            "cache root must survive — only the per-project subdir is reclaimed",
        );
    }

    #[test]
    fn reclaim_project_cache_is_noop_when_directory_missing() {
        let cache_dir = tempfile::tempdir().expect("tempdir");
        let project_dir = tempfile::tempdir().expect("tempdir");

        // No history written — the per-project directory was never
        // created. Reclamation must not panic and must not disturb
        // the cache root.
        super::reclaim_project_cache_under(cache_dir.path(), project_dir.path());

        assert!(cache_dir.path().is_dir());
        let project_cache = paths::project_dir_under(cache_dir.path(), project_dir.path());
        assert!(!project_cache.as_path().exists());
    }

    // ── should_lint_on_startup ──────────────────────────────────────

    #[test]
    fn should_lint_on_startup_gates_nolog_by_discovery_and_relints_stale_terminal() {
        // NoLog (never linted) is the discovery case — gated by config, and
        // independent of any source mtime.
        assert!(CachedLintStatus::NoLog.should_lint_on_startup(
            None,
            None,
            DiscoveryLint::Immediate
        ));
        assert!(!CachedLintStatus::NoLog.should_lint_on_startup(
            None,
            None,
            DiscoveryLint::Deferred
        ));

        // A terminal result re-lints only when a source mtime post-dates the run
        // start, regardless of discovery config.
        let started: DateTime<FixedOffset> =
            DateTime::parse_from_rfc3339("2026-03-30T14:22:01-05:00").expect("parse start");
        let run_epoch = SystemTime::UNIX_EPOCH
            + Duration::from_secs(u64::try_from(started.timestamp()).expect("non-negative epoch"));
        let passed = CachedLintStatus::Passed(started);

        assert!(passed.should_lint_on_startup(
            Some(started),
            Some(run_epoch + Duration::from_secs(5)),
            DiscoveryLint::Deferred,
        ));
        assert!(!passed.should_lint_on_startup(
            Some(started),
            Some(run_epoch - Duration::from_secs(5)),
            DiscoveryLint::Deferred,
        ));
        // Same whole second is not "newer" — the second-granularity guard.
        assert!(!passed.should_lint_on_startup(
            Some(started),
            Some(run_epoch),
            DiscoveryLint::Immediate,
        ));
        // No source mtime collected → a terminal result cannot be stale.
        assert!(!passed.should_lint_on_startup(Some(started), None, DiscoveryLint::Immediate));
    }
}