travelagent-core 1.10.3

Core library for travelagent code review tool
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
use directories::ProjectDirs;
use std::cell::RefCell;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use crate::config::SessionGcConfig;
use crate::error::{Result, TrvError};
use crate::model::ReviewSession;
use crate::model::review::{SESSION_VERSION, SessionDiffSource};
const SESSION_FILENAME_DELIMITER: &str = "--";
/// Expected component count when splitting a v2 session filename stem on the
/// delimiter: `{name}--{hex8}--{branch}--{diff_source}--{YYYYMMDD_HHMMSS}--{id}`.
const SESSION_FILENAME_PART_COUNT: usize = 6;
const SESSION_FILENAME_DATE_LEN: usize = 8;
const SESSION_FILENAME_TIME_LEN: usize = 6;
const FINGERPRINT_HEX_LEN: usize = 8;

struct SessionFilenameParts {
    repo_fingerprints: Vec<String>,
    diff_source: String,
}

/// Parse a session filename.
///
/// The canonical format uses `--` (double-dash) as the major delimiter so that
/// `diff_source` and any other component may safely contain single underscores
/// (e.g. `staged_and_unstaged`). Returns `None` for filenames that do not
/// conform to the current format — callers can treat this as "unknown
/// provenance" and decide whether to include the file when filtering.
fn parse_session_filename(filename: &str) -> Option<SessionFilenameParts> {
    let stem = filename.strip_suffix(".json")?;
    let parts: Vec<&str> = stem.split(SESSION_FILENAME_DELIMITER).collect();

    if parts.len() != SESSION_FILENAME_PART_COUNT {
        return None;
    }

    let repo_fingerprint = parts[1];
    let diff_source = parts[3];
    let date_part = parts[4].get(..SESSION_FILENAME_DATE_LEN)?;
    let time_part = parts[4].get(SESSION_FILENAME_DATE_LEN + 1..)?;

    if !matches!(
        diff_source,
        "worktree"
            | "staged"
            | "unstaged"
            | "staged_and_unstaged"
            | "commits"
            | "worktree_and_commits"
            | "staged_unstaged_and_commits"
            | "remote"
    ) {
        return None;
    }

    // Timestamp layout is `YYYYMMDD_HHMMSS`.
    if parts[4].len() != SESSION_FILENAME_DATE_LEN + 1 + SESSION_FILENAME_TIME_LEN
        || parts[4].as_bytes().get(SESSION_FILENAME_DATE_LEN) != Some(&b'_')
        || !is_timestamp_part(date_part, SESSION_FILENAME_DATE_LEN)
        || !is_timestamp_part(time_part, SESSION_FILENAME_TIME_LEN)
    {
        return None;
    }

    if !is_hex_fingerprint(repo_fingerprint) {
        return None;
    }

    Some(SessionFilenameParts {
        repo_fingerprints: vec![repo_fingerprint.to_string()],
        diff_source: diff_source.to_string(),
    })
}

fn is_timestamp_part(part: &str, len: usize) -> bool {
    part.len() == len && part.chars().all(|ch| ch.is_ascii_digit())
}

fn is_hex_fingerprint(part: &str) -> bool {
    part.len() == FINGERPRINT_HEX_LEN && part.chars().all(|ch| ch.is_ascii_hexdigit())
}

thread_local! {
    /// Per-thread override for [`get_reviews_dir`]. Tests use
    /// [`with_reviews_dir_override`] instead of mutating `std::env`, which would
    /// be `unsafe` and racy under Rust 2024's tightened env-var model.
    static REVIEWS_DIR_OVERRIDE: RefCell<Option<PathBuf>> = const { RefCell::new(None) };
}

/// Run `f` with `dir` installed as the thread-local reviews directory.
///
/// Compiled into test builds (via `cfg(test)`) and into the
/// `test-support` feature so integration tests in sibling crates can
/// redirect the reviews directory without spawning a fresh process. The
/// override is thread-local to avoid cross-test interference.
#[cfg(any(test, feature = "test-support"))]
pub fn set_reviews_dir_override(dir: PathBuf) {
    REVIEWS_DIR_OVERRIDE.with(|cell| {
        *cell.borrow_mut() = Some(dir);
    });
}

#[cfg(any(test, feature = "test-support"))]
pub fn clear_reviews_dir_override() {
    REVIEWS_DIR_OVERRIDE.with(|cell| {
        *cell.borrow_mut() = None;
    });
}

fn get_reviews_dir() -> Result<PathBuf> {
    if let Some(override_dir) = REVIEWS_DIR_OVERRIDE.with(|cell| cell.borrow().clone()) {
        fs::create_dir_all(&override_dir)?;
        return Ok(override_dir);
    }

    let proj_dirs = ProjectDirs::from("", "", "travelagent")
        .ok_or_else(|| TrvError::Io(std::io::Error::other("Could not determine data directory")))?;

    let data_dir = proj_dirs.data_dir().join("reviews");
    fs::create_dir_all(&data_dir)?;
    Ok(data_dir)
}

const MAX_FILENAME_COMPONENT_LEN: usize = 64;

fn sanitize_filename_component(value: &str) -> String {
    let mut sanitized = String::with_capacity(value.len().min(MAX_FILENAME_COMPONENT_LEN));
    for ch in value.chars() {
        if sanitized.len() >= MAX_FILENAME_COMPONENT_LEN {
            break;
        }
        let ok = ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.');
        sanitized.push(if ok { ch } else { '-' });
    }

    let sanitized = sanitized.trim_matches('-');
    if sanitized.is_empty() {
        "unknown".to_string()
    } else {
        sanitized.to_string()
    }
}

fn fnv1a_64(bytes: &[u8]) -> u64 {
    const OFFSET_BASIS: u64 = 0xcbf29ce484222325;
    const PRIME: u64 = 0x100000001b3;

    let mut hash = OFFSET_BASIS;
    for byte in bytes {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(PRIME);
    }
    hash
}

fn repo_path_fingerprint(repo_path: &Path) -> String {
    let normalized = normalize_repo_path(repo_path);
    let hash = fnv1a_64(normalized.as_bytes());
    let hex = format!("{hash:016x}");
    hex[..FINGERPRINT_HEX_LEN].to_string()
}

fn normalize_repo_path(repo_path: &Path) -> String {
    let canonical = fs::canonicalize(repo_path).unwrap_or_else(|_| repo_path.to_path_buf());
    let normalized = canonical.to_string_lossy().to_string();

    if cfg!(windows) {
        normalized.to_lowercase()
    } else {
        normalized
    }
}

fn diff_source_slug(diff_source: SessionDiffSource) -> &'static str {
    match diff_source {
        SessionDiffSource::WorkingTree => "worktree",
        SessionDiffSource::Staged => "staged",
        SessionDiffSource::Unstaged => "unstaged",
        SessionDiffSource::StagedAndUnstaged => "staged_and_unstaged",
        SessionDiffSource::CommitRange => "commits",
        SessionDiffSource::WorkingTreeAndCommits => "worktree_and_commits",
        SessionDiffSource::StagedUnstagedAndCommits => "staged_unstaged_and_commits",
        SessionDiffSource::Remote => "remote",
    }
}

