session-summary 0.1.0

CLI tool for summarizing and restoring Claude Code sessions
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
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
//! Session Summary CLI
//!
//! Restores bounded working context from a Claude Code session transcript:
//! finds sessions on disk (`list`) and prints a digest of verbatim quotes from
//! the tail of a chosen session (`load`). The digest is never an agent-written
//! summary — every line comes straight from the transcript: user prompts,
//! assistant text, tool calls with their key argument, and system errors.
//!
//! # Bounded, not schema-strict
//!
//! The Claude Code transcript format keeps growing new root event types and
//! new field shapes on existing ones. This parser treats that as normal: an
//! unrecognized root type is skipped silently (never a parse failure for the
//! rest of the line's siblings — see [`claude_session_types::events::SessionEvent::Unknown`]),
//! and a handful of known fields (`message.content`, `toolUseResult`) accept
//! more than one wire shape rather than dropping the whole event.
//!
//! # Reads are byte-budgeted, not full-file scans
//!
//! Both `list` and `load` read a bounded window from the end of the file
//! (`read_tail_lines`) with a single seek plus one read — cost is
//! proportional to the window, not to file size, so a multi-gigabyte
//! transcript loads in well under a second. Session titles can lag behind a
//! large tail window on a very bursty session, so title detection falls back
//! to a small bounded read from the *start* of the file (`read_head_lines`)
//! when the tail window doesn't carry one.
//!
//! # Topic selection
//!
//! In priority order: the session's own `custom-title` (Claude Code's UI
//! title), then `ai-title` (model-generated), then `last-prompt` (latest
//! verbatim human prompt), then the first genuine human-typed prompt in the
//! session (skipping harness-injected meta turns, command-palette
//! injections, and tool-result-only turns) — never a generic placeholder
//! unless none of the above exist at all.

#![allow(clippy::too_many_lines)]
#![allow(clippy::cast_possible_wrap)]
#![allow(clippy::cast_precision_loss)]

use anyhow::{Context, Result};
use chrono::{DateTime, Local, Utc};
use clap::{Parser, Subcommand};
use claude_session_types::events::{ProgressData, SessionEvent, UserTurnKind};
use colored::Colorize;
use regex::Regex;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashSet;
use std::fmt;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;

/// JSON report schema tag for `list --json`.
const SCHEMA_LIST: &str = "claude-session-restore-list-v1";
/// JSON report schema tag for `load --json`.
const SCHEMA_LOAD: &str = "claude-session-restore-load-v1";

/// Tail byte budget for `load` — generous, since a full digest is worth
/// reading more context for.
const LOAD_TAIL_BYTES: u64 = 32 * 1024 * 1024;
/// Tail byte budget per session for `list`'s preview — small, since only a
/// handful of recent items are shown per session and up to `--limit` sessions
/// are scanned per invocation.
const LIST_TAIL_BYTES: u64 = 4 * 1024 * 1024;
/// Head byte budget used by the title/first-prompt fallback scan, for both
/// commands.
const HEAD_FALLBACK_BYTES: u64 = 1024 * 1024;

/// Per-vector item cap for `load`'s digest.
const LOAD_MAX_ITEMS: usize = 10;
/// Per-vector item cap for `list`'s preview digest.
const LIST_MAX_ITEMS: usize = 5;

#[derive(Parser)]
#[command(name = "session-summary")]
#[command(about = "Quick summary of Claude Code session files", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// List recent sessions with brief summaries (reads a bounded byte window
    /// from the end of each file, not the whole file)
    List {
        /// Number of recent sessions to show
        #[arg(short, long, default_value = "10")]
        limit: usize,

        /// Only show projects directory (exclude archive)
        #[arg(long)]
        projects_only: bool,

        /// Maximum age in hours (filter by last modification time)
        #[arg(long, default_value = "12")]
        max_age_hours: u64,

        /// Ignore --max-age-hours and list the newest sessions regardless of age
        #[arg(long)]
        all: bool,

        /// Claude home containing projects/ and archive/ (defaults to ~/.claude)
        #[arg(long, value_name = "PATH")]
        home: Option<PathBuf>,

        /// Emit machine-readable JSON instead of the human-readable listing
        #[arg(long)]
        json: bool,
    },
    /// Load full context from selected session (last segment + git hints)
    Load {
        /// Session JSONL path, exact UUID, or unique UUID prefix (at least 16 characters)
        session: String,

        /// Claude home containing projects/ and archive/ (defaults to ~/.claude)
        #[arg(long, value_name = "PATH")]
        home: Option<PathBuf>,

        /// Emit machine-readable JSON instead of the human-readable report
        #[arg(long)]
        json: bool,

        /// Print a count of unrecognized root event types seen in the scanned
        /// window to stderr. Diagnostic only — never changes stdout.
        #[arg(long)]
        debug: bool,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::List { limit, projects_only, max_age_hours, all, home, json } => {
            list_sessions(limit, !projects_only, max_age_hours, all, home, json)?;
        }
        Commands::Load { session, home, json, debug } => {
            let home = match home {
                Some(path) => path,
                None => dirs::home_dir()
                    .context("Failed to get home directory")?
                    .join(".claude"),
            };
            let path = resolve_session_path(&session, &home)?;
            load_session_context(&path, json, debug)?;
        }
    }

    Ok(())
}

// ============================================================================
// Path resolution and filesystem safety
// ============================================================================

#[derive(Debug)]
struct SessionRoot {
    lexical: PathBuf,
    canonical: PathBuf,
}

/// Resolve a load argument without allowing it to escape the selected Claude home.
fn resolve_session_path(session: &str, home: &Path) -> Result<PathBuf> {
    let roots = session_roots(home)?;
    let raw_path = Path::new(session);

    if looks_like_jsonl_path(session, raw_path) {
        return validate_session_path(raw_path, &roots);
    }

    if !is_uuid(session) && !is_uuid_prefix(session) {
        anyhow::bail!(
            "Session must be an exact JSONL path, an exact UUID, or a UUID prefix of at least 16 characters"
        );
    }

    let needle = session.to_ascii_lowercase();
    let exact = is_uuid(session);
    let mut matches = Vec::new();

    for root in &roots {
        collect_session_files(&root.lexical, &mut matches)?;
    }

    matches.retain(|path| {
        let Some(stem) = path.file_stem().and_then(|value| value.to_str()) else {
            return false;
        };
        if !is_uuid(stem) {
            return false;
        }
        if exact {
            stem.eq_ignore_ascii_case(session)
        } else {
            stem.to_ascii_lowercase().starts_with(&needle)
        }
    });

    match matches.len() {
        0 => anyhow::bail!("No Claude session matches identifier: {session}"),
        1 => validate_session_path(&matches[0], &roots),
        count => anyhow::bail!("Session identifier is ambiguous ({count} matches): {session}"),
    }
}

fn session_roots(home: &Path) -> Result<Vec<SessionRoot>> {
    let home = absolute_lexical(home)?;
    let mut roots = Vec::new();

    for directory in ["projects", "archive"] {
        let lexical = home.join(directory);
        let metadata = match fs::symlink_metadata(&lexical) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => return Err(error).with_context(|| {
                format!("Failed to inspect Claude session root: {}", lexical.display())
            }),
        };

        if is_symlink_or_reparse(&metadata) {
            anyhow::bail!("Claude session root must not be a symlink: {}", lexical.display());
        }
        if !metadata.is_dir() {
            anyhow::bail!("Claude session root is not a directory: {}", lexical.display());
        }

        let canonical = fs::canonicalize(&lexical).with_context(|| {
            format!("Failed to canonicalize Claude session root: {}", lexical.display())
        })?;
        roots.push(SessionRoot { lexical, canonical });
    }

    if roots.is_empty() {
        anyhow::bail!(
            "Claude session roots were not found under: {}",
            home.display()
        );
    }

    Ok(roots)
}

fn validate_session_path(path: &Path, roots: &[SessionRoot]) -> Result<PathBuf> {
    if path.extension().and_then(|value| value.to_str()) != Some("jsonl") {
        anyhow::bail!("Session path must name a .jsonl file: {}", path.display());
    }

    let lexical = absolute_lexical(path)?;
    let canonical = fs::canonicalize(&lexical)
        .with_context(|| format!("Session file not found: {}", lexical.display()))?;

    let root = roots.iter().find(|root| {
        lexical.starts_with(&root.lexical) && canonical.starts_with(&root.canonical)
    });
    let Some(root) = root else {
        anyhow::bail!(
            "Session path is outside the configured projects/archive roots: {}",
            lexical.display()
        );
    };

    reject_symlink_components(&lexical, &root.lexical)?;

    let metadata = fs::symlink_metadata(&lexical)
        .with_context(|| format!("Failed to inspect session file: {}", lexical.display()))?;
    if is_symlink_or_reparse(&metadata) {
        anyhow::bail!("Session path must not be a symlink: {}", lexical.display());
    }
    if !metadata.is_file() {
        anyhow::bail!("Session path is not a regular file: {}", lexical.display());
    }

    Ok(canonical)
}

fn reject_symlink_components(path: &Path, root: &Path) -> Result<()> {
    let relative = path.strip_prefix(root).context("Session path is outside its root")?;
    let mut current = root.to_path_buf();

    for component in relative.components() {
        current.push(component.as_os_str());
        let metadata = fs::symlink_metadata(&current)
            .with_context(|| format!("Failed to inspect session path: {}", current.display()))?;
        if is_symlink_or_reparse(&metadata) {
            anyhow::bail!("Session path must not contain symlinks: {}", current.display());
        }
    }

    Ok(())
}

fn is_symlink_or_reparse(metadata: &fs::Metadata) -> bool {
    if metadata.file_type().is_symlink() {
        return true;
    }

    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        has_windows_reparse_attribute(metadata.file_attributes())
    }

    #[cfg(not(windows))]
    false
}

#[cfg(windows)]
fn has_windows_reparse_attribute(attributes: u32) -> bool {
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
    attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
}

/// Directory basenames that never hold selectable sessions: subagent
/// transcripts and their raw tool-result blobs live alongside a session's
/// own `<uuid>.jsonl` under `<uuid>/subagents/` and `<uuid>/tool-results/`.
/// Skipping them here means `load`'s UUID/prefix resolution can never select
/// a subagent transcript (whose filename is `agent-<hex>.jsonl`, not a UUID,
/// so it was already excluded downstream — this also avoids the wasted
/// recursion on sessions with many delegated subagents).
const NON_SESSION_DIRECTORIES: [&str; 2] = ["subagents", "tool-results"];

fn collect_session_files(root: &Path, sessions: &mut Vec<PathBuf>) -> Result<()> {
    let mut pending = vec![root.to_path_buf()];

    while let Some(directory) = pending.pop() {
        for entry in fs::read_dir(&directory).with_context(|| {
            format!("Failed to read Claude session directory: {}", directory.display())
        })? {
            let entry = entry?;
            let path = entry.path();
            let metadata = fs::symlink_metadata(&path).with_context(|| {
                format!("Failed to inspect Claude session entry: {}", path.display())
            })?;

            if is_symlink_or_reparse(&metadata) {
                if path.extension().and_then(|value| value.to_str()) == Some("jsonl") {
                    sessions.push(path);
                }
                continue;
            }
            if metadata.is_dir() {
                let is_non_session_dir = path
                    .file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| NON_SESSION_DIRECTORIES.contains(&name));
                if !is_non_session_dir {
                    pending.push(path);
                }
            } else if metadata.is_file()
                && path.extension().and_then(|value| value.to_str()) == Some("jsonl")
            {
                sessions.push(path);
            }
        }
    }

    Ok(())
}

fn looks_like_jsonl_path(session: &str, path: &Path) -> bool {
    path.is_absolute()
        || path.extension().and_then(|value| value.to_str()) == Some("jsonl")
        || session.contains('/')
        || session.contains('\\')
        || session.starts_with('.')
}

fn is_uuid(value: &str) -> bool {
    if value.len() != 36 {
        return false;
    }

    value.bytes().enumerate().all(|(index, byte)| {
        if matches!(index, 8 | 13 | 18 | 23) {
            byte == b'-'
        } else {
            byte.is_ascii_hexdigit()
        }
    })
}

fn is_uuid_prefix(value: &str) -> bool {
    if value.len() < 16 || value.len() >= 36 {
        return false;
    }

    value.bytes().enumerate().all(|(index, byte)| {
        if matches!(index, 8 | 13 | 18 | 23) {
            byte == b'-'
        } else {
            byte.is_ascii_hexdigit()
        }
    })
}

fn absolute_lexical(path: &Path) -> Result<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .context("Failed to get current directory")?
            .join(path)
    };
    let mut normalized = PathBuf::new();

    for component in absolute.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() {
                    anyhow::bail!("Path escapes its filesystem root: {}", path.display());
                }
            }
            other => normalized.push(other.as_os_str()),
        }
    }

    Ok(normalized)
}

// ============================================================================
// Byte-budgeted reads (no external `tail` process, no full-file scans)
// ============================================================================

/// Read up to `max_bytes` from the end of `path`, split into complete lines.
///
/// A single seek plus one bounded read — cost is proportional to `max_bytes`,
/// not to file size. If the seek lands mid-line, that partial leading line is
/// dropped (it is truncated data anyway; its start lies outside the budget).
/// Returns `(lines, truncated)`, where `truncated` is `true` when the file is
/// larger than `max_bytes` (earlier context exists that this call did not read).
fn read_tail_lines(path: &Path, max_bytes: u64) -> Result<(Vec<String>, bool)> {
    let mut file = fs::File::open(path)
        .with_context(|| format!("Failed to open session file: {}", path.display()))?;
    let len = file
        .metadata()
        .with_context(|| format!("Failed to inspect session file: {}", path.display()))?
        .len();
    let start = len.saturating_sub(max_bytes);
    file.seek(SeekFrom::Start(start))
        .with_context(|| format!("Failed to seek session file: {}", path.display()))?;

    let mut buffer = Vec::with_capacity((len - start) as usize);
    file.read_to_end(&mut buffer)
        .with_context(|| format!("Failed to read session file: {}", path.display()))?;

    if start > 0 {
        if let Some(index) = buffer.iter().position(|byte| *byte == b'\n') {
            buffer.drain(..=index);
        } else {
            buffer.clear();
        }
    }

    let text = String::from_utf8_lossy(&buffer);
    let lines = text.lines().map(str::to_owned).collect();
    Ok((lines, start > 0))
}

/// Read up to `max_bytes` from the start of `path`, split into complete lines.
///
/// Used only as a fallback for title/first-prompt detection when the tail
/// window (which is read first, since it is far cheaper on a huge session)
/// carries neither.
fn read_head_lines(path: &Path, max_bytes: u64) -> Result<Vec<String>> {
    let mut file = fs::File::open(path)
        .with_context(|| format!("Failed to open session file: {}", path.display()))?;
    let mut buffer = vec![0_u8; max_bytes as usize];
    let read = file
        .read(&mut buffer)
        .with_context(|| format!("Failed to read session file: {}", path.display()))?;
    buffer.truncate(read);

    // If the budget was fully consumed, drop a trailing partial line — its
    // continuation lies outside the budget.
    if read as u64 == max_bytes {
        if let Some(index) = buffer.iter().rposition(|byte| *byte == b'\n') {
            buffer.truncate(index);
        }
    }

    let text = String::from_utf8_lossy(&buffer);
    Ok(text.lines().map(str::to_owned).collect())
}

/// Parse each line as a [`SessionEvent`], silently skipping lines that fail
/// to deserialize (malformed JSON, truncated leading/trailing line, or a
/// partial line from a session still being written to).
fn parse_events(lines: &[String]) -> Vec<SessionEvent> {
    lines
        .iter()
        .filter_map(|line| serde_json::from_str::<SessionEvent>(line).ok())
        .collect()
}

// ============================================================================
// Topic detection (D3: prefer the provider's own title over any inferred label)
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TopicSource {
    CustomTitle,
    AiTitle,
    LastPrompt,
    FirstPrompt,
    None,
}

impl fmt::Display for TopicSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let label = match self {
            Self::CustomTitle => "custom_title",
            Self::AiTitle => "ai_title",
            Self::LastPrompt => "last_prompt",
            Self::FirstPrompt => "first_prompt",
            Self::None => "none",
        };
        f.write_str(label)
    }
}

fn last_custom_title(events: &[SessionEvent]) -> Option<String> {
    events.iter().rev().find_map(|event| match event {
        SessionEvent::CustomTitle(title) => Some(title.custom_title.clone()),
        _ => None,
    })
}

fn last_ai_title(events: &[SessionEvent]) -> Option<String> {
    events.iter().rev().find_map(|event| match event {
        SessionEvent::AiTitle(title) => Some(title.ai_title.clone()),
        _ => None,
    })
}

fn last_last_prompt(events: &[SessionEvent]) -> Option<String> {
    events.iter().rev().find_map(|event| match event {
        SessionEvent::LastPrompt(prompt) => Some(prompt.last_prompt.clone()),
        _ => None,
    })
}

/// First genuine human turn (a topic fallback) — excludes slash commands and
/// harness notifications, per [`UserTurnKind`].
fn first_human_prompt(events: &[SessionEvent]) -> Option<String> {
    events.iter().find_map(|event| match event {
        SessionEvent::User(user) => match user.classify_turn() {
            UserTurnKind::HumanPrompt(text) => Some(text.to_owned()),
            _ => None,
        },
        _ => None,
    })
}