fn session_filename(session: &ReviewSession) -> String {
    let repo_name = session
        .repo_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unknown");

    let repo_name = sanitize_filename_component(repo_name);
    let repo_fingerprint = repo_path_fingerprint(&session.repo_path);

    let branch = session.branch_name.as_deref().unwrap_or("detached");
    let branch = sanitize_filename_component(branch);

    let diff_source = diff_source_slug(session.diff_source);

    let timestamp = session.created_at.format("%Y%m%d_%H%M%S");
    let id_fragment = session.id.split('-').next().unwrap_or(&session.id);

    format!(
        "{repo_name}{SESSION_FILENAME_DELIMITER}{repo_fingerprint}{SESSION_FILENAME_DELIMITER}{branch}{SESSION_FILENAME_DELIMITER}{diff_source}{SESSION_FILENAME_DELIMITER}{timestamp}{SESSION_FILENAME_DELIMITER}{id_fragment}.json",
    )
}

pub fn save_session(session: &ReviewSession) -> Result<PathBuf> {
    let reviews_dir = get_reviews_dir()?;
    let filename = session_filename(session);
    let path = reviews_dir.join(&filename);

    // Write atomically: emit the serialized JSON to `<target>.tmp` on the
    // same directory, then `fs::rename` it into place. Rename is atomic on
    // the same filesystem on POSIX and on modern Windows NTFS, so a crash
    // mid-write leaves either the old contents or the full new contents —
    // never a half-written file.
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let tmp_path = {
        let mut p = path.clone().into_os_string();
        p.push(".tmp");
        PathBuf::from(p)
    };

    // Compact JSON (Phase B): pretty-printing was ~30% overhead on large
    // sessions. Sessions are machine-written / machine-read only; the
    // `--debug-session` escape hatch (pending) exposes pretty output
    // when needed. The single-line JSON still round-trips losslessly.
    let json = save_session_to_string(session)?;
    fs::write(&tmp_path, json)?;
    if let Err(err) = fs::rename(&tmp_path, &path) {
        // Best-effort cleanup so a failed rename does not leave stray
        // `<target>.tmp` files littering the reviews directory.
        let _ = fs::remove_file(&tmp_path);
        return Err(err.into());
    }

    Ok(path)
}

/// Serialize a session to its on-disk JSON form without touching the
/// filesystem. Symmetric counterpart to [`load_session_from_str`]; exists
/// so property/fuzz tests can round-trip through the serde boundary.
pub fn save_session_to_string(session: &ReviewSession) -> Result<String> {
    Ok(serde_json::to_string(session)?)
}

pub fn load_session(path: &PathBuf) -> Result<ReviewSession> {
    let contents = fs::read_to_string(path)?;
    load_session_from_str(&contents)
}

/// Parse a session body from JSON without touching the filesystem. Runs
/// the same version check + tour / legacy-marker migrations as
/// [`load_session`]. Exists so property/fuzz tests can drive the loader
/// with arbitrary inputs.
///
/// Invariant under test: every input either returns `Err(TrvError)` or
/// `Ok(ReviewSession)` with zero panics — malformed JSON, unsupported
/// version strings, and future-versioned tours all flow through
/// `TrvError::CorruptedSession` with a caller-facing message.
pub fn load_session_from_str(contents: &str) -> Result<ReviewSession> {
    let mut session: ReviewSession =
        serde_json::from_str(contents).map_err(|e| TrvError::CorruptedSession(e.to_string()))?;

    // Refuse to load sessions written by a newer schema. Parse both versions
    // as dotted numeric tuples so "1.10" correctly compares as newer than
    // "1.2"; malformed versions are treated as incompatible and rejected.
    let file_version = parse_version(&session.version).ok_or_else(|| {
        TrvError::CorruptedSession(format!(
            "session version {} is not a valid dotted numeric version",
            session.version
        ))
    })?;
    let supported_version = parse_version(SESSION_VERSION)
        .expect("SESSION_VERSION constant must be a valid dotted numeric version");
    if file_version > supported_version {
        return Err(TrvError::CorruptedSession(format!(
            "session version {} is newer than supported {}",
            session.version, SESSION_VERSION
        )));
    }

    // Roll the tour forward through any pending schema migrations (H11).
    // Independent of `SESSION_VERSION` so a tour-shape change doesn't
    // force a whole-session version bump. A future-versioned tour is
    // treated as a corrupted session so the user sees the same refusal
    // they'd get for a newer `SESSION_VERSION` — don't silently interpret
    // unknown shape.
    if let Some(tour) = session.tour.as_mut() {
        crate::model::tour::migrate_tour(tour)
            .map_err(|e| TrvError::CorruptedSession(e.to_string()))?;
    }

    // Migrate 1.3-era agent comments. The legacy marker is idempotent so
    // running this on a 1.4-native session is a no-op: only bodies that
    // still end with the exact marker are rewritten.
    migrate_legacy_mcp_markers_in_place(&mut session);

    Ok(session)
}

/// Strip the legacy `\n\n_(via MCP agent)_` suffix from every comment in
/// `session` and promote `author_kind` to `McpAgent`. Idempotent.
fn migrate_legacy_mcp_markers_in_place(session: &mut ReviewSession) {
    use crate::model::comment::migrate_legacy_mcp_author_marker;
    for comment in session.review_comments.iter_mut() {
        migrate_legacy_mcp_author_marker(comment);
    }
    for file in session.files.values_mut() {
        for comment in file.file_comments.iter_mut() {
            migrate_legacy_mcp_author_marker(comment);
        }
        for comments in file.line_comments.values_mut() {
            for comment in comments.iter_mut() {
                migrate_legacy_mcp_author_marker(comment);
            }
        }
        for comment in file.orphaned_comments.iter_mut() {
            migrate_legacy_mcp_author_marker(comment);
        }
    }
}

/// Parse a dotted numeric version string like `"1.10"` into a vector of u32
/// components that can be compared numerically. Returns `None` for empty
/// strings or any component that fails to parse as `u32`.
fn parse_version(s: &str) -> Option<Vec<u32>> {
    if s.is_empty() {
        return None;
    }
    s.split('.').map(|part| part.parse::<u32>().ok()).collect()
}

/// Summary of a single GC pass over the reviews directory. Zero-valued
/// counters mean "that bound didn't trigger" rather than "the scan failed";
/// `scanned` is the total number of `.json` entries inspected before any
/// deletions.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GcReport {
    pub scanned: usize,
    pub removed_age: usize,
    pub removed_size: usize,
    pub removed_count: usize,
    pub remaining_files: usize,
    pub remaining_bytes: u64,
}

impl GcReport {
    pub fn total_removed(&self) -> usize {
        self.removed_age + self.removed_size + self.removed_count
    }
}

/// Run session GC against a specific directory with the given config. Used
/// by the transparent per-load purge (age-only defaults) and by
/// `run_session_gc` (all three bounds). `dry_run` counts what would be
/// removed without mutating the filesystem.
///
/// Errors during deletion or metadata inspection are logged but never
/// abort the scan; clock skew (mtime in the future) is ignored so a
/// freshly-written file is not accidentally purged.
fn purge_sessions(reviews_dir: &Path, cfg: &SessionGcConfig, dry_run: bool) -> GcReport {
    let mut report = GcReport::default();

    let Ok(read_dir) = fs::read_dir(reviews_dir) else {
        return report;
    };

    struct Entry {
        path: PathBuf,
        modified: SystemTime,
        size: u64,
    }

    let mut entries: Vec<Entry> = Vec::new();
    for entry in read_dir.flatten() {
        let path = entry.path();
        if !path
            .extension()
            .and_then(|ext| ext.to_str())
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
        {
            continue;
        }

        let metadata = match entry.metadata() {
            Ok(m) => m,
            Err(err) => {
                eprintln!(
                    "travelagent: failed to stat {} during session GC: {err}",
                    path.display()
                );
                continue;
            }
        };
        let modified = match metadata.modified() {
            Ok(t) => t,
            Err(err) => {
                eprintln!(
                    "travelagent: failed to read mtime for {} during session GC: {err}",
                    path.display()
                );
                continue;
            }
        };
        entries.push(Entry {
            path,
            modified,
            size: metadata.len(),
        });
    }
    report.scanned = entries.len();

    let remove = |path: &Path| -> bool {
        if dry_run {
            return true;
        }
        match fs::remove_file(path) {
            Ok(()) => true,
            Err(err) => {
                eprintln!(
                    "travelagent: failed to remove session {}: {err}",
                    path.display()
                );
                false
            }
        }
    };

    if cfg.max_age_days > 0 {
        // saturating_mul mirrors the size-pass cap below; prevents silent
        // wrap on pathological user values from producing a tiny max_age
        // that would evict everything.
        let max_age = Duration::from_secs(cfg.max_age_days.saturating_mul(24 * 60 * 60));
        let now = SystemTime::now();
        entries.retain(|e| match now.duration_since(e.modified) {
            Ok(age) if age > max_age => {
                if remove(&e.path) {
                    report.removed_age += 1;
                    false
                } else {
                    // Couldn't delete; keep it so downstream bounds still
                    // reason about it accurately.
                    true
                }
            }
            // Fresh file or clock-skewed mtime in the future. Leave it alone.
            Ok(_) | Err(_) => true,
        });
    }

    // Oldest first for subsequent size / count passes so we evict the least-
    // recently-used files.
    entries.sort_by_key(|e| e.modified);

    if cfg.max_size_mb > 0 {
        let cap = cfg.max_size_mb.saturating_mul(1024 * 1024);
        let mut total: u64 = entries.iter().map(|e| e.size).sum();
        let mut kept = Vec::with_capacity(entries.len());
        for entry in entries {
            if total > cap {
                let size = entry.size;
                if remove(&entry.path) {
                    report.removed_size += 1;
                    total = total.saturating_sub(size);
                    continue;
                }
                // Delete failed: subtract the size anyway so the next
                // iteration's `total > cap` check reflects the files we can
                // actually evict, not ghosts we can't. Keep the entry in
                // `kept` so the count pass still sees it.
                total = total.saturating_sub(size);
            }
            kept.push(entry);
        }
        entries = kept;
    }

    if cfg.max_count > 0 {
        // `max_count` keeps the newest N — entries are currently oldest
        // first, so drop from the front.
        let cap = cfg.max_count as usize;
        if entries.len() > cap {
            let drop_n = entries.len() - cap;
            let mut kept = Vec::with_capacity(cap);
            for (i, entry) in entries.into_iter().enumerate() {
                if i < drop_n && remove(&entry.path) {
                    report.removed_count += 1;
                    continue;
                }
                kept.push(entry);
            }
            entries = kept;
        }
    }

    report.remaining_files = entries.len();
    report.remaining_bytes = entries.iter().map(|e| e.size).sum();
    report
}

/// Public entry point for explicit `trv --session-gc` invocations. Returns
/// the full [`GcReport`] so the caller can print a human-readable summary.
pub fn run_session_gc(cfg: &SessionGcConfig, dry_run: bool) -> Result<GcReport> {
    let reviews_dir = get_reviews_dir()?;
    Ok(purge_sessions(&reviews_dir, cfg, dry_run))
}

pub fn load_latest_session_for_context(
    repo_path: &Path,
    branch_name: Option<&str>,
    head_commit: &str,
    diff_source: SessionDiffSource,
    commit_range: Option<&[String]>,
) -> Result<Option<(PathBuf, ReviewSession)>> {
    let current_repo_path = normalize_repo_path(repo_path);
    let current_fingerprint = repo_path_fingerprint(repo_path);
    let current_diff_source = diff_source_slug(diff_source);

    let reviews_dir = get_reviews_dir()?;
    // Transparent startup GC uses SessionGcConfig defaults (age-only,
    // preserving historical behaviour). Explicit `trv --session-gc`
    // runs go through `run_session_gc` with the effective config.
    let _ = purge_sessions(&reviews_dir, &SessionGcConfig::default(), false);

    // Collect `(path, mtime)` pairs once so the subsequent sort does not re-stat
    // every entry. Files that survive the filename filter but whose metadata we
    // cannot read fall back to `UNIX_EPOCH` — they sort last and will be tried
    // only if nothing else matches.
    let mut session_files: Vec<(PathBuf, SystemTime)> = fs::read_dir(&reviews_dir)?
        .filter_map(std::result::Result::ok)
        .filter_map(|entry| {
            let path = entry.path();

            if !path
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
            {
                return None;
            }

            let filename = path.file_name().and_then(|f| f.to_str())?;

            if let Some(parts) = parse_session_filename(filename) {
                if !parts
                    .repo_fingerprints
                    .iter()
                    .any(|fingerprint| fingerprint == &current_fingerprint)
                {
                    return None;
                }

                if parts.diff_source != current_diff_source {
                    return None;
                }
            }
            // Filenames that do not parse (e.g. legacy single-dash files) are
            // kept and fully verified by loading their JSON below.

            let modified = entry
                .metadata()
                .and_then(|m| m.modified())
                .unwrap_or(SystemTime::UNIX_EPOCH);
            Some((path, modified))
        })
        .collect();

    // Newest first; tiebreak on path so results are deterministic when two
    // files share an mtime (common on coarse-grained filesystems).
    session_files.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    let mut legacy_candidate = None;

    for (path, _modified) in session_files {
        let Ok(session) = load_session(&path) else {
            continue;
        };

        if normalize_repo_path(&session.repo_path) != current_repo_path {
            continue;
        }

        if session.diff_source != diff_source {
            continue;
        }

        if matches!(
            diff_source,
            SessionDiffSource::CommitRange
                | SessionDiffSource::WorkingTreeAndCommits
                | SessionDiffSource::StagedUnstagedAndCommits
        ) && let Some(expected_range) = commit_range
            && session.commit_range.as_deref() != Some(expected_range)
        {
            continue;
        }

        let session_branch = session.branch_name.as_deref();
        if session_branch == branch_name {
            if branch_name.is_none() && session.base_commit != head_commit {
                continue;
            }

            // Files are iterated newest-first, so the first full match is the
            // winner and we can stop parsing the rest of the directory.
            return Ok(Some((path, session)));
        }

        let eligible_legacy = branch_name.is_some()
            && legacy_candidate.is_none()
            && commit_range.is_none()
            && session_branch.is_none()
            && session.base_commit == head_commit;
        if eligible_legacy {
            legacy_candidate = Some((path, session));
        }
    }

    Ok(legacy_candidate)
}