/// Pick the topic per the priority order documented on this module: the
/// tail window is checked first (cheap, and titles repeat through the file
/// so the tail almost always carries the latest one), then the head window
/// as a fallback for sessions whose tail window missed every repeat.
fn detect_topic(head: &[SessionEvent], tail: &[SessionEvent]) -> (String, TopicSource) {
    if let Some(title) = last_custom_title(tail) {
        return (title, TopicSource::CustomTitle);
    }
    if let Some(title) = last_ai_title(tail) {
        return (title, TopicSource::AiTitle);
    }
    if let Some(prompt) = last_last_prompt(tail) {
        return (prompt, TopicSource::LastPrompt);
    }
    if let Some(title) = last_custom_title(head) {
        return (title, TopicSource::CustomTitle);
    }
    if let Some(title) = last_ai_title(head) {
        return (title, TopicSource::AiTitle);
    }
    if let Some(prompt) = last_last_prompt(head) {
        return (prompt, TopicSource::LastPrompt);
    }
    if let Some(prompt) = first_human_prompt(head) {
        return (prompt, TopicSource::FirstPrompt);
    }
    if let Some(prompt) = first_human_prompt(tail) {
        return (prompt, TopicSource::FirstPrompt);
    }
    ("Empty session".to_string(), TopicSource::None)
}

// ============================================================================
// Digest extraction
// ============================================================================

#[derive(Debug, Clone, Default)]
struct SessionDigest {
    topic: String,
    topic_source: String,
    agent_tasks: Vec<String>,
    user_messages: Vec<String>,
    assistant_texts: Vec<String>,
    tool_operations: Vec<String>,
    bash_activities: Vec<String>,
    web_queries: Vec<String>,
    errors: Vec<String>,
    files: Vec<String>,
    git_branch: Option<String>,
    commit_hints: Vec<String>,
    truncated: bool,
    unknown_type_counts: Vec<(String, u64)>,
    /// Count of `user` turns classified as
    /// [`claude_session_types::events::UserTurnKind::HarnessNotification`]
    /// within the scanned window: task notifications, compaction summaries,
    /// peer/cross-session messages, local-command echoes, `isMeta` turns, and
    /// tool-result-only turns. Kept so filtering them out of the digest is
    /// visible, not silent.
    harness_notifications_skipped: u64,
}

struct DigestLimits {
    tail_bytes: u64,
    head_bytes: u64,
    max_items: usize,
    count_unknown_types: bool,
}

const LIST_LIMITS: DigestLimits = DigestLimits {
    tail_bytes: LIST_TAIL_BYTES,
    head_bytes: HEAD_FALLBACK_BYTES,
    max_items: LIST_MAX_ITEMS,
    count_unknown_types: false,
};

fn load_limits(debug: bool) -> DigestLimits {
    DigestLimits {
        tail_bytes: LOAD_TAIL_BYTES,
        head_bytes: HEAD_FALLBACK_BYTES,
        max_items: LOAD_MAX_ITEMS,
        count_unknown_types: debug,
    }
}

/// Keep only the last `cap` entries of `items`, preserving order.
///
/// Digest vectors are collected in chronological order across the whole
/// scanned window; a session with more real turns than `cap` must keep the
/// *most recent* ones, not whichever were encountered first — showing the
/// earliest N turns of a long window as "the digest" silently hides
/// everything since, including the very last thing the user said.
fn truncate_to_last(items: &mut Vec<String>, cap: usize) {
    if items.len() > cap {
        let drop_count = items.len() - cap;
        items.drain(..drop_count);
    }
}

/// Build a verbatim-quote digest of `path`'s tail window.
fn build_digest(path: &Path, limits: &DigestLimits) -> Result<SessionDigest> {
    let (tail_lines, truncated) = read_tail_lines(path, limits.tail_bytes)?;
    let tail_events = parse_events(&tail_lines);
    let head_lines = read_head_lines(path, limits.head_bytes)?;
    let head_events = parse_events(&head_lines);

    let (topic, topic_source) = detect_topic(&head_events, &tail_events);

    let unknown_type_counts = if limits.count_unknown_types {
        count_unknown_root_types(&tail_lines)
    } else {
        Vec::new()
    };

    // "Last events" means after the last compaction boundary, when one
    // exists inside the scanned window.
    let boundary = tail_events.iter().rposition(|event| {
        matches!(event, SessionEvent::System(sys) if sys.is_compact_boundary())
    });
    let window = boundary.map_or(tail_events.as_slice(), |index| &tail_events[index + 1..]);

    let mut digest = SessionDigest {
        topic,
        topic_source: topic_source.to_string(),
        truncated,
        unknown_type_counts,
        ..SessionDigest::default()
    };
    let mut commit_hints = HashSet::new();
    let mut files = HashSet::new();

    for event in window {
        match event {
            SessionEvent::User(user) => {
                if let Some(branch) = &user.metadata.git_branch {
                    digest.git_branch = Some(branch.clone());
                }
                match user.classify_turn() {
                    UserTurnKind::HumanPrompt(text) => {
                        extract_commit_hints(text, &mut commit_hints);
                        digest.user_messages.push(text.to_string());
                    }
                    UserTurnKind::SlashCommand { name, args } => {
                        digest.user_messages.push(render_slash_command(name, args));
                    }
                    UserTurnKind::HarnessNotification => {
                        digest.harness_notifications_skipped += 1;
                    }
                }
            }
            SessionEvent::Assistant(assistant) => {
                for block in &assistant.message.content {
                    if let Some(text) = block.as_text() {
                        extract_commit_hints(text, &mut commit_hints);
                        digest.assistant_texts.push(text.to_string());
                    }
                    if let Some((_, name, input)) = block.as_tool_use() {
                        digest.tool_operations.push(describe_tool_use(name, input));
                        record_tool_side_effects(name, input, &mut digest, &mut files);
                    }
                }
            }
            SessionEvent::Progress(progress) => match &progress.data {
                ProgressData::AgentProgress(agent) => {
                    extract_commit_hints(&agent.prompt, &mut commit_hints);
                    digest.agent_tasks.push(agent.prompt.clone());
                }
                ProgressData::QueryUpdate(query) => {
                    digest.web_queries.push(query.query.clone());
                }
                _ => {}
            },
            SessionEvent::FileSnapshot(snapshot) => {
                for file_path in snapshot.snapshot.tracked_file_backups.keys() {
                    files.insert(normalize_path_separators(file_path));
                }
            }
            SessionEvent::System(sys) if sys.is_error() => {
                let message = sys
                    .error
                    .as_ref()
                    .map(|error| format!("{}: {}", error.error_type, error.message))
                    .or_else(|| sys.content.clone())
                    .unwrap_or_else(|| "unspecified system error".to_string());
                digest.errors.push(message);
            }
            _ => {}
        }
    }

    truncate_to_last(&mut digest.agent_tasks, limits.max_items);
    truncate_to_last(&mut digest.user_messages, limits.max_items);
    truncate_to_last(&mut digest.assistant_texts, limits.max_items);
    truncate_to_last(&mut digest.tool_operations, limits.max_items * 3);
    truncate_to_last(&mut digest.bash_activities, limits.max_items);
    truncate_to_last(&mut digest.web_queries, limits.max_items);
    truncate_to_last(&mut digest.errors, limits.max_items);

    digest.files = files.into_iter().collect();
    digest.files.sort();
    digest.commit_hints = commit_hints.into_iter().collect();
    digest.commit_hints.sort();

    Ok(digest)
}

/// Render a slash-command turn for display: `/model claude-fable-5`, or just
/// `/compact` when there are no arguments.
fn render_slash_command(name: &str, args: &str) -> String {
    let args = args.trim();
    if args.is_empty() {
        name.to_string()
    } else {
        format!("{name} {args}")
    }
}

fn record_tool_side_effects(
    name: &str,
    input: &JsonValue,
    digest: &mut SessionDigest,
    files: &mut HashSet<String>,
) {
    match name {
        "Read" | "Write" | "Edit" | "NotebookEdit" => {
            if let Some(path) = input
                .get("file_path")
                .or_else(|| input.get("filePath"))
                .and_then(JsonValue::as_str)
            {
                files.insert(normalize_path_separators(path));
            }
        }
        "Bash" => {
            if let Some(command) = input.get("command").and_then(JsonValue::as_str) {
                if is_interesting_bash(command) {
                    digest.bash_activities.push(command.to_string());
                }
            }
        }
        "WebSearch" => {
            if let Some(query) = input.get("query").and_then(JsonValue::as_str) {
                digest.web_queries.push(query.to_string());
            }
        }
        _ => {}
    }
}

fn normalize_path_separators(path: &str) -> String {
    path.replace('\\', "/")
}

fn is_interesting_bash(command: &str) -> bool {
    let lowered = command.to_lowercase();
    [
        "cargo build",
        "cargo check",
        "cargo test",
        "npm install",
        "git commit",
        "pytest",
        "compiling",
    ]
    .iter()
    .any(|marker| lowered.contains(marker))
}