#[cfg(test)]
fn delete_session(path: &PathBuf) -> Result<()> {
    fs::remove_file(path)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::FileStatus;
    use std::path::PathBuf;
    use std::time::Duration;

    const TEST_MTIME_RETRIES: usize = 40;
    const TEST_MTIME_SLEEP_MS: u64 = 100;

    fn create_test_session() -> ReviewSession {
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);
        session
    }

    /// RAII guard that installs a fresh per-test reviews directory on the
    /// current thread and wipes it on drop. Tests run on separate threads
    /// under `cargo test`, so the thread-local override gives us isolation
    /// without the `unsafe` env-var mutation the previous implementation
    /// relied on.
    struct TestReviewsDirGuard {
        path: PathBuf,
    }

    impl TestReviewsDirGuard {
        fn new() -> Self {
            let path =
                std::env::temp_dir().join(format!("trv-reviews-test-{}", uuid::Uuid::new_v4()));
            fs::create_dir_all(&path).unwrap();
            set_reviews_dir_override(path.clone());
            Self { path }
        }
    }

    impl Drop for TestReviewsDirGuard {
        fn drop(&mut self) {
            clear_reviews_dir_override();
            let _ = fs::remove_dir_all(&self.path);
        }
    }

    fn with_test_reviews_dir() -> TestReviewsDirGuard {
        TestReviewsDirGuard::new()
    }

    fn create_session(
        repo_path: PathBuf,
        base_commit: &str,
        branch_name: Option<&str>,
        diff_source: SessionDiffSource,
        commit_range: Option<Vec<String>>,
    ) -> ReviewSession {
        let mut session = ReviewSession::new(
            repo_path,
            base_commit.to_string(),
            branch_name.map(std::string::ToString::to_string),
            diff_source,
        );
        session.commit_range = commit_range;
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);
        session
    }

    fn save_legacy_session(reviews_dir: &Path, session: &ReviewSession) -> PathBuf {
        let mut value = serde_json::to_value(session).unwrap();
        let obj = value.as_object_mut().unwrap();
        obj.remove("branch_name");
        obj.remove("diff_source");
        obj.remove("commit_range");
        obj.insert(
            "version".to_string(),
            serde_json::Value::String("1.0".to_string()),
        );

        let id_fragment = session.id.split('-').next().unwrap_or(&session.id);
        let path = reviews_dir.join(format!("legacy_{id_fragment}.json"));
        fs::write(&path, serde_json::to_string_pretty(&value).unwrap()).unwrap();
        path
    }

    fn ensure_newer_mtime(newer: &Path, older: &Path) {
        let older_time = fs::metadata(older)
            .ok()
            .and_then(|m| m.modified().ok())
            .unwrap_or(std::time::SystemTime::UNIX_EPOCH);

        for _ in 0..TEST_MTIME_RETRIES {
            let newer_time = fs::metadata(newer)
                .ok()
                .and_then(|m| m.modified().ok())
                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);

            if newer_time > older_time {
                return;
            }

            std::thread::sleep(Duration::from_millis(TEST_MTIME_SLEEP_MS));
            let contents = fs::read_to_string(newer).unwrap();
            fs::write(newer, contents).unwrap();
        }

        let newer_time = fs::metadata(newer)
            .ok()
            .and_then(|m| m.modified().ok())
            .unwrap_or(std::time::SystemTime::UNIX_EPOCH);

        assert!(
            newer_time > older_time,
            "failed to produce newer mtime for {}",
            newer.display()
        );
    }

    #[test]
    fn should_generate_correct_filename() {
        let session = create_test_session();
        let filename = session_filename(&session);
        assert!(filename.starts_with("test-repo--"));
        assert!(filename.contains("--main--worktree--"));
        assert!(filename.ends_with(".json"));
    }

    #[test]
    fn should_generate_filename_for_staged_unstaged() {
        let session = create_session(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def",
            Some("main"),
            SessionDiffSource::StagedAndUnstaged,
            None,
        );
        let filename = session_filename(&session);
        assert!(filename.contains("--staged_and_unstaged--"));
    }

    #[test]
    fn should_roundtrip_session() {
        let _guard = with_test_reviews_dir();
        let session = create_test_session();
        let path = save_session(&session).unwrap();
        let loaded = load_session(&path).unwrap();
        assert_eq!(session.id, loaded.id);
        assert_eq!(session.base_commit, loaded.base_commit);
        assert_eq!(session.branch_name, loaded.branch_name);
        assert_eq!(session.diff_source, loaded.diff_source);
        assert_eq!(session.files.len(), loaded.files.len());
        let _ = delete_session(&path);
    }

    #[test]
    fn should_sanitize_branch_name_in_filename() {
        let session = create_session(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def",
            Some("feature/login"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let filename = session_filename(&session);
        assert!(!filename.contains('/'));
        assert!(filename.contains("feature-login"));
    }

    #[test]
    fn should_select_latest_session_for_branch() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let session1 = create_session(
            repo_path.clone(),
            "commit-1",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let path1 = save_session(&session1).unwrap();

        let session2 = create_session(
            repo_path.clone(),
            "commit-2",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let path2 = save_session(&session2).unwrap();
        ensure_newer_mtime(&path2, &path1);
        let (selected_path, selected) = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "head-does-not-matter-for-branch",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap()
        .unwrap();
        assert_eq!(selected_path, path2);
        assert_ne!(selected_path, path1);
        assert_eq!(selected.base_commit, "commit-2");
    }

    #[test]
    fn should_match_branch_even_when_head_commit_differs() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let session = create_session(
            repo_path.clone(),
            "old-head",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let _ = save_session(&session).unwrap();
        let loaded = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "new-head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        assert!(loaded.is_some());
    }

    #[test]
    fn should_load_session_with_underscore_branch_name() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let session = create_session(
            repo_path.clone(),
            "head-commit",
            Some("feature/with_underscores"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let _ = save_session(&session).unwrap();
        let loaded = load_latest_session_for_context(
            &repo_path,
            Some("feature/with_underscores"),
            "new-head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        assert!(loaded.is_some());
    }

    #[test]
    fn should_load_session_with_hex_like_branch_segment() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let session = create_session(
            repo_path.clone(),
            "head-commit",
            Some("feature/deadbeef_fix"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let _ = save_session(&session).unwrap();
        let loaded = load_latest_session_for_context(
            &repo_path,
            Some("feature/deadbeef_fix"),
            "new-head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        assert!(loaded.is_some());
    }

    #[test]
    fn should_prefer_branch_match_over_legacy_candidate() {
        let guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let branch_session = create_session(
            repo_path.clone(),
            "branch-base",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let branch_path = save_session(&branch_session).unwrap();

        let legacy_source = create_session(
            repo_path.clone(),
            "head-commit",
            None,
            SessionDiffSource::WorkingTree,
            None,
        );
        let legacy_path = save_legacy_session(&guard.path, &legacy_source);
        let (selected_path, _selected) = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "head-commit",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap()
        .unwrap();
        assert_eq!(selected_path, branch_path);
        assert_ne!(selected_path, legacy_path);
    }

    #[test]
    fn should_fallback_to_legacy_session_when_no_branch_session_exists() {
        let guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let legacy_source = create_session(
            repo_path.clone(),
            "head-commit",
            None,
            SessionDiffSource::WorkingTree,
            None,
        );
        let legacy_path = save_legacy_session(&guard.path, &legacy_source);
        let (selected_path, selected) = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "head-commit",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap()
        .unwrap();
        assert_eq!(selected_path, legacy_path);
        assert_eq!(selected.branch_name, None);
        assert_eq!(selected.diff_source, SessionDiffSource::WorkingTree);
    }

    #[test]
    fn should_not_select_legacy_session_when_head_commit_differs() {
        let guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let legacy_source = create_session(
            repo_path.clone(),
            "old-head",
            None,
            SessionDiffSource::WorkingTree,
            None,
        );
        let _legacy_path = save_legacy_session(&guard.path, &legacy_source);
        let loaded = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "new-head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn should_require_commit_match_in_detached_head() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let session = create_session(
            repo_path.clone(),
            "detached-head",
            None,
            SessionDiffSource::WorkingTree,
            None,
        );
        let _ = save_session(&session).unwrap();
        let mismatch = load_latest_session_for_context(
            &repo_path,
            None,
            "different-head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        let match_ = load_latest_session_for_context(
            &repo_path,
            None,
            "detached-head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        assert!(mismatch.is_none());
        assert!(match_.is_some());
    }

    #[test]
    fn should_ignore_sessions_with_different_diff_source() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let commit_range = vec!["commit-2".to_string(), "commit-1".to_string()];
        let commits_session = create_session(
            repo_path.clone(),
            "commit-2",
            Some("main"),
            SessionDiffSource::CommitRange,
            Some(commit_range.clone()),
        );
        let _ = save_session(&commits_session).unwrap();
        let worktree = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap();
        let commits = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "head",
            SessionDiffSource::CommitRange,
            Some(commit_range.as_slice()),
        )
        .unwrap();
        assert!(worktree.is_none());
        assert!(commits.is_some());
    }

    #[test]
    fn should_match_commit_range_session() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let commit_range_a = vec!["commit-a2".to_string(), "commit-a1".to_string()];
        let commit_range_b = vec!["commit-b2".to_string(), "commit-b1".to_string()];

        let session_a = create_session(
            repo_path.clone(),
            "commit-a2",
            Some("main"),
            SessionDiffSource::CommitRange,
            Some(commit_range_a.clone()),
        );
        let path_a = save_session(&session_a).unwrap();

        let session_b = create_session(
            repo_path.clone(),
            "commit-b2",
            Some("main"),
            SessionDiffSource::CommitRange,
            Some(commit_range_b.clone()),
        );
        let path_b = save_session(&session_b).unwrap();
        let (selected_path, selected) = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "commit-b2",
            SessionDiffSource::CommitRange,
            Some(commit_range_b.as_slice()),
        )
        .unwrap()
        .unwrap();
        assert_eq!(selected_path, path_b);
        assert_ne!(selected_path, path_a);
        assert_eq!(
            selected.commit_range.as_deref(),
            Some(commit_range_b.as_slice())
        );
    }

    #[test]
    fn should_roundtrip_commit_range_session() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let commit_range = vec!["commit-2".to_string(), "commit-1".to_string()];
        let session = create_session(
            repo_path,
            "commit-2",
            Some("main"),
            SessionDiffSource::CommitRange,
            Some(commit_range.clone()),
        );
        let path = save_session(&session).unwrap();
        let loaded = load_session(&path).unwrap();
        assert_eq!(loaded.commit_range, Some(commit_range));
        assert_eq!(loaded.diff_source, SessionDiffSource::CommitRange);
        let _ = delete_session(&path);
    }

    #[test]
    fn should_require_commit_range_order_match() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let commit_range = vec!["commit-2".to_string(), "commit-1".to_string()];
        let reversed_range = vec!["commit-1".to_string(), "commit-2".to_string()];

        let session = create_session(
            repo_path.clone(),
            "commit-2",
            Some("main"),
            SessionDiffSource::CommitRange,
            Some(commit_range),
        );
        let _ = save_session(&session).unwrap();
        let loaded = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "commit-2",
            SessionDiffSource::CommitRange,
            Some(reversed_range.as_slice()),
        )
        .unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn should_skip_commit_sessions_without_range_match() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let commit_range = vec!["commit-2".to_string(), "commit-1".to_string()];

        let session = create_session(
            repo_path.clone(),
            "commit-2",
            Some("main"),
            SessionDiffSource::CommitRange,
            None,
        );
        let _ = save_session(&session).unwrap();
        let loaded = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "commit-2",
            SessionDiffSource::CommitRange,
            Some(commit_range.as_slice()),
        )
        .unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn should_load_legacy_session_without_tour_fields() {
        let guard = with_test_reviews_dir();
        let session = create_test_session();
        let path = save_legacy_session(&guard.path, &session);
        let loaded = load_session(&path).unwrap();
        assert!(loaded.tour.is_none());
        assert!(loaded.tour_comment_meta.is_empty());
        assert!(loaded.tour_triage.is_empty());
    }

    #[test]
    fn should_roundtrip_session_with_tour_state() {
        use crate::model::tour::{
            CommentTriage, NewCommentLocation, TourCommentMeta, TourState, TourStop,
            TourTriageVerdict,
        };
        let _guard = with_test_reviews_dir();
        let mut session = create_test_session();
        session.tour = Some(TourState {
            stops: vec![
                TourStop {
                    commit_ids: vec!["abc".into()],
                    summary: "first commit".into(),
                    risk: crate::risk::RiskScore::MIN,
                },
                TourStop {
                    commit_ids: vec!["def".into(), "ghi".into()],
                    summary: "batched".into(),
                    risk: crate::risk::RiskScore::MIN,
                },
            ],
            index: 1,
            threshold: crate::risk::RiskScore::MIN,
            tour_schema_version: crate::model::tour::TOUR_SCHEMA_VERSION,
        });
        session.tour_comment_meta.insert(
            "cid-1".to_string(),
            TourCommentMeta {
                stop_index: 0,
                stop_commit_shas: vec!["abc".into()],
                file: "src/a.rs".into(),
                line: 42,
            },
        );
        session.tour_triage.insert(
            "cid-1".to_string(),
            CommentTriage {
                verdict: TourTriageVerdict::Moved,
                reasoning: "renamed".into(),
                new_location: Some(NewCommentLocation {
                    file: "src/a2.rs".into(),
                    line: 50,
                }),
            },
        );

        let path = save_session(&session).unwrap();
        let loaded = load_session(&path).unwrap();
        assert_eq!(loaded.tour.as_ref().unwrap().index, 1);
        assert_eq!(loaded.tour.as_ref().unwrap().stops.len(), 2);
        assert_eq!(loaded.tour_comment_meta.len(), 1);
        let meta = loaded.tour_comment_meta.get("cid-1").unwrap();
        assert_eq!(meta.file, "src/a.rs");
        assert_eq!(meta.line, 42);
        let triage = loaded.tour_triage.get("cid-1").unwrap();
        assert_eq!(triage.verdict, TourTriageVerdict::Moved);
        assert_eq!(triage.new_location.as_ref().unwrap().line, 50);
        let _ = delete_session(&path);
    }

    #[test]
    fn load_session_migrates_legacy_tour_to_current_schema_version() {
        // Regression (H11): a session whose on-disk tour JSON predates
        // the H11 tour_schema_version field must load successfully and
        // have its tour rolled forward via migrate_tour.
        let guard = with_test_reviews_dir();
        let legacy = format!(
            r#"{{
              "id": "abc",
              "version": "{SESSION_VERSION}",
              "repo_path": "/repo",
              "base_commit": "deadbeef",
              "created_at": "2024-01-01T00:00:00Z",
              "updated_at": "2024-01-01T00:00:00Z",
              "files": {{}},
              "tour": {{
                "stops": [{{"commit_ids": ["sha1"], "summary": "first"}}],
                "index": 0
              }}
            }}"#
        );
        let path = guard.path.join("legacy-tour-session.json");
        fs::write(&path, legacy).unwrap();

        let loaded = load_session(&path).expect("legacy tour session loads");
        let tour = loaded.tour.expect("tour preserved");
        assert_eq!(
            tour.tour_schema_version,
            crate::model::tour::TOUR_SCHEMA_VERSION,
            "migrate_tour rolled the legacy v0 tour up to current"
        );
        assert_eq!(tour.stops.len(), 1);
        assert_eq!(tour.stops[0].commit_ids, vec!["sha1".to_string()]);
    }

    #[test]
    fn load_session_migrates_legacy_mcp_author_marker_to_author_kind() {
        // Regression (Phase B): 1.3-era sessions tagged agent-authored
        // comments by appending `\n\n_(via MCP agent)_` to the body. 1.4
        // introduced `AuthorKind`; `load_session` must strip the legacy
        // suffix and promote `author_kind` on load.
        use crate::model::AuthorKind;
        let guard = with_test_reviews_dir();
        let legacy = r#"{
              "id": "abc",
              "version": "1.3",
              "repo_path": "/repo",
              "base_commit": "deadbeef",
              "created_at": "2024-01-01T00:00:00Z",
              "updated_at": "2024-01-01T00:00:00Z",
              "files": {
                "src/foo.rs": {
                  "path": "src/foo.rs",
                  "reviewed": false,
                  "status": "modified",
                  "file_comments": [
                    {
                      "id": "fc1",
                      "content": "plain human file comment",
                      "comment_type": "note",
                      "created_at": "2024-01-01T00:00:00Z",
                      "line_context": null
                    }
                  ],
                  "line_comments": {
                    "10": [
                      {
                        "id": "lc1",
                        "content": "agent said\n\n_(via MCP agent)_",
                        "comment_type": "note",
                        "created_at": "2024-01-01T00:00:00Z",
                        "line_context": null,
                        "side": "new"
                      },
                      {
                        "id": "lc2",
                        "content": "human said",
                        "comment_type": "note",
                        "created_at": "2024-01-01T00:00:00Z",
                        "line_context": null,
                        "side": "new"
                      }
                    ]
                  }
                }
              },
              "review_comments": [
                {
                  "id": "rc1",
                  "content": "agent review comment\n\n_(via MCP agent)_",
                  "comment_type": "note",
                  "created_at": "2024-01-01T00:00:00Z",
                  "line_context": null
                }
              ]
            }"#;
        let path = guard.path.join("legacy-mcp-marker.json");
        fs::write(&path, legacy).unwrap();

        let loaded = load_session(&path).expect("legacy marker session loads");

        // Agent line comment: suffix stripped, kind promoted.
        let file = loaded.files.get(&PathBuf::from("src/foo.rs")).unwrap();
        let line10 = file.line_comments.get(&10).unwrap();
        assert_eq!(line10[0].content, "agent said");
        assert_eq!(line10[0].author_kind, AuthorKind::McpAgent);
        // Human line comment: untouched.
        assert_eq!(line10[1].content, "human said");
        assert_eq!(line10[1].author_kind, AuthorKind::Human);
        // Human file comment: untouched.
        assert_eq!(file.file_comments[0].content, "plain human file comment");
        assert_eq!(file.file_comments[0].author_kind, AuthorKind::Human);
        // Agent review comment: also migrated.
        assert_eq!(loaded.review_comments[0].content, "agent review comment");
        assert_eq!(loaded.review_comments[0].author_kind, AuthorKind::McpAgent);
    }

    #[test]
    fn should_disambiguate_repos_with_same_folder_name() {
        let _guard = with_test_reviews_dir();
        let base = std::env::temp_dir().join(format!("trv-repos-{}", uuid::Uuid::new_v4()));
        let repo_a = base.join("a").join("same-repo");
        let repo_b = base.join("b").join("same-repo");
        fs::create_dir_all(&repo_a).unwrap();
        fs::create_dir_all(&repo_b).unwrap();

        let session_a = create_session(
            repo_a.clone(),
            "head-a",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let _ = save_session(&session_a).unwrap();

        let session_b = create_session(
            repo_b.clone(),
            "head-b",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let _ = save_session(&session_b).unwrap();
        let (_path, selected) = load_latest_session_for_context(
            &repo_a,
            Some("main"),
            "head",
            SessionDiffSource::WorkingTree,
            None,
        )
        .unwrap()
        .unwrap();
        assert_eq!(selected.base_commit, "head-a");
        assert_eq!(
            normalize_repo_path(&selected.repo_path),
            normalize_repo_path(&repo_a)
        );
    }

    // ---- New tests covering the bug fixes ----

    /// C1: every `SessionDiffSource` variant must round-trip through the
    /// filename writer/parser pair. Previously `staged_and_unstaged`,
    /// `worktree_and_commits`, and `staged_unstaged_and_commits` tripped the
    /// parser because it assumed `diff_source` was a single token.
    #[test]
    fn should_roundtrip_filename_for_all_diff_source_variants() {
        let repo_path = PathBuf::from("/tmp/test-repo");
        let commit_range = vec!["c1".to_string(), "c2".to_string()];
        let variants = [
            (SessionDiffSource::WorkingTree, "worktree", None),
            (SessionDiffSource::Staged, "staged", None),
            (SessionDiffSource::Unstaged, "unstaged", None),
            (
                SessionDiffSource::StagedAndUnstaged,
                "staged_and_unstaged",
                None,
            ),
            (
                SessionDiffSource::CommitRange,
                "commits",
                Some(commit_range.clone()),
            ),
            (
                SessionDiffSource::WorkingTreeAndCommits,
                "worktree_and_commits",
                Some(commit_range.clone()),
            ),
            (
                SessionDiffSource::StagedUnstagedAndCommits,
                "staged_unstaged_and_commits",
                Some(commit_range.clone()),
            ),
            (SessionDiffSource::Remote, "remote", None),
        ];

        for (variant, expected_slug, range) in variants {
            let session = create_session(
                repo_path.clone(),
                "base-commit",
                Some("main"),
                variant,
                range,
            );
            let filename = session_filename(&session);

            assert!(
                filename.contains(&format!("--{expected_slug}--")),
                "filename {filename} should contain slug {expected_slug}"
            );

            let parts =
                parse_session_filename(&filename).expect("filename must parse for every variant");
            assert_eq!(
                parts.diff_source, expected_slug,
                "parser drift for {variant:?}"
            );
            assert_eq!(parts.repo_fingerprints.len(), 1);
            assert!(is_hex_fingerprint(&parts.repo_fingerprints[0]));
        }
    }

    /// C1: filter must not crash or silently drop sessions for multi-token
    /// diff sources once the session is round-tripped through disk.
    #[test]
    fn should_filter_multi_token_diff_source_sessions() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        let commit_range = vec!["c1".to_string(), "c2".to_string()];
        let session = create_session(
            repo_path.clone(),
            "c2",
            Some("main"),
            SessionDiffSource::StagedUnstagedAndCommits,
            Some(commit_range.clone()),
        );
        let path = save_session(&session).unwrap();

        let (selected_path, selected) = load_latest_session_for_context(
            &repo_path,
            Some("main"),
            "c2",
            SessionDiffSource::StagedUnstagedAndCommits,
            Some(commit_range.as_slice()),
        )
        .unwrap()
        .unwrap();
        assert_eq!(selected_path, path);
        assert_eq!(
            selected.diff_source,
            SessionDiffSource::StagedUnstagedAndCommits
        );
    }

    /// H3: sessions whose schema version is newer than this binary must be
    /// rejected rather than silently loaded with missing fields.
    #[test]
    fn should_reject_session_with_newer_version() {
        let _guard = with_test_reviews_dir();
        let reviews_dir = get_reviews_dir().unwrap();

        let session = create_test_session();
        let mut value = serde_json::to_value(&session).unwrap();
        value["version"] = serde_json::Value::String("9.9".to_string());
        let path = reviews_dir.join("newer-version.json");
        fs::write(&path, serde_json::to_string_pretty(&value).unwrap()).unwrap();

        let err = load_session(&path).unwrap_err();
        match err {
            TrvError::CorruptedSession(msg) => {
                assert!(
                    msg.contains("9.9"),
                    "error message should mention version: {msg}"
                );
                assert!(
                    msg.contains(SESSION_VERSION),
                    "error message should mention supported version"
                );
            }
            other => panic!("expected CorruptedSession, got {other:?}"),
        }
    }

    /// H3: sessions at or below the supported version must still load.
    #[test]
    fn should_accept_session_with_current_version() {
        let _guard = with_test_reviews_dir();
        let session = create_test_session();
        let path = save_session(&session).unwrap();
        let loaded = load_session(&path).unwrap();
        assert_eq!(loaded.version, SESSION_VERSION);
    }

    /// Version comparison must be numeric, not lexicographic: `"1.10"` is
    /// newer than `"1.2"`.
    #[test]
    fn should_compare_versions_numerically_not_lexicographically() {
        let v1_10 = parse_version("1.10").expect("1.10 must parse");
        let v1_2 = parse_version("1.2").expect("1.2 must parse");
        assert!(v1_10 > v1_2, "1.10 must sort newer than 1.2 numerically");
    }

    /// Sanity check that a larger major beats a large minor.
    #[test]
    fn should_treat_major_version_bumps_as_newer() {
        let v2_0 = parse_version("2.0").expect("2.0 must parse");
        let v1_99 = parse_version("1.99").expect("1.99 must parse");
        assert!(v2_0 > v1_99, "2.0 must sort newer than 1.99");
    }

    /// Malformed version strings are rejected rather than silently accepted.
    #[test]
    fn should_reject_malformed_version() {
        assert!(parse_version("").is_none());
        assert!(parse_version("1.x").is_none());
        assert!(parse_version("abc").is_none());
        assert!(parse_version("1..2").is_none());
    }

    /// Equal versions must be accepted by `load_session`.
    #[test]
    fn should_accept_session_with_equal_version() {
        let _guard = with_test_reviews_dir();
        let reviews_dir = get_reviews_dir().unwrap();

        let session = create_test_session();
        let mut value = serde_json::to_value(&session).unwrap();
        value["version"] = serde_json::Value::String(SESSION_VERSION.to_string());
        let path = reviews_dir.join("equal-version.json");
        fs::write(&path, serde_json::to_string_pretty(&value).unwrap()).unwrap();

        let loaded = load_session(&path).expect("equal version must load");
        assert_eq!(loaded.version, SESSION_VERSION);
    }

    /// `load_session` must reject `"1.10"` as newer than `"1.2"` / `"1.0"`
    /// (whichever the current SESSION_VERSION is) when numerics say so.
    #[test]
    fn should_reject_newer_version_by_numeric_comparison() {
        let _guard = with_test_reviews_dir();
        let reviews_dir = get_reviews_dir().unwrap();

        // Build a version that is guaranteed numerically newer than the
        // current SESSION_VERSION regardless of what that value is today.
        let current = parse_version(SESSION_VERSION).unwrap();
        let newer_major = current[0] + 1;
        let newer = format!("{newer_major}.0");

        let session = create_test_session();
        let mut value = serde_json::to_value(&session).unwrap();
        value["version"] = serde_json::Value::String(newer.clone());
        let path = reviews_dir.join("numerically-newer.json");
        fs::write(&path, serde_json::to_string_pretty(&value).unwrap()).unwrap();

        let err = load_session(&path).unwrap_err();
        match err {
            TrvError::CorruptedSession(msg) => {
                assert!(
                    msg.contains(&newer),
                    "message should mention version: {msg}"
                );
            }
            other => panic!("expected CorruptedSession, got {other:?}"),
        }
    }

    /// `save_session` must produce a file whose contents equal the most
    /// recent save — not an append or a half-written intermediate. This
    /// guards the atomic-rename path in `save_session`.
    #[test]
    fn should_overwrite_session_file_atomically_on_resave() {
        let _guard = with_test_reviews_dir();
        let repo_path = std::env::temp_dir().join(format!("trv-repo-{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&repo_path).unwrap();

        // First save: branch `main`, one file.
        let session1 = create_session(
            repo_path.clone(),
            "base-1",
            Some("main"),
            SessionDiffSource::WorkingTree,
            None,
        );
        let path1 = save_session(&session1).unwrap();

        // Second save with the same id (and therefore same filename) but a
        // distinct payload, so we can prove the file reflects the second
        // write in full rather than a concatenation or truncated remnant.
        let mut session2 = session1.clone();
        session2.base_commit = "base-2".to_string();
        session2.add_file(PathBuf::from("src/other.rs"), FileStatus::Added);

        let path2 = save_session(&session2).unwrap();
        assert_eq!(
            path1, path2,
            "save path must be stable for a session with stable id"
        );

        // File must be valid JSON (not garbled) and must match session2.
        let loaded = load_session(&path2).expect("resaved file must be valid JSON");
        assert_eq!(loaded.base_commit, "base-2");
        assert_eq!(
            loaded.files.len(),
            2,
            "second save must be the full payload, not appended"
        );

        // No leftover `.tmp` sidecar should remain in the reviews dir.
        let reviews_dir = get_reviews_dir().unwrap();
        for entry in fs::read_dir(&reviews_dir).unwrap().flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            assert!(
                !name_str.ends_with(".tmp"),
                "stale tmp file left behind: {name_str}"
            );
        }
    }

    /// `load_session` must reject sessions whose `version` field is not a
    /// valid dotted numeric string.
    #[test]
    fn should_reject_session_with_malformed_version() {
        let _guard = with_test_reviews_dir();
        let reviews_dir = get_reviews_dir().unwrap();

        let session = create_test_session();
        let mut value = serde_json::to_value(&session).unwrap();
        value["version"] = serde_json::Value::String("not-a-version".to_string());
        let path = reviews_dir.join("malformed-version.json");
        fs::write(&path, serde_json::to_string_pretty(&value).unwrap()).unwrap();

        let err = load_session(&path).unwrap_err();
        match err {
            TrvError::CorruptedSession(msg) => {
                assert!(
                    msg.contains("not-a-version"),
                    "message should mention version: {msg}"
                );
            }
            other => panic!("expected CorruptedSession, got {other:?}"),
        }
    }

    /// H2: the thread-local override must route writes without touching the
    /// process-wide environment. We assert the env var stays untouched.
    #[test]
    fn should_use_thread_local_override_without_env_var() {
        let key = "TRV_REVIEWS_DIR";
        let before = std::env::var_os(key);

        let _guard = with_test_reviews_dir();
        let session = create_test_session();
        let saved = save_session(&session).unwrap();
        assert!(
            saved.exists(),
            "session should be written under thread-local override"
        );

        let after = std::env::var_os(key);
        assert_eq!(before, after, "tests must not mutate TRV_REVIEWS_DIR");
    }

    /// H2: resolved paths should match the override directory exactly.
    #[test]
    fn should_resolve_reviews_dir_from_thread_local_override() {
        let guard = with_test_reviews_dir();
        let resolved = get_reviews_dir().unwrap();
        assert_eq!(resolved, guard.path);
    }

    /// H2: clearing the override must fall back to the default production path.
    /// We only assert that the override is no longer honored (the real path may
    /// legitimately vary by platform / user profile).
    #[test]
    fn should_clear_override_on_guard_drop() {
        let temp = {
            let guard = with_test_reviews_dir();
            let path = get_reviews_dir().unwrap();
            assert_eq!(path, guard.path);
            guard.path.clone()
        };
        // After drop the override should be gone: resolving again should not
        // return the (now-deleted) temp directory.
        let resolved = get_reviews_dir().unwrap();
        assert_ne!(resolved, temp, "override must be cleared after guard drop");
    }

    // ---- Phase G: session GC (age / size / count bounds) ----

    /// Write `content` to a session file under `dir` and stamp its mtime
    /// `age_days` days in the past so the age pass sees it as stale.
    fn write_aged_session(dir: &Path, name: &str, content: &str, age_days: u64) -> PathBuf {
        let path = dir.join(name);
        fs::write(&path, content).unwrap();
        let age = Duration::from_secs(age_days * 24 * 60 * 60);
        let modified = std::time::SystemTime::now()
            .checked_sub(age)
            .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
        let ft = filetime::FileTime::from_system_time(modified);
        filetime::set_file_mtime(&path, ft).unwrap();
        path
    }

    #[test]
    fn gc_age_eviction_preserves_historical_behavior() {
        // Regression guard: the default SessionGcConfig (7-day age, no
        // size / count cap) must evict files older than 7 days and leave
        // fresher files alone — matching pre-Phase-G behaviour.
        let guard = with_test_reviews_dir();
        let stale = write_aged_session(&guard.path, "stale.json", "{}", 30);
        let fresh = write_aged_session(&guard.path, "fresh.json", "{}", 1);

        let report = purge_sessions(&guard.path, &SessionGcConfig::default(), false);
        assert_eq!(report.removed_age, 1);
        assert_eq!(report.removed_size, 0);
        assert_eq!(report.removed_count, 0);
        assert_eq!(report.remaining_files, 1);
        assert!(!stale.exists(), "30-day-old file should be purged");
        assert!(fresh.exists(), "1-day-old file should be preserved");
    }

    #[test]
    fn gc_size_cap_evicts_oldest_first() {
        let guard = with_test_reviews_dir();
        // 1 MB-ish bodies so the size cap is easy to reason about.
        let body = "x".repeat(1024 * 1024);
        let oldest = write_aged_session(&guard.path, "oldest.json", &body, 2);
        let middle = write_aged_session(&guard.path, "middle.json", &body, 1);
        let newest = write_aged_session(&guard.path, "newest.json", &body, 0);

        let cfg = SessionGcConfig {
            max_age_days: 0,
            max_size_mb: 2,
            max_count: 0,
        };
        let report = purge_sessions(&guard.path, &cfg, false);
        assert_eq!(report.removed_age, 0);
        assert!(
            report.removed_size >= 1,
            "size cap must evict at least one file"
        );
        assert!(!oldest.exists(), "oldest file should be evicted first");
        assert!(middle.exists(), "middle file should survive a 2 MB cap");
        assert!(newest.exists(), "newest file should always survive");
    }

    #[test]
    fn gc_count_cap_keeps_newest_n() {
        let guard = with_test_reviews_dir();
        let f1 = write_aged_session(&guard.path, "f1.json", "{}", 5);
        let f2 = write_aged_session(&guard.path, "f2.json", "{}", 4);
        let f3 = write_aged_session(&guard.path, "f3.json", "{}", 3);
        let f4 = write_aged_session(&guard.path, "f4.json", "{}", 2);

        let cfg = SessionGcConfig {
            max_age_days: 0,
            max_size_mb: 0,
            max_count: 2,
        };
        let report = purge_sessions(&guard.path, &cfg, false);
        assert_eq!(report.removed_count, 2);
        assert_eq!(report.remaining_files, 2);
        assert!(!f1.exists(), "oldest pruned");
        assert!(!f2.exists(), "second oldest pruned");
        assert!(f3.exists(), "second newest kept");
        assert!(f4.exists(), "newest kept");
    }

    #[test]
    fn gc_dry_run_reports_without_deleting() {
        let guard = with_test_reviews_dir();
        let stale = write_aged_session(&guard.path, "stale.json", "{}", 30);
        let fresh = write_aged_session(&guard.path, "fresh.json", "{}", 1);

        let report = purge_sessions(&guard.path, &SessionGcConfig::default(), true);
        assert_eq!(report.removed_age, 1);
        assert!(stale.exists(), "dry run must not delete the stale file");
        assert!(fresh.exists());
    }

    #[test]
    fn gc_zero_means_unbounded_for_each_cap() {
        // All three caps set to 0 => full no-op (scanned only, nothing removed).
        let guard = with_test_reviews_dir();
        let f1 = write_aged_session(&guard.path, "a.json", "{}", 365);
        let f2 = write_aged_session(&guard.path, "b.json", "{}", 365);

        let cfg = SessionGcConfig {
            max_age_days: 0,
            max_size_mb: 0,
            max_count: 0,
        };
        let report = purge_sessions(&guard.path, &cfg, false);
        assert_eq!(report.scanned, 2);
        assert_eq!(report.removed_age, 0);
        assert_eq!(report.removed_size, 0);
        assert_eq!(report.removed_count, 0);
        assert!(f1.exists());
        assert!(f2.exists());
    }

    #[test]
    fn gc_config_round_trips_through_toml() {
        let toml_src = r#"
[session_gc]
max_age_days = 14
max_size_mb = 100
max_count = 50
"#;
        let cfg: SessionGcConfig = toml::from_str::<toml::Table>(toml_src)
            .unwrap()
            .get("session_gc")
            .unwrap()
            .clone()
            .try_into()
            .unwrap();
        assert_eq!(cfg.max_age_days, 14);
        assert_eq!(cfg.max_size_mb, 100);
        assert_eq!(cfg.max_count, 50);

        // Defaults: empty section preserves historical (age-only, 7-day) behaviour.
        let empty: SessionGcConfig = toml::from_str("").unwrap();
        assert_eq!(empty, SessionGcConfig::default());
        assert_eq!(empty.max_age_days, 7);
        assert_eq!(empty.max_size_mb, 0);
        assert_eq!(empty.max_count, 0);
    }
}