/// One-line description of a tool invocation including its most relevant
/// argument — the "tool calls with key args" the digest spec asks for.
fn describe_tool_use(name: &str, input: &JsonValue) -> String {
    let key_arg = match name {
        "Bash" => input.get("command").and_then(JsonValue::as_str),
        "Read" | "Write" | "Edit" | "NotebookEdit" => {
            input.get("file_path").or_else(|| input.get("filePath")).and_then(JsonValue::as_str)
        }
        "Grep" | "Glob" => input.get("pattern").and_then(JsonValue::as_str),
        "WebSearch" => input.get("query").and_then(JsonValue::as_str),
        "WebFetch" => input.get("url").and_then(JsonValue::as_str),
        "Task" | "Agent" => input
            .get("description")
            .and_then(JsonValue::as_str)
            .or_else(|| input.get("subagent_type").and_then(JsonValue::as_str)),
        _ => None,
    };

    match key_arg {
        Some(arg) => {
            let first_line = arg.lines().next().unwrap_or(arg);
            format!("{name}: {}", truncate(first_line, 100))
        }
        None => name.to_string(),
    }
}

/// Extract git commit hints (`feat(scope)`-style prefixes and path mentions)
/// from verbatim quoted text — human prompts and assistant text alike.
fn extract_commit_hints(text: &str, hints: &mut HashSet<String>) {
    let patterns = [
        r"feat\(([^)]+)\)",
        r"fix\(([^)]+)\)",
        r"refactor\(([^)]+)\)",
        r"chore\(([^)]+)\)",
        r"test\(([^)]+)\)",
    ];

    for pattern in &patterns {
        if let Ok(re) = Regex::new(pattern) {
            for cap in re.captures_iter(text) {
                if let Some(scope) = cap.get(1) {
                    hints.insert(scope.as_str().to_string());
                }
            }
        }
    }

    for word in text.split_whitespace() {
        if word.contains("v5/") || word.contains("connectors/") || word.contains("ui/") {
            hints.insert(word.to_string());
        }
    }
}

/// Root event `type` tags modeled by [`SessionEvent`]. Used only by the
/// `--debug` histogram to name types that fall into `SessionEvent::Unknown`
/// without re-deriving the tag list from serde internals.
const KNOWN_ROOT_TYPES: &[&str] = &[
    "user",
    "assistant",
    "progress",
    "system",
    "file-history-snapshot",
    "queue-operation",
    "summary",
    "attachment",
    "custom-title",
    "ai-title",
    "last-prompt",
    "bridge-session",
    "atis-latch",
    "mode",
    "permission-mode",
    "agent-name",
    "file-history-delta",
];

/// Count root `type` tags that do not match any [`SessionEvent`] variant,
/// for the `--debug` diagnostic. This never affects `load`'s stdout output.
fn count_unknown_root_types(lines: &[String]) -> Vec<(String, u64)> {
    let mut counts: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
    for line in lines {
        let Ok(value) = serde_json::from_str::<JsonValue>(line) else {
            continue;
        };
        let Some(type_tag) = value.get("type").and_then(JsonValue::as_str) else {
            continue;
        };
        if !KNOWN_ROOT_TYPES.contains(&type_tag) {
            *counts.entry(type_tag.to_string()).or_default() += 1;
        }
    }
    let mut counts: Vec<(String, u64)> = counts.into_iter().collect();
    counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    counts
}

// ============================================================================
// `list`
// ============================================================================

#[derive(Serialize)]
struct SessionListEntry {
    id: String,
    /// UTC, ISO 8601 (`--json` always reports UTC regardless of the human
    /// display's local time)
    modified: Option<String>,
    size_bytes: u64,
    source: &'static str,
    topic: String,
    topic_source: String,
    tasks: Vec<String>,
    user_messages: Vec<String>,
    tool_operations: Vec<String>,
    bash_activities: Vec<String>,
    web_queries: Vec<String>,
    harness_notifications_skipped: u64,
}

#[derive(Serialize)]
struct SessionListReport {
    schema: &'static str,
    sessions: Vec<SessionListEntry>,
}

fn list_sessions(
    limit: usize,
    include_archived: bool,
    max_age_hours: u64,
    all: bool,
    home: Option<PathBuf>,
    json: bool,
) -> Result<()> {
    let home = match home {
        Some(path) => path,
        None => dirs::home_dir().context("Failed to get home directory")?.join(".claude"),
    };
    let projects_dir = home.join("projects");

    if !projects_dir.exists() {
        anyhow::bail!("Claude projects directory not found: {}", projects_dir.display());
    }

    let now = SystemTime::now();
    let cutoff_time = if all {
        SystemTime::UNIX_EPOCH
    } else {
        let max_age = std::time::Duration::from_secs(max_age_hours * 3600);
        now.checked_sub(max_age).unwrap_or(SystemTime::UNIX_EPOCH)
    };

    let mut sessions: Vec<(PathBuf, u64, Option<DateTime<Utc>>, &'static str)> = Vec::new();

    for entry in fs::read_dir(&projects_dir).with_context(|| {
        format!("Failed to read Claude projects directory: {}", projects_dir.display())
    })? {
        let entry = entry?;
        let project_path = entry.path();
        if !project_path.is_dir() {
            continue;
        }
        collect_top_level_sessions(&project_path, cutoff_time, "projects", &mut sessions)?;
    }

    if include_archived {
        let archive_dir = home.join("archive");
        if archive_dir.exists() {
            collect_top_level_sessions(&archive_dir, cutoff_time, "archive", &mut sessions)?;
        }
    }

    sessions.sort_by_key(|(_, _, modified, _)| std::cmp::Reverse(*modified));
    sessions.truncate(limit);

    if sessions.is_empty() {
        if json {
            let report = SessionListReport { schema: SCHEMA_LIST, sessions: Vec::new() };
            println!("{}", serde_json::to_string_pretty(&report)?);
        } else {
            println!("{}", "Recent Sessions:".bold().bright_cyan());
            println!();
            let window = if all {
                "any age".to_string()
            } else {
                format!("the last {max_age_hours}h")
            };
            println!(
                "No Claude sessions found in {window} under {}. Try --max-age-hours <N> or --all.",
                projects_dir.display()
            );
        }
        return Ok(());
    }

    if json {
        let mut entries = Vec::with_capacity(sessions.len());
        for (path, size, modified, source) in &sessions {
            entries.push(build_list_entry(path, *size, *modified, source)?);
        }
        let report = SessionListReport { schema: SCHEMA_LIST, sessions: entries };
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }

    println!("{}", "Recent Sessions:".bold().bright_cyan());
    println!();

    for (i, (path, size, modified, source)) in sessions.iter().enumerate() {
        let digest = build_digest(path, &LIST_LIMITS).unwrap_or_default();

        let session_id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown");

        println!("{}", format!("{}. {}", i + 1, session_id).bright_yellow());

        if let Some(mod_time) = modified {
            print!("   {} | ", local_time(mod_time).format("%b %d %H:%M"));
        }
        print!("{} | ", format_size(*size));
        print!("[{}] | ", source.dimmed());
        println!("{}", truncate(&digest.topic, 80).bright_green());

        if !digest.agent_tasks.is_empty() {
            let tasks_preview: Vec<String> =
                last_n(&digest.agent_tasks, 2).iter().map(|t| truncate(t, 60)).collect();
            println!("   📋 Tasks: {}", tasks_preview.join("").dimmed());
        }

        if !digest.user_messages.is_empty() {
            let msg_preview: Vec<String> =
                last_n(&digest.user_messages, 2).iter().map(|m| truncate(m, 50)).collect();
            println!("   💬 User: {}", msg_preview.join("").dimmed());
        }

        if !digest.tool_operations.is_empty() {
            let tools_preview: Vec<String> =
                last_n(&digest.tool_operations, 5).iter().map(|t| truncate(t, 80)).collect();
            println!("   🔧 Tools: {}", tools_preview.join(", ").dimmed());
        }

        if !digest.bash_activities.is_empty() {
            let bash_preview: Vec<String> = last_n(&digest.bash_activities, 3)
                .iter()
                .map(|cmd| truncate(cmd.lines().next().unwrap_or(cmd).trim(), 100))
                .collect();
            println!("   ⚙️  Bash: {}", bash_preview.join("; ").dimmed());
        }

        if !digest.web_queries.is_empty() {
            println!("   🔍 Search: {}", last_n(&digest.web_queries, 3).join(", ").dimmed());
        }

        println!();
    }

    println!();
    println!("{}", "To load a session, use:".bold());
    for (i, (path, _, _, _)) in sessions.iter().enumerate() {
        println!("  {}. session-summary.exe load \"{}\"", i + 1, path.display());
    }

    Ok(())
}

fn collect_top_level_sessions(
    dir: &Path,
    cutoff_time: SystemTime,
    source: &'static str,
    sessions: &mut Vec<(PathBuf, u64, Option<DateTime<Utc>>, &'static str)>,
) -> Result<()> {
    for entry in fs::read_dir(dir)
        .with_context(|| format!("Failed to read Claude session directory: {}", dir.display()))?
    {
        let entry = entry?;
        let path = entry.path();

        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }

        let Ok(metadata) = fs::metadata(&path) else {
            continue;
        };
        let Ok(modified_time) = metadata.modified() else {
            continue;
        };
        if modified_time < cutoff_time {
            continue;
        }

        let modified = modified_time
            .duration_since(SystemTime::UNIX_EPOCH)
            .ok()
            .and_then(|duration| DateTime::from_timestamp(duration.as_secs() as i64, 0));

        sessions.push((path, metadata.len(), modified, source));
    }

    Ok(())
}

fn build_list_entry(
    path: &Path,
    size: u64,
    modified: Option<DateTime<Utc>>,
    source: &'static str,
) -> Result<SessionListEntry> {
    let digest = build_digest(path, &LIST_LIMITS)?;
    let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown").to_string();

    Ok(SessionListEntry {
        id,
        modified: modified.map(|value| value.to_rfc3339()),
        size_bytes: size,
        source,
        topic: digest.topic,
        topic_source: digest.topic_source,
        tasks: digest.agent_tasks,
        user_messages: digest.user_messages,
        tool_operations: digest.tool_operations,
        bash_activities: digest.bash_activities,
        web_queries: digest.web_queries,
        harness_notifications_skipped: digest.harness_notifications_skipped,
    })
}

// ============================================================================
// `load`
// ============================================================================

#[derive(Serialize)]
struct SessionLoadReport {
    schema: &'static str,
    session_id: String,
    date: Option<String>,
    size_bytes: u64,
    topic: String,
    topic_source: String,
    agent_tasks: Vec<String>,
    user_messages: Vec<String>,
    assistant_texts: Vec<String>,
    tool_operations: Vec<String>,
    bash_activities: Vec<String>,
    web_queries: Vec<String>,
    errors: Vec<String>,
    files: Vec<String>,
    git_branch: Option<String>,
    commit_hints: Vec<String>,
    truncated: bool,
    harness_notifications_skipped: u64,
}

fn load_session_context(path: &Path, json: bool, debug: bool) -> Result<()> {
    if !path.exists() {
        anyhow::bail!("Session file not found: {}", path.display());
    }

    let metadata = fs::metadata(path)?;
    let size_bytes = metadata.len();
    let modified = metadata
        .modified()
        .ok()
        .and_then(|st| st.duration_since(SystemTime::UNIX_EPOCH).ok())
        .and_then(|d| DateTime::from_timestamp(d.as_secs() as i64, 0));

    let session_id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown");
    let digest = build_digest(path, &load_limits(debug))?;

    if debug {
        if digest.unknown_type_counts.is_empty() {
            eprintln!("[debug] no unrecognized root event types in the scanned window");
        } else {
            eprintln!("[debug] unrecognized root event types in the scanned window:");
            for (type_name, count) in &digest.unknown_type_counts {
                eprintln!("[debug]   {type_name}: {count}");
            }
        }
    }

    if json {
        let report = SessionLoadReport {
            schema: SCHEMA_LOAD,
            session_id: session_id.to_string(),
            date: modified.map(|value| value.to_rfc3339()),
            size_bytes,
            topic: digest.topic,
            topic_source: digest.topic_source,
            agent_tasks: digest.agent_tasks,
            user_messages: digest.user_messages,
            assistant_texts: digest.assistant_texts,
            tool_operations: digest.tool_operations,
            bash_activities: digest.bash_activities,
            web_queries: digest.web_queries,
            errors: digest.errors,
            files: digest.files,
            git_branch: digest.git_branch,
            commit_hints: digest.commit_hints,
            truncated: digest.truncated,
            harness_notifications_skipped: digest.harness_notifications_skipped,
        };
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }

    println!("{}", "═══════════════════════════════════════".bright_cyan());
    println!("{} {}", "Session:".bold(), session_id.bright_yellow());
    println!("{}", "═══════════════════════════════════════".bright_cyan());

    if let Some(mod_time) = modified {
        println!("{} {}", "Date:".bold(), local_time(&mod_time).format("%Y-%m-%d %H:%M:%S %z"));
    }

    println!("{} {}", "Size:".bold(), format_size(size_bytes));
    println!("{} {}", "Topic:".bold(), digest.topic.bright_green());

    if digest.harness_notifications_skipped > 0 {
        println!(
            "{} {}",
            "Harness notifications skipped:".bold(),
            digest.harness_notifications_skipped
        );
    }

    if !digest.agent_tasks.is_empty() {
        println!(
            "\n{} 📋 {}",
            "Agent Tasks".bold(),
            format!("({} tasks)", digest.agent_tasks.len()).dimmed()
        );
        print_numbered(&digest.agent_tasks, 10, 200);
    }

    if !digest.user_messages.is_empty() {
        println!(
            "\n{} 💬 {}",
            "User Messages".bold(),
            format!("({} messages)", digest.user_messages.len()).dimmed()
        );
        print_numbered_tail_verbatim(&digest.user_messages, 10, 150, 3, 4000);
    }

    if !digest.assistant_texts.is_empty() {
        println!(
            "\n{} 🤖 {}",
            "Assistant Texts".bold(),
            format!("({} texts)", digest.assistant_texts.len()).dimmed()
        );
        print_numbered_tail_verbatim(&digest.assistant_texts, 10, 200, 3, 4000);
    }

    if !digest.tool_operations.is_empty() {
        println!(
            "\n{} 🔧 {}",
            "Tool Operations".bold(),
            format!("({} operations)", digest.tool_operations.len()).dimmed()
        );
        print_numbered(&digest.tool_operations, 15, 200);
    }

    if !digest.bash_activities.is_empty() {
        println!(
            "\n{} ⚙️  {}",
            "Bash Activities".bold(),
            format!("({} commands)", digest.bash_activities.len()).dimmed()
        );
        for (i, cmd) in digest.bash_activities.iter().take(5).enumerate() {
            let first_line = cmd.lines().next().unwrap_or("");
            println!("  {}. {}", i + 1, truncate(first_line, 150).bright_white());
        }
        if digest.bash_activities.len() > 5 {
            println!("  {} ({} more)", "...".dimmed(), digest.bash_activities.len() - 5);
        }
    }

    if !digest.web_queries.is_empty() {
        println!(
            "\n{} 🔍 {}",
            "Web Searches".bold(),
            format!("({} queries)", digest.web_queries.len()).dimmed()
        );
        print_numbered(&digest.web_queries, 10, 200);
    }

    if !digest.errors.is_empty() {
        println!(
            "\n{} 🚨 {}",
            "Errors".bold(),
            format!("({} errors)", digest.errors.len()).dimmed()
        );
        print_numbered(&digest.errors, 10, 300);
    }

    if !digest.files.is_empty() {
        println!(
            "\n{} 📁 {}",
            "Files Touched".bold(),
            format!("({} files)", digest.files.len()).dimmed()
        );
        for (i, file) in digest.files.iter().take(10).enumerate() {
            println!("  {}. {}", i + 1, shorten_path(file).bright_white());
        }
        if digest.files.len() > 10 {
            println!("  {} ({} more files)", "...".dimmed(), digest.files.len() - 10);
        }
    }

    if let Some(ref branch) = digest.git_branch {
        println!("\n{} {}", "Git Branch:".bold(), branch.bright_cyan());
    }

    if !digest.commit_hints.is_empty() {
        println!("\n{} 🔎", "Git Commit Hints (for git log search):".bold());
        for hint in &digest.commit_hints {
            println!("  - {}", hint.dimmed());
        }
    }

    if digest.truncated {
        println!(
            "\n{}",
            "(session is larger than the read window — earlier context was not scanned)".dimmed()
        );
    }

    println!();

    Ok(())
}

fn print_numbered(items: &[String], limit: usize, max_chars: usize) {
    for (i, item) in items.iter().take(limit).enumerate() {
        println!("  {}. {}", i + 1, truncate(item, max_chars).bright_white());
    }
    if items.len() > limit {
        println!("  {} ({} more)", "...".dimmed(), items.len() - limit);
    }
}

/// Print up to `limit` of the most recent `items`, with the last `full_tail`
/// entries shown in full (single-line collapsed for the rest, up to
/// `short_max_chars`) — bounded at `full_max_chars` with an explicit
/// "[truncated N chars]" marker rather than a silent `...`. Verbatim means
/// verbatim: the newest turns are worth reading in full, not guessing at
/// from a 150-character snippet.
fn print_numbered_tail_verbatim(
    items: &[String],
    limit: usize,
    short_max_chars: usize,
    full_tail: usize,
    full_max_chars: usize,
) {
    let shown = last_n(items, limit);
    let hidden = items.len() - shown.len();
    let full_start = shown.len().saturating_sub(full_tail);

    for (i, item) in shown.iter().enumerate() {
        let index = hidden + i + 1;
        if i >= full_start {
            let (text, cut) = truncate_reporting(item, full_max_chars);
            println!("  {index}. {}", text.bright_white());
            if let Some(cut) = cut {
                println!("     {}", format!("[truncated {cut} chars]").dimmed());
            }
        } else {
            let first_line = item.lines().next().unwrap_or(item);
            println!("  {index}. {}", truncate(first_line, short_max_chars).bright_white());
        }
    }
    if hidden > 0 {
        println!("  {} ({hidden} earlier, not shown)", "...".dimmed());
    }
}

// ============================================================================
// Formatting helpers
// ============================================================================

/// Slice out the last `n` elements of `items`, preserving order (oldest of
/// the kept set first, newest last).
fn last_n<T>(items: &[T], n: usize) -> &[T] {
    let start = items.len().saturating_sub(n);
    &items[start..]
}

/// Convert a stored UTC timestamp to local time for human display. `--json`
/// output keeps the UTC `DateTime` untouched (via `to_rfc3339`) — this
/// conversion is display-only.
fn local_time(utc: &DateTime<Utc>) -> DateTime<Local> {
    utc.with_timezone(&Local)
}

/// Shorten path for display
fn shorten_path(path: &str) -> String {
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() > 2 {
        format!(".../{}/{}", parts[parts.len() - 2], parts[parts.len() - 1])
    } else {
        path.to_string()
    }
}

/// Truncate string to max length (UTF-8 safe)
fn truncate(s: &str, max_len: usize) -> String {
    if s.len() > max_len {
        let mut boundary = max_len;
        while boundary > 0 && !s.is_char_boundary(boundary) {
            boundary -= 1;
        }
        format!("{}...", &s[..boundary])
    } else {
        s.to_string()
    }
}

/// Truncate `text` to at most `max_bytes`, UTF-8 safe. Returns the
/// (possibly-truncated) text and, if truncation happened, how many bytes
/// were cut — used to print an explicit "[truncated N chars]" marker instead
/// of a silent `...`.
fn truncate_reporting(text: &str, max_bytes: usize) -> (String, Option<usize>) {
    if text.len() <= max_bytes {
        return (text.to_string(), None);
    }
    let mut boundary = max_bytes;
    while boundary > 0 && !text.is_char_boundary(boundary) {
        boundary -= 1;
    }
    (text[..boundary].to_string(), Some(text.len() - boundary))
}

/// Format file size in human-readable format
fn format_size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{bytes} bytes")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct TestHome {
        path: PathBuf,
    }

    impl TestHome {
        fn new() -> Self {
            let unique = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .expect("system clock")
                .as_nanos();
            let path = std::env::temp_dir().join(format!(
                "session-summary-tests-{}-{unique}",
                std::process::id()
            ));
            fs::create_dir_all(path.join("projects").join("project-a"))
                .expect("create projects root");
            fs::create_dir_all(path.join("archive")).expect("create archive root");
            Self { path }
        }

        fn session(&self, relative: &str, id: &str) -> PathBuf {
            let directory = self.path.join(relative);
            fs::create_dir_all(&directory).expect("create session directory");
            let path = directory.join(format!("{id}.jsonl"));
            fs::write(&path, "{}\n").expect("write session fixture");
            path
        }

        fn session_with_content(&self, relative: &str, id: &str, content: &str) -> PathBuf {
            let directory = self.path.join(relative);
            fs::create_dir_all(&directory).expect("create session directory");
            let path = directory.join(format!("{id}.jsonl"));
            fs::write(&path, content).expect("write session fixture");
            path
        }
    }

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

    #[test]
    fn parses_home_after_load_identifier() {
        let cli = Cli::try_parse_from([
            "session-summary",
            "load",
            "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
            "--home",
            "C:\\fixture\\.claude",
        ])
        .expect("parse load command");

        let Commands::Load { session, home, json, debug } = cli.command else {
            panic!("expected load command");
        };
        assert_eq!(session, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
        assert_eq!(home, Some(PathBuf::from("C:\\fixture\\.claude")));
        assert!(!json);
        assert!(!debug);
    }

    #[test]
    fn parses_list_with_home_all_and_json() {
        let cli = Cli::try_parse_from([
            "session-summary",
            "list",
            "--home",
            "C:\\fixture\\.claude",
            "--all",
            "--json",
        ])
        .expect("parse list command");

        let Commands::List { home, all, json, .. } = cli.command else {
            panic!("expected list command");
        };
        assert_eq!(home, Some(PathBuf::from("C:\\fixture\\.claude")));
        assert!(all);
        assert!(json);
    }

    #[cfg(windows)]
    #[test]
    fn recognizes_windows_reparse_attribute() {
        assert!(has_windows_reparse_attribute(0x400));
        assert!(has_windows_reparse_attribute(0x420));
        assert!(!has_windows_reparse_attribute(0x20));
    }

    #[test]
    fn resolves_existing_path_exact_uuid_and_unique_prefix() {
        let home = TestHome::new();
        let id = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
        let path = home.session("projects/project-a", id);
        let expected = fs::canonicalize(&path).expect("canonical fixture path");

        assert_eq!(
            resolve_session_path(path.to_str().expect("UTF-8 path"), &home.path)
                .expect("resolve exact path"),
            expected
        );
        assert_eq!(
            resolve_session_path(id, &home.path).expect("resolve exact UUID"),
            expected
        );
        assert_eq!(
            resolve_session_path("aaaaaaaa-aaaa-4aaa-8aaa-a", &home.path)
                .expect("resolve unique prefix"),
            expected
        );
    }

    #[test]
    fn rejects_short_and_ambiguous_prefixes() {
        let home = TestHome::new();
        home.session(
            "projects/project-a",
            "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
        );
        home.session("archive", "aaaaaaaa-aaaa-4aaa-8aaa-bbbbbbbbbbbb");

        let short = resolve_session_path("aaaaaaaa-aaaa-4", &home.path)
            .expect_err("short prefix must fail")
            .to_string();
        assert!(short.contains("at least 16"), "unexpected error: {short}");

        let ambiguous = resolve_session_path("aaaaaaaa-aaaa-4a", &home.path)
            .expect_err("ambiguous prefix must fail")
            .to_string();
        assert!(ambiguous.contains("ambiguous"), "unexpected error: {ambiguous}");
    }

    #[test]
    fn rejects_outside_and_nonregular_paths() {
        let home = TestHome::new();
        let outside = home.path.with_extension("outside.jsonl");
        fs::write(&outside, "{}\n").expect("write outside fixture");
        let nonregular = home.path.join("projects").join("directory.jsonl");
        fs::create_dir(&nonregular).expect("create nonregular fixture");

        let outside_error = resolve_session_path(
            outside.to_str().expect("UTF-8 outside path"),
            &home.path,
        )
        .expect_err("outside path must fail")
        .to_string();
        assert!(
            outside_error.contains("outside"),
            "unexpected error: {outside_error}"
        );

        let nonregular_error = resolve_session_path(
            nonregular.to_str().expect("UTF-8 nonregular path"),
            &home.path,
        )
        .expect_err("nonregular path must fail")
        .to_string();
        assert!(
            nonregular_error.contains("not a regular file"),
            "unexpected error: {nonregular_error}"
        );

        fs::remove_file(outside).expect("remove outside fixture");
    }

    #[test]
    fn rejects_symlink_session_path() {
        let home = TestHome::new();
        let target = home.session(
            "projects/project-a",
            "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
        );
        let link = home
            .path
            .join("projects")
            .join("project-a")
            .join("cccccccc-cccc-4ccc-8ccc-cccccccccccc.jsonl");

        #[cfg(unix)]
        std::os::unix::fs::symlink(&target, &link).expect("create session symlink");

        #[cfg(windows)]
        if let Err(error) = std::os::windows::fs::symlink_file(&target, &link) {
            if error.kind() == std::io::ErrorKind::PermissionDenied
                || error.raw_os_error() == Some(1314)
            {
                return;
            }
            panic!("create session symlink: {error}");
        }

        let error = resolve_session_path(link.to_str().expect("UTF-8 link path"), &home.path)
            .expect_err("symlink must fail")
            .to_string();
        assert!(
            error.contains("symlink"),
            "unexpected symlink error: {error}"
        );
    }

    #[test]
    fn subagent_transcripts_are_never_selected_as_load_targets() {
        let home = TestHome::new();
        let session_id = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
        home.session("projects/project-a", session_id);
        // A subagent transcript directory sibling to the session file, named
        // after the session UUID, holding a non-UUID-stemmed jsonl.
        let subagents_dir = home
            .path
            .join("projects")
            .join("project-a")
            .join(session_id)
            .join("subagents");
        fs::create_dir_all(&subagents_dir).expect("create subagents dir");
        fs::write(subagents_dir.join("agent-deadbeef.jsonl"), "{}\n")
            .expect("write subagent fixture");

        let mut matches = Vec::new();
        let roots = session_roots(&home.path).expect("session roots");
        for root in &roots {
            collect_session_files(&root.lexical, &mut matches).expect("collect session files");
        }
        assert!(
            matches.iter().all(|path| path

                .file_stem()
                .and_then(|s| s.to_str())
                .is_some_and(is_uuid)),
            "collect_session_files must never surface a non-UUID-stemmed subagent transcript: {matches:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn rejects_windows_junction_component() {
        let home = TestHome::new();
        let id = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
        let target = home.path.join("projects").join("real-project");
        fs::create_dir_all(&target).expect("create junction target");
        fs::write(target.join(format!("{id}.jsonl")), "{}\n")
            .expect("write junction session fixture");
        let junction = home.path.join("projects").join("linked-project");
        let output = std::process::Command::new("cmd.exe")
            .args(["/C", "mklink", "/J"])
            .arg(&junction)
            .arg(&target)
            .output()
            .expect("invoke mklink");
        assert!(
            output.status.success(),
            "mklink failed: {}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );

        let linked_session = junction.join(format!("{id}.jsonl"));
        let error = resolve_session_path(
            linked_session.to_str().expect("UTF-8 junction path"),
            &home.path,
        )
        .expect_err("junction component must fail")
        .to_string();
        assert!(
            error.contains("symlink"),
            "unexpected junction error: {error}"
        );

        fs::remove_dir(&junction).expect("remove junction fixture");
    }

    // ------------------------------------------------------------------
    // Byte-budgeted reads
    // ------------------------------------------------------------------

    #[test]
    fn read_tail_lines_returns_whole_file_when_under_budget() {
        let home = TestHome::new();
        let path = home.session_with_content(
            "projects/project-a",
            "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",
            "line-one\nline-two\nline-three\n",
        );
        let (lines, truncated) = read_tail_lines(&path, 4096).expect("read tail");
        assert_eq!(lines, vec!["line-one", "line-two", "line-three"]);
        assert!(!truncated);
    }

    #[test]
    fn read_tail_lines_drops_partial_leading_line_and_reports_truncated() {
        let home = TestHome::new();
        // Each line is 10 bytes ("lineNNN\n"). A budget smaller than the
        // whole file must land the seek mid-line at least once.
        let mut content = String::new();
        for index in 0..50 {
            content.push_str(&format!("line{index:03}\n"));
        }
        let path = home.session_with_content(
            "projects/project-a",
            "ffffffff-ffff-4fff-8fff-ffffffffffff",
            &content,
        );
        let (lines, truncated) = read_tail_lines(&path, 25).expect("read tail");
        assert!(truncated);
        // No partial ("torn") line survives, and every surviving line is a
        // real, complete, unbroken record from the original content.
        for line in &lines {
            assert!(content.lines().any(|full| full == line), "unexpected partial line: {line}");
        }
        assert_eq!(lines.last().map(String::as_str), Some("line049"));
    }

    #[test]
    fn read_head_lines_drops_partial_trailing_line() {
        let home = TestHome::new();
        let path = home.session_with_content(
            "projects/project-a",
            "11111111-1111-4111-8111-111111111111",
            "line-one\nline-two\nline-three\n",
        );
        // Budget lands inside "line-two".
        let lines = read_head_lines(&path, 12).expect("read head");
        assert_eq!(lines, vec!["line-one"]);
    }

    // ------------------------------------------------------------------
    // Topic detection (D3)
    // ------------------------------------------------------------------

    fn event(json: &str) -> SessionEvent {
        serde_json::from_str(json).expect("fixture event must parse")
    }

    #[test]
    fn detect_topic_prefers_custom_title_over_everything() {
        let tail = vec![
            event(r#"{"type":"last-prompt","lastPrompt":"placeholder prompt","sessionId":"s"}"#),
            event(r#"{"type":"ai-title","aiTitle":"placeholder ai title","sessionId":"s"}"#),
            event(r#"{"type":"custom-title","customTitle":"placeholder custom title","sessionId":"s"}"#),
        ];
        let (topic, source) = detect_topic(&[], &tail);
        assert_eq!(topic, "placeholder custom title");
        assert_eq!(source.to_string(), "custom_title");
    }

    #[test]
    fn detect_topic_falls_back_to_ai_title_then_last_prompt() {
        let ai_only = vec![event(
            r#"{"type":"ai-title","aiTitle":"placeholder ai title","sessionId":"s"}"#,
        )];
        assert_eq!(detect_topic(&[], &ai_only).0, "placeholder ai title");

        let last_prompt_only = vec![event(
            r#"{"type":"last-prompt","lastPrompt":"placeholder prompt","sessionId":"s"}"#,
        )];
        let (topic, source) = detect_topic(&[], &last_prompt_only);
        assert_eq!(topic, "placeholder prompt");
        assert_eq!(source.to_string(), "last_prompt");
    }

    #[test]
    fn detect_topic_falls_back_to_head_window_then_first_human_prompt() {
        let head = vec![event(
            r#"{"type":"custom-title","customTitle":"placeholder head title","sessionId":"s"}"#,
        )];
        let (topic, source) = detect_topic(&head, &[]);
        assert_eq!(topic, "placeholder head title");
        assert_eq!(source.to_string(), "custom_title");

        let head_prompt_only = vec![event(
            r#"{"type":"user","uuid":"u","sessionId":"s","timestamp":"2024-01-01T00:00:00Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder first prompt"}}"#,
        )];
        let (topic, source) = detect_topic(&head_prompt_only, &[]);
        assert_eq!(topic, "placeholder first prompt");
        assert_eq!(source.to_string(), "first_prompt");
    }

    #[test]
    fn detect_topic_none_when_nothing_present() {
        let (topic, source) = detect_topic(&[], &[]);
        assert_eq!(topic, "Empty session");
        assert_eq!(source.to_string(), "none");
    }

    #[test]
    fn detect_topic_takes_the_last_custom_title_when_it_repeats() {
        let tail = vec![
            event(r#"{"type":"custom-title","customTitle":"placeholder first","sessionId":"s"}"#),
            event(r#"{"type":"custom-title","customTitle":"placeholder second","sessionId":"s"}"#),
        ];
        assert_eq!(detect_topic(&[], &tail).0, "placeholder second");
    }

    // ------------------------------------------------------------------
    // Tool-call key-argument descriptions
    // ------------------------------------------------------------------

    #[test]
    fn describe_tool_use_extracts_key_arguments() {
        assert_eq!(
            describe_tool_use("Bash", &serde_json::json!({"command": "cargo build --release"})),
            "Bash: cargo build --release"
        );
        assert_eq!(
            describe_tool_use("Read", &serde_json::json!({"file_path": "/work/src/lib.rs"})),
            "Read: /work/src/lib.rs"
        );
        assert_eq!(
            describe_tool_use("Grep", &serde_json::json!({"pattern": "fn main"})),
            "Grep: fn main"
        );
        assert_eq!(describe_tool_use("TodoWrite", &serde_json::json!({})), "TodoWrite");
    }

    // ------------------------------------------------------------------
    // Digest extraction end to end (fixture built from real event shapes,
    // content redacted to placeholders)
    // ------------------------------------------------------------------

    #[test]
    fn build_digest_produces_verbatim_quotes_and_skips_injections() {
        let home = TestHome::new();
        let lines = [
            r#"{"type":"custom-title","customTitle":"placeholder session title","sessionId":"s"}"#.to_string(),
            r#"{"type":"user","uuid":"u1","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:00Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder human prompt"}}"#.to_string(),
            r#"{"type":"user","uuid":"u2","parentUuid":"u1","sessionId":"s","timestamp":"2024-01-01T00:00:01Z","isSidechain":false,"userType":"external","isMeta":true,"cwd":"/work","message":{"role":"user","content":"<local-command-caveat>placeholder caveat</local-command-caveat>"}}"#.to_string(),
            r#"{"type":"assistant","uuid":"a1","parentUuid":"u1","sessionId":"s","timestamp":"2024-01-01T00:00:02Z","isSidechain":false,"cwd":"/work","message":{"model":"claude-test","id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"placeholder assistant reply"},{"type":"tool_use","id":"tool-1","name":"Bash","input":{"command":"cargo build --release"}}]}}"#.to_string(),
            r#"{"type":"system","subtype":"error","uuid":"sys1","parentUuid":"a1","sessionId":"s","timestamp":"2024-01-01T00:00:03Z","isSidechain":false,"cwd":"/work","level":"error","content":"placeholder error text","error":{"type":"overloaded_error","message":"placeholder overload"}}"#.to_string(),
        ];
        let path = home.session_with_content(
            "projects/project-a",
            "22222222-2222-4222-8222-222222222222",
            &lines.join("\n"),
        );

        let digest = build_digest(&path, &load_limits(false)).expect("build digest");
        assert_eq!(digest.topic, "placeholder session title");
        assert_eq!(digest.topic_source, "custom_title");
        assert_eq!(digest.user_messages, vec!["placeholder human prompt".to_string()]);
        assert_eq!(digest.assistant_texts, vec!["placeholder assistant reply".to_string()]);
        assert_eq!(digest.tool_operations, vec!["Bash: cargo build --release".to_string()]);
        assert_eq!(digest.errors, vec!["overloaded_error: placeholder overload".to_string()]);
    }

    #[test]
    fn build_digest_windows_to_events_after_the_last_compact_boundary() {
        let home = TestHome::new();
        let lines = [
            r#"{"type":"user","uuid":"u1","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:00Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder before boundary"}}"#.to_string(),
            r#"{"type":"system","subtype":"compact_boundary","uuid":"boundary1","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:01Z","isSidechain":false,"cwd":"/work","compactMetadata":{"trigger":"auto","preTokens":1000}}"#.to_string(),
            r#"{"type":"user","uuid":"u2","parentUuid":"boundary1","sessionId":"s","timestamp":"2024-01-01T00:00:02Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder after boundary"}}"#.to_string(),
        ];
        let path = home.session_with_content(
            "projects/project-a",
            "33333333-3333-4333-8333-333333333333",
            &lines.join("\n"),
        );

        let digest = build_digest(&path, &load_limits(false)).expect("build digest");
        assert_eq!(digest.user_messages, vec!["placeholder after boundary".to_string()]);
    }

    #[test]
    fn count_unknown_root_types_ignores_modeled_types() {
        let lines = vec![
            r#"{"type":"user","message":{"role":"user","content":"x"}}"#.to_string(),
            r#"{"type":"some-future-event"}"#.to_string(),
            r#"{"type":"some-future-event"}"#.to_string(),
            r#"{"type":"another-future-event"}"#.to_string(),
        ];
        let counts = count_unknown_root_types(&lines);
        assert_eq!(
            counts,
            vec![
                ("some-future-event".to_string(), 2),
                ("another-future-event".to_string(), 1),
            ]
        );
    }

    // ------------------------------------------------------------------
    // Round 2: harness-notification filtering, tail-not-head capping,
    // slash-command rendering, and local-time display.
    // ------------------------------------------------------------------

    #[test]
    fn last_n_returns_the_tail_slice() {
        let items: Vec<String> = ["a", "b", "c", "d"].iter().map(|s| (*s).to_string()).collect();
        assert_eq!(last_n(&items, 2), ["c".to_string(), "d".to_string()]);
        assert_eq!(last_n(&items, 10), items.as_slice());
        assert_eq!(last_n(&items, 0), Vec::<String>::new().as_slice());
    }

    #[test]
    fn truncate_to_last_keeps_the_tail_not_the_head() {
        // This is the exact bug reported live: a front-biased cap kept the
        // earliest N messages of a long window, so `list`'s preview showed
        // two near-duplicate early prompts and never the session's actual
        // latest activity.
        let mut items: Vec<String> = (0..7).map(|i| i.to_string()).collect();
        truncate_to_last(&mut items, 3);
        assert_eq!(items, vec!["4".to_string(), "5".to_string(), "6".to_string()]);
    }

    #[test]
    fn truncate_to_last_is_a_no_op_under_the_cap() {
        let mut items = vec!["a".to_string(), "b".to_string()];
        truncate_to_last(&mut items, 5);
        assert_eq!(items, vec!["a".to_string(), "b".to_string()]);
    }

    #[test]
    fn truncate_reporting_marks_cut_length() {
        let (text, cut) = truncate_reporting("hello world", 5);
        assert_eq!(text, "hello");
        assert_eq!(cut, Some(6));

        let (text, cut) = truncate_reporting("hi", 5);
        assert_eq!(text, "hi");
        assert_eq!(cut, None);
    }

    #[test]
    fn render_slash_command_formats_name_and_args() {
        assert_eq!(render_slash_command("/model", "placeholder-model"), "/model placeholder-model");
        assert_eq!(render_slash_command("/compact", ""), "/compact");
        assert_eq!(render_slash_command("/compact", "   "), "/compact");
    }

    #[test]
    fn local_time_preserves_the_instant() {
        let utc = DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("valid timestamp");
        let local = local_time(&utc);
        assert_eq!(local.timestamp(), utc.timestamp());
    }

    #[test]
    fn build_digest_excludes_harness_notifications_and_renders_slash_commands() {
        let home = TestHome::new();
        // Real shapes, content redacted to placeholders: a genuine prompt, a
        // task-notification (by origin.kind), a compact-summary turn (by
        // isCompactSummary), a peer/cross-session message (by origin.kind),
        // a local-command-stdout echo, and two slash commands (with and
        // without arguments).
        let lines = [
            r#"{"type":"custom-title","customTitle":"placeholder session title","sessionId":"s"}"#.to_string(),
            r#"{"type":"user","uuid":"u1","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:00Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder genuine prompt"}}"#.to_string(),
            r#"{"type":"user","uuid":"u2","parentUuid":"u1","sessionId":"s","timestamp":"2024-01-01T00:00:01Z","isSidechain":false,"userType":"external","origin":{"kind":"task-notification"},"cwd":"/work","message":{"role":"user","content":"placeholder task result, not a real prompt"}}"#.to_string(),
            r#"{"type":"user","uuid":"u3","parentUuid":"u2","sessionId":"s","timestamp":"2024-01-01T00:00:02Z","isSidechain":false,"userType":"external","isCompactSummary":true,"cwd":"/work","message":{"role":"user","content":"This session is being continued from a previous conversation: placeholder summary"}}"#.to_string(),
            r#"{"type":"user","uuid":"u4","parentUuid":"u3","sessionId":"s","timestamp":"2024-01-01T00:00:03Z","isSidechain":false,"userType":"external","isMeta":true,"origin":{"kind":"peer"},"cwd":"/work","message":{"role":"user","content":"Another Claude session sent a message: placeholder"}}"#.to_string(),
            r#"{"type":"user","uuid":"u5","parentUuid":"u4","sessionId":"s","timestamp":"2024-01-01T00:00:04Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"<local-command-stdout>Set model to placeholder</local-command-stdout>"}}"#.to_string(),
            r#"{"type":"user","uuid":"u6","parentUuid":"u5","sessionId":"s","timestamp":"2024-01-01T00:00:05Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"<command-name>/model</command-name>\n<command-message>model</command-message>\n<command-args>placeholder-model</command-args>"}}"#.to_string(),
            r#"{"type":"user","uuid":"u7","parentUuid":"u6","sessionId":"s","timestamp":"2024-01-01T00:00:06Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"<command-name>/compact</command-name>\n<command-message>compact</command-message>\n<command-args></command-args>"}}"#.to_string(),
        ];
        let path = home.session_with_content(
            "projects/project-a",
            "44444444-4444-4444-8444-444444444444",
            &lines.join("\n"),
        );

        let digest = build_digest(&path, &load_limits(false)).expect("build digest");
        assert_eq!(
            digest.user_messages,
            vec![
                "placeholder genuine prompt".to_string(),
                "/model placeholder-model".to_string(),
                "/compact".to_string(),
            ]
        );
        assert_eq!(digest.harness_notifications_skipped, 4);
    }

    #[test]
    fn build_digest_keeps_the_latest_messages_when_the_window_exceeds_the_cap() {
        // Reproduces the reported bug end to end: three near-duplicate early
        // prompts, an excluded task notification, then two later distinct
        // prompts. `LIST_LIMITS` caps at 5 real messages; the two most
        // recent (not the three earliest) must survive.
        let home = TestHome::new();
        let mut lines = vec![
            r#"{"type":"custom-title","customTitle":"placeholder title","sessionId":"s"}"#.to_string(),
        ];
        for (i, text) in [
            "placeholder repeated request",
            "placeholder repeated request",
            "placeholder repeated request",
        ]
        .iter()
        .enumerate()
        {
            lines.push(format!(
                r#"{{"type":"user","uuid":"u{i}","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:0{i}Z","isSidechain":false,"userType":"external","cwd":"/work","message":{{"role":"user","content":"{text}"}}}}"#
            ));
        }
        lines.push(r#"{"type":"user","uuid":"u-notif","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:04Z","isSidechain":false,"userType":"external","origin":{"kind":"task-notification"},"cwd":"/work","message":{"role":"user","content":"placeholder notification"}}"#.to_string());
        lines.push(r#"{"type":"user","uuid":"u-later","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:05Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder later question"}}"#.to_string());
        lines.push(r#"{"type":"user","uuid":"u-final","parentUuid":null,"sessionId":"s","timestamp":"2024-01-01T00:00:06Z","isSidechain":false,"userType":"external","cwd":"/work","message":{"role":"user","content":"placeholder final instruction"}}"#.to_string());

        let path = home.session_with_content(
            "projects/project-a",
            "55555555-5555-4555-8555-555555555555",
            &lines.join("\n"),
        );

        let digest = build_digest(&path, &LIST_LIMITS).expect("build digest");
        assert_eq!(digest.harness_notifications_skipped, 1);
        assert_eq!(
            digest.user_messages,
            vec![
                "placeholder repeated request".to_string(),
                "placeholder repeated request".to_string(),
                "placeholder repeated request".to_string(),
                "placeholder later question".to_string(),
                "placeholder final instruction".to_string(),
            ]
        );
        // The list preview shows the *last* two, not the first two.
        assert_eq!(
            last_n(&digest.user_messages, 2),
            [
                "placeholder later question".to_string(),
                "placeholder final instruction".to_string(),
            ]
        );
    }
}