claude-session-parser 0.2.4

Streaming parser for Claude Code session JSONL files: token usage, chat events, and activity classification.
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
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
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
use chrono::DateTime;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use super::activity::{classify, normalize_user_text, Activity};

/// Pricing per 1M tokens (USD) by model family.
///
/// Anthropic bills three prompt-cache tiers off the base input rate:
/// 5-minute cache write = 1.25× input, 1-hour cache write = 2× input,
/// cache read = 0.1× input. `cache_write` is the 5-minute rate (Claude Code's
/// historical default); `cache_write_1h` is the 1-hour rate. Claude Code now
/// emits `usage.cache_creation.ephemeral_1h_input_tokens` for the 1-hour
/// portion, so the two must be priced separately or 1h writes undercount ~38%.
pub struct ModelPricing {
    pub input: f64,
    pub output: f64,
    pub cache_read: f64,
    /// 5-minute cache write (1.25× input).
    pub cache_write: f64,
    /// 1-hour cache write (2× input).
    pub cache_write_1h: f64,
}

/// `(major, minor)` of the version that follows `family` in a
/// `claude-<family>-<major>[-<minor>][-<yyyymmdd>]` id, or `None` when no
/// parseable version follows it (aliases like `"fable"`, legacy
/// `claude-3-5-sonnet-…` forms, `<synthetic>`).
///
/// An 8-digit segment is a date snapshot, not a minor version, so
/// `claude-sonnet-5-20260701` is `(5, 0)` while `claude-haiku-4-5-20251001`
/// is `(4, 5)`. Callers compare with `>=` so an unrecognised future version
/// prices as the newest tier we know about rather than the oldest.
///
/// A trailing context-window tag (`claude-opus-5-5[1m]`) is dropped first:
/// left in, it glues onto the last version segment and reads as `(5, 0)` —
/// or fails the parse outright for `claude-sonnet-5[1m]`.
fn family_version(model: &str, family: &str) -> Option<(u32, u32)> {
    fn is_date(p: &str) -> bool {
        p.len() == 8 && p.bytes().all(|b| b.is_ascii_digit())
    }
    let model = model.split('[').next().unwrap_or(model);
    let rest = model.split_once(family)?.1.strip_prefix('-')?;
    let mut parts = rest.split('-');
    let head = parts.next()?;
    // Legacy ids put the version *before* the family (`claude-3-5-sonnet-…`),
    // so what follows is a date snapshot, not a version. Reject it rather than
    // reading 20241022 as major version 20241022.
    if is_date(head) {
        return None;
    }
    let major: u32 = head.parse().ok()?;
    let minor = match parts.next() {
        Some(p) if is_date(p) => 0,
        Some(p) => p.parse().unwrap_or(0),
        None => 0,
    };
    Some((major, minor))
}

/// Haiku 5.5 bills by prompt size: prompts over this many tokens pay the
/// long-context tier. The docs don't say which token classes count; we use
/// input + cache reads + cache writes (see `pricing_for_entry`).
const HAIKU_LONG_PROMPT_TOKENS: u64 = 100_000;

fn is_haiku_5_5(model: &str) -> bool {
    matches!(family_version(model, "haiku"), Some(v) if v >= (5, 5))
}

fn haiku_5_5_pricing(long_prompt: bool) -> ModelPricing {
    if long_prompt {
        ModelPricing {
            input: 0.5,
            output: 2.5,
            cache_read: 0.05,
            cache_write: 0.625,
            cache_write_1h: 1.0,
        }
    } else {
        ModelPricing {
            input: 0.1,
            output: 0.5,
            cache_read: 0.01,
            cache_write: 0.125,
            cache_write_1h: 0.2,
        }
    }
}

/// Hardcoded as of 2026-10. Requires a code change + release when Anthropic updates pricing.
///
/// Four families price by version, so the id must carry one to get the newer
/// rate — an alias (`"fable"`, `"opus"`, `"sonnet"`) prices as the older tier:
/// - **Fable 5.1+** reads cache at 0.025× input ($0.25/MTok) instead of the
///   standard 0.1× ($1/MTok) that Fable 5 pays. Everything else is identical.
/// - **Opus 5.5+** is $4/$20 and reads cache at 0.05× input ($0.20/MTok);
///   Opus 5 and earlier stay at $5/$25 with the standard 0.1× read.
/// - **Sonnet 5+** is $2/$10; Sonnet 4.6 and earlier stay at $3/$15. The $2/$10
///   launch price became Sonnet 5's standard price on 2026-09-01 — the
///   scheduled increase to $3/$15 was cancelled.
/// - **Haiku 5.5+** is $0.10/$0.50 for prompts up to 100k tokens and 5× that
///   above it; this returns the up-to-100k tier, and `pricing_for_entry`
///   applies the long-prompt tier. Haiku 4.5 and the `"haiku"` alias stay at $1/$5.
pub fn pricing_for_model(model: &str) -> ModelPricing {
    if model.contains("fable") {
        // Fable 5 / 5.1: $10/$50 per MTok. Writes derive from input at the
        // standard multipliers (1.25× 5m, 2× 1h); only the read rate moved.
        let cache_read = match family_version(model, "fable") {
            Some(v) if v >= (5, 1) => 0.25,
            _ => 1.0,
        };
        ModelPricing {
            input: 10.0,
            output: 50.0,
            cache_read,
            cache_write: 12.5,
            cache_write_1h: 20.0,
        }
    } else if matches!(family_version(model, "opus"), Some(v) if v >= (5, 5)) {
        // Opus 5.5: $4/$20, writes at the standard multipliers, reads at
        // 0.05× input rather than 0.1×.
        ModelPricing {
            input: 4.0,
            output: 20.0,
            cache_read: 0.2,
            cache_write: 5.0,
            cache_write_1h: 8.0,
        }
    } else if model.contains("opus") {
        ModelPricing {
            input: 5.0,
            output: 25.0,
            cache_read: 0.5,
            cache_write: 6.25,
            cache_write_1h: 10.0,
        }
    } else if is_haiku_5_5(model) {
        haiku_5_5_pricing(false)
    } else if model.contains("haiku") {
        ModelPricing {
            input: 1.0,
            output: 5.0,
            cache_read: 0.1,
            cache_write: 1.25,
            cache_write_1h: 2.0,
        }
    } else if matches!(family_version(model, "sonnet"), Some(v) if v >= (5, 0)) {
        ModelPricing {
            input: 2.0,
            output: 10.0,
            cache_read: 0.2,
            cache_write: 2.5,
            cache_write_1h: 4.0,
        }
    } else {
        // Sonnet 4.6 and earlier, or unknown
        ModelPricing {
            input: 3.0,
            output: 15.0,
            cache_read: 0.3,
            cache_write: 3.75,
            cache_write_1h: 6.0,
        }
    }
}

/// Per-turn rates: `pricing_for_model`, except Haiku 5.5+ turns whose prompt
/// (input + cache reads + cache writes) exceeds 100k tokens, which bill the
/// long-prompt tier. Unverified: Anthropic's pricing page doesn't say which
/// token classes count toward the threshold.
pub fn pricing_for_entry(entry: &UsageEntry) -> ModelPricing {
    let prompt = entry.input_tokens + entry.cache_read_tokens + entry.cache_write_tokens;
    if is_haiku_5_5(&entry.model) && prompt > HAIKU_LONG_PROMPT_TOKENS {
        haiku_5_5_pricing(true)
    } else {
        pricing_for_model(&entry.model)
    }
}

/// Flat fee per Anthropic web-search server-tool request ($10 per 1,000 = $0.01).
pub const WEB_SEARCH_COST_PER_REQUEST: f64 = 0.01;

/// Fast-mode (research preview) cost multiplier, applied to the entire token
/// cost line when `usage.speed == "fast"`. Fast mode is Opus-only and its
/// premium varies by version (confirmed Anthropic pricing, 2026-09):
/// - Opus 4.6 / 4.7 fast: 6× ($30/$150 vs $5/$25)
/// - Opus 4.8 / 5 fast:   2× ($10/$50 vs $5/$25)
/// - Opus 5.5 fast:       2× ($8/$40 vs $4/$20)
///
/// Caching multipliers stack on top of fast pricing, i.e. fast scales the whole
/// per-token line (input, output, and the cache rates that derive from input).
/// Unknown / unsupported models return 1.0 (no premium) so we never overcount
/// on a guess — newer Opus releases default here until their multiplier is added.
/// Fable has no fast-mode variant (fast is Opus-only) → 1.0.
pub fn fast_multiplier_for_model(model: &str) -> f64 {
    if model.contains("opus-4-8") || model.contains("opus-5") {
        2.0
    } else if model.contains("opus-4-7") || model.contains("opus-4-6") {
        6.0
    } else {
        1.0
    }
}

/// Single source of truth for per-turn cost (USD), used by both the live status
/// bar (`reduce_session`) and the Usage page (`commands::usage`).
///
/// Splits cache-write tokens into 5-minute and 1-hour tiers, applies the
/// fast-mode multiplier to the token line when the turn ran in fast mode, and
/// adds the flat web-search fee (which is not a token cost and so is unaffected
/// by the fast multiplier).
pub fn cost_for_entry(entry: &UsageEntry) -> f64 {
    let p = pricing_for_entry(entry);
    let cw_1h = entry.cache_write_1h_tokens.min(entry.cache_write_tokens);
    let cw_5m = entry.cache_write_tokens - cw_1h;
    let token_cost = entry.input_tokens as f64 * p.input
        + entry.output_tokens as f64 * p.output
        + entry.cache_read_tokens as f64 * p.cache_read
        + cw_5m as f64 * p.cache_write
        + cw_1h as f64 * p.cache_write_1h;
    let fast = if entry.speed.as_deref() == Some("fast") {
        fast_multiplier_for_model(&entry.model)
    } else {
        1.0
    };
    (token_cost * fast) / 1_000_000.0
        + entry.web_search_requests as f64 * WEB_SEARCH_COST_PER_REQUEST
}

pub fn context_window_for_model(model: &str) -> u64 {
    // Fable 5 and Haiku 5.5 are natively 1M — there is no `[1m]` suffix variant.
    if model.contains("[1m]") || model.contains("fable") || is_haiku_5_5(model) {
        1_000_000
    } else {
        200_000
    }
}

/// Flat row representing a single completed assistant turn.
///
/// One entry per unique `message.id`. Claude Code writes multiple JSONL
/// entries per assistant message as the stream progresses (typically 2-3),
/// all sharing the same `id` and final usage numbers — dedup keeps only the
/// first occurrence.
///
/// Token field semantics (inherited from Anthropic's API):
/// - `input_tokens`: *fresh* tokens in this turn's prompt that were NOT served
///   from cache. Small when conversation is reused, large on cache misses.
/// - `cache_read_tokens`: tokens served from the prompt cache (cheap).
/// - `cache_write_tokens`: tokens written into the prompt cache (~25% premium).
/// - `output_tokens`: tokens generated by the model.
///
/// "Total context sent" for a turn = input + cache_read + cache_write.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UsageEntry {
    pub session_id: String,
    /// Unix epoch ms from the JSONL `timestamp` field. 0 if unparseable.
    pub timestamp_ms: u64,
    pub model: String,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    /// Total cache-write (creation) tokens for this turn: `max(legacy flat
    /// `cache_creation_input_tokens`, ephemeral_5m + ephemeral_1h)`. The 1-hour
    /// subset is broken out separately in `cache_write_1h_tokens` for pricing;
    /// this total still drives cache-hit % and token displays.
    pub cache_write_tokens: u64,
    /// The 1-hour-TTL portion of `cache_write_tokens` (from
    /// `usage.cache_creation.ephemeral_1h_input_tokens`). Billed at 2× input
    /// vs the 5-minute tier's 1.25×. The 5-minute portion is the remainder.
    #[serde(default)]
    pub cache_write_1h_tokens: u64,
    /// Anthropic web-search server-tool requests this turn
    /// (`usage.server_tool_use.web_search_requests`). Billed flat at $0.01 each.
    #[serde(default)]
    pub web_search_requests: u64,
    /// `usage.speed`: `"standard"` or `"fast"`. `Some("fast")` applies the
    /// fast-mode cost multiplier (see `fast_multiplier_for_model`). `None` on
    /// rows that predate the field.
    #[serde(default)]
    pub speed: Option<String>,
    /// Names of tools this turn invoked (from `tool_use` content blocks).
    /// Empty for pure-text turns. Duplicates preserved when the model called
    /// the same tool multiple times in one turn.
    pub tool_uses: Vec<String>,
    /// Sum of `text` content block character counts for this turn. Zero means
    /// a silent tool-only turn; non-zero means the model said something.
    pub text_chars: u32,
    /// Classified activity category (Coding, Debugging, Exploration, …).
    /// See the [`crate::activity`] module for the decision tree.
    pub activity: Activity,
    /// JSONL `entrypoint` field captured from the first row of each message id.
    /// `"cli"` = interactive Claude Code session. `"sdk-cli"` = headless
    /// `claude -p` spawn (any Agent SDK consumer lands here). `None` for legacy
    /// rows that predate the field. Useful for distinguishing interactive vs.
    /// headless usage; also load-bearing once Anthropic splits Agent SDK
    /// billing from interactive plans (announced June 2026).
    pub entrypoint: Option<String>,
}

/// A single hook execution event from a `type: "attachment"` JSONL record
/// where `attachment.type == "hook_success"`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HookExecution {
    pub session_id: String,
    pub timestamp_ms: u64,
    /// Lifecycle phase: `PreToolUse`, `PostToolUse`, `SessionStart`, `Stop`, etc.
    pub hook_event: String,
    /// Full hook label including matcher: `PreToolUse:Bash`, `Stop`, etc.
    pub hook_name: String,
    /// The shell command that was executed.
    pub command: String,
    pub exit_code: i32,
    pub duration_ms: u64,
    /// The tool-use ID that triggered this hook (groups multiple hooks per tool call).
    pub tool_use_id: Option<String>,
}

/// Combined result from parsing a single JSONL file.
#[derive(Default)]
pub struct ParsedJsonl {
    pub entries: Vec<UsageEntry>,
    pub hooks: Vec<HookExecution>,
}

/// Usage summary for a single session, returned to the frontend status bar.
#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SessionUsage {
    pub model: String,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub total_tokens: u64,
    pub estimated_cost_usd: f64,
    pub context_window_size: u64,
    pub context_window_used_pct: f64,
    /// Last message's total input context (current context window usage).
    pub current_context_tokens: u64,
    /// Cumulative context sent (input + cache_read + cache_write).
    pub total_context_sent: u64,
    /// cache_read / (input + cache_read), in percent. 0 when no cache activity.
    pub cache_hit_pct: f64,
    pub message_count: u64,
    pub session_id: String,
}

/// Minimal JSONL entry structure.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JsonlRaw {
    #[serde(rename = "type")]
    entry_type: Option<String>,
    timestamp: Option<String>,
    message: Option<MessageData>,
    attachment: Option<AttachmentData>,
    // Fields for `type: "system"` hook summary records (v2.1.119+).
    subtype: Option<String>,
    #[allow(dead_code)]
    hook_count: Option<usize>,
    hook_infos: Option<Vec<HookInfoEntry>>,
    hook_errors: Option<Vec<serde_json::Value>>,
    prevented_continuation: Option<bool>,
    #[serde(rename = "toolUseID")]
    tool_use_id: Option<String>,
    /// Origin of the session: `"cli"` (interactive Claude Code) or `"sdk-cli"`
    /// (headless `claude -p` / Agent SDK). Present on every assistant + user row.
    entrypoint: Option<String>,
}

#[derive(Deserialize)]
struct MessageData {
    id: Option<String>,
    model: Option<String>,
    usage: Option<UsageData>,
    /// Raw content — assistant messages use `Vec<ContentBlock>`, user messages
    /// use either a string or an array of blocks (including tool_results).
    /// Kept as a raw Value so we can handle both shapes without maintaining
    /// two parallel structs.
    #[serde(default)]
    content: Option<serde_json::Value>,
}

#[derive(Deserialize, Default)]
struct UsageData {
    input_tokens: Option<u64>,
    output_tokens: Option<u64>,
    cache_read_input_tokens: Option<u64>,
    /// Legacy flat total of cache-creation tokens. Still emitted alongside the
    /// nested `cache_creation` split; we take the max of the two for safety.
    cache_creation_input_tokens: Option<u64>,
    /// 5-minute / 1-hour cache-write split (Claude Code ≥ the 1h-cache rollout).
    cache_creation: Option<CacheCreation>,
    /// Server-tool request counts (web search / web fetch).
    server_tool_use: Option<ServerToolUse>,
    /// `"standard"` | `"fast"`. Drives the fast-mode cost multiplier.
    speed: Option<String>,
}

/// Nested `usage.cache_creation` object splitting cache writes by TTL tier.
#[derive(Deserialize, Default)]
struct CacheCreation {
    ephemeral_5m_input_tokens: Option<u64>,
    ephemeral_1h_input_tokens: Option<u64>,
}

/// Nested `usage.server_tool_use` object. Only `web_search_requests` is billable
/// ($0.01/req); `web_fetch_requests` is free and intentionally not priced.
#[derive(Deserialize, Default)]
struct ServerToolUse {
    web_search_requests: Option<u64>,
}

/// Single hook execution in a `hookInfos` array (v2.1.119+ system records).
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct HookInfoEntry {
    command: Option<String>,
    duration_ms: Option<u64>,
}

/// Minimal deserialization of the `attachment` field on `type: "attachment"` rows.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AttachmentData {
    #[serde(rename = "type")]
    attachment_type: Option<String>,
    hook_name: Option<String>,
    hook_event: Option<String>,
    command: Option<String>,
    exit_code: Option<i32>,
    duration_ms: Option<u64>,
    #[serde(rename = "toolUseID")]
    tool_use_id: Option<String>,
}

/// Claude Code active session file in `{config_dir}/sessions/{pid}.json`.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ActiveSession {
    session_id: String,
    cwd: String,
    started_at: u64,
}

/// Hard cap to avoid pathological parsing of a corrupted file.
///
/// Parsing is streaming (`BufReader::lines()`) so memory is O(1) per line —
/// the cap only exists to keep a runaway file from blocking the UI. Real
/// agent sessions (Task-tool sub-agents) frequently exceed 30MB, so the cap
/// needs generous headroom.
use super::MAX_JSONL_BYTES;

/// Encode a project path the same way Claude Code does.
///
/// Windows: `S:\Loom` -> `S--Loom`, `C:\Users\Seven\foo` -> `C--Users-Seven-foo`
/// macOS/Linux: `/Users/seven/Loom` -> `-Users-seven-Loom`, `/home/alice/proj` -> `-home-alice-proj`
///
/// The transform collapses any leading path separator(s) into a single leading
/// dash, which is how Claude Code writes `~/.claude/projects/` directory names
/// on Unix. Verified against ccusage's decoder (see GitHub issue
/// anthropics/claude-code#19972 for the path-encoding discussion).
pub fn encode_project_path(project_path: &str) -> String {
    let normalized = project_path.replace('/', "\\");
    let mut result = String::new();
    let mut chars = normalized.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == ':' {
            if chars.peek() == Some(&'\\') {
                chars.next();
                result.push_str("--");
            } else {
                result.push('-');
            }
        } else if ch == '\\' {
            result.push('-');
        } else {
            result.push(ch);
        }
    }

    while result.ends_with('-') {
        result.pop();
    }

    result
}

/// Extracted signal from an assistant message's `content` array.
struct AssistantContent {
    tool_uses: Vec<String>,
    bash_cmds: Vec<String>,
    text_chars: u32,
}

/// Walk an assistant message's content blocks to pull out tool names, any
/// bash-style commands (used by the classifier for Testing/GitOps/Build
/// detection), and the total character count of `text` blocks.
fn extract_assistant_content(content: Option<&serde_json::Value>) -> AssistantContent {
    let mut out = AssistantContent {
        tool_uses: Vec::new(),
        bash_cmds: Vec::new(),
        text_chars: 0,
    };
    let arr = match content.and_then(|v| v.as_array()) {
        Some(a) => a,
        None => return out,
    };

    for block in arr {
        let block_type = match block.get("type").and_then(|v| v.as_str()) {
            Some(t) => t,
            None => continue,
        };
        match block_type {
            "tool_use" => {
                if let Some(name) = block.get("name").and_then(|v| v.as_str()) {
                    // If this is a Bash-family tool, grab the command string so
                    // the classifier can distinguish Testing / GitOps / Build.
                    if matches!(name, "Bash" | "BashTool" | "PowerShellTool") {
                        if let Some(cmd) = block
                            .get("input")
                            .and_then(|i| i.get("command"))
                            .and_then(|c| c.as_str())
                        {
                            out.bash_cmds.push(cmd.to_string());
                        }
                    }
                    out.tool_uses.push(name.to_string());
                }
            }
            "text" => {
                if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
                    // Saturating because a single turn's text can exceed u32
                    // only in pathological cases (would be >4 GB of text).
                    out.text_chars = out
                        .text_chars
                        .saturating_add(text.chars().count() as u32);
                }
            }
            _ => {}
        }
    }

    out
}

/// Extract the human-typed portion of a user message's content, if any.
///
/// User rows in Claude Code JSONL carry two distinct shapes:
/// - A plain string (`"content": "hello"`) — always a real user turn.
/// - An array of content blocks, which may be:
///   - `[{"type":"text","text":"..."}]` → real user turn
///   - `[{"type":"tool_result",...}]` → injected tool output, NOT a user turn
///   - Mixed → treated as a real user turn
///
/// Sanitize the per-hook `command` for use inside a synthesized `hook_name`
/// bucket key. Takes the first line, collapses internal whitespace, and caps
/// at 64 chars (with `…` suffix). The full command is preserved separately on
/// the `HookExecution.command` field — this only affects the display label /
/// aggregation key used by the Usage page and Refinery hook stats.
///
/// Without this, `/goal`-style hooks whose "command" is a multi-KB goal
/// statement explode the hook-table layout AND defeat aggregation (one bucket
/// per invocation).
fn sanitize_hook_command_label(cmd: &str) -> String {
    const MAX_LEN: usize = 64;
    let first_line = cmd.lines().next().unwrap_or("").trim();
    let collapsed: String = first_line.split_whitespace().collect::<Vec<_>>().join(" ");
    if collapsed.chars().count() <= MAX_LEN {
        return collapsed;
    }
    let truncated: String = collapsed.chars().take(MAX_LEN).collect();
    format!("{truncated}…")
}

/// Convert `snake_case` to `PascalCase`: `"stop"` → `"Stop"`, `"pre_tool_use"` → `"PreToolUse"`.
fn snake_to_pascal(s: &str) -> String {
    s.split('_')
        .filter(|w| !w.is_empty())
        .map(|w| {
            let mut c = w.chars();
            match c.next() {
                Some(first) => {
                    let mut out = first.to_uppercase().to_string();
                    out.extend(c);
                    out
                }
                None => String::new(),
            }
        })
        .collect()
}

/// Returns `None` for tool-result-only rows so the rolling `last_user_text`
/// stays pinned to the most recent actual user message.
fn extract_user_text(content: &serde_json::Value) -> Option<String> {
    match content {
        serde_json::Value::String(s) => {
            if s.is_empty() {
                None
            } else {
                Some(s.clone())
            }
        }
        serde_json::Value::Array(arr) => {
            let mut parts: Vec<&str> = Vec::new();
            for item in arr {
                let t = item.get("type").and_then(|v| v.as_str()).unwrap_or("");
                if t == "text" {
                    if let Some(text) = item.get("text").and_then(|v| v.as_str()) {
                        if !text.is_empty() {
                            parts.push(text);
                        }
                    }
                }
            }
            if parts.is_empty() {
                None
            } else {
                Some(parts.join(" "))
            }
        }
        _ => None,
    }
}

/// Per-message-id accumulator for content blocks that arrive split across
/// multiple JSONL rows. See `parse_jsonl_entries` for the why.
struct EntryAccumulator {
    out_idx: usize,
    bash_cmds: Vec<String>,
    user_text_at_first: Option<String>,
}

/// Parse a single JSONL file into one `UsageEntry` per unique `message.id`.
///
/// Pure function: depends only on the file contents. Non-assistant entries,
/// malformed lines, and missing IDs are skipped silently.
///
/// **Dedup is split by field semantics**, because Claude Code emits one JSONL
/// row per assistant content block (thinking / text / each tool_use) all
/// sharing the same `message.id`:
///
/// - Billing fields (token counts, model, timestamp, session_id) come from the
///   **first** row seen for each id — they repeat identically across rows.
/// - Content fields (`tool_uses`, `text_chars`, and the bash commands fed to
///   the activity classifier) are **unioned across every row** with that id,
///   then `activity` is classified once at the end using the merged content.
///
/// Folding only by `message.id` (as this parser did before 2026-05-13) drops
/// every tool_use after the first row, which made the Toolkit and Usage tool
/// counters undercount by an order of magnitude. The chat parser already
/// uses `(message_id + content)` for the same reason — see CLAUDE.md.
///
/// Runs a rolling `last_user_text` cursor during the stream: each genuine
/// `type: "user"` row updates it; the snapshot taken at the **first** row of
/// each assistant message is used for activity classification.
pub fn parse_jsonl_entries(path: &Path) -> std::io::Result<ParsedJsonl> {
    let meta = fs::metadata(path)?;
    if meta.len() > MAX_JSONL_BYTES {
        tracing::warn!(
            path = %path.display(),
            size = meta.len(),
            "skipping JSONL larger than {}MB",
            MAX_JSONL_BYTES / 1024 / 1024
        );
        return Ok(ParsedJsonl::default());
    }

    let file = fs::File::open(path)?;
    let reader = BufReader::new(file);

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

    let mut accums: HashMap<String, EntryAccumulator> = HashMap::new();
    let mut out: Vec<UsageEntry> = Vec::new();
    let mut hooks: Vec<HookExecution> = Vec::new();
    let mut last_user_text: Option<String> = None;

    for line in reader.lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => continue,
        };
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        let raw: JsonlRaw = match serde_json::from_str(line) {
            Ok(r) => r,
            Err(_) => continue,
        };

        let entry_type = raw.entry_type.as_deref();

        // Update the rolling user-message cursor on genuine user turns.
        // Tool-result-only rows (also type="user") leave it untouched.
        if entry_type == Some("user") {
            if let Some(msg) = raw.message.as_ref() {
                if let Some(content) = msg.content.as_ref() {
                    if let Some(text) = extract_user_text(content) {
                        last_user_text = Some(normalize_user_text(&text));
                    }
                }
            }
            continue;
        }

        // Extract hook execution events from attachment records (v2.1.101 format).
        if entry_type == Some("attachment") {
            if let Some(att) = raw.attachment {
                if att.attachment_type.as_deref() == Some("hook_success") {
                    let timestamp_ms = raw
                        .timestamp
                        .as_deref()
                        .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
                        .map(|dt| dt.timestamp_millis().max(0) as u64)
                        .unwrap_or(0);
                    hooks.push(HookExecution {
                        session_id: session_id.clone(),
                        timestamp_ms,
                        hook_event: att.hook_event.unwrap_or_default(),
                        hook_name: att.hook_name.unwrap_or_default(),
                        command: att.command.unwrap_or_default(),
                        exit_code: att.exit_code.unwrap_or(0),
                        duration_ms: att.duration_ms.unwrap_or(0),
                        tool_use_id: att.tool_use_id,
                    });
                }
            }
            continue;
        }

        // Extract hook summaries from system records (v2.1.119+ format).
        // Subtype pattern: "<event>_hook_summary" → hook_event = "<Event>".
        if entry_type == Some("system") {
            if let Some(subtype) = raw.subtype.as_deref() {
                if let Some(event_snake) = subtype.strip_suffix("_hook_summary") {
                    let hook_event = snake_to_pascal(event_snake);
                    let timestamp_ms = raw
                        .timestamp
                        .as_deref()
                        .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
                        .map(|dt| dt.timestamp_millis().max(0) as u64)
                        .unwrap_or(0);
                    let had_errors = raw
                        .hook_errors
                        .as_ref()
                        .is_some_and(|e| !e.is_empty());
                    let prevented = raw.prevented_continuation.unwrap_or(false);
                    if let Some(infos) = raw.hook_infos {
                        for info in infos {
                            let cmd = info.command.unwrap_or_default();
                            let hook_name =
                                format!("{}:{}", hook_event, sanitize_hook_command_label(&cmd));
                            hooks.push(HookExecution {
                                session_id: session_id.clone(),
                                timestamp_ms,
                                hook_event: hook_event.clone(),
                                hook_name,
                                command: cmd,
                                exit_code: if had_errors || prevented { 1 } else { 0 },
                                duration_ms: info.duration_ms.unwrap_or(0),
                                tool_use_id: raw.tool_use_id.clone(),
                            });
                        }
                    }
                }
            }
            continue;
        }

        if entry_type != Some("assistant") {
            continue;
        }

        let msg = match raw.message {
            Some(m) => m,
            None => continue,
        };
        let mid = match msg.id {
            Some(id) => id,
            None => continue,
        };

        let mut content_parsed = extract_assistant_content(msg.content.as_ref());

        // Subsequent row for an already-seen message: union its content into
        // the existing entry. Billing/model/timestamp on the entry stay as-is.
        if let Some(acc) = accums.get_mut(&mid) {
            let entry = &mut out[acc.out_idx];
            entry
                .tool_uses
                .append(&mut content_parsed.tool_uses);
            entry.text_chars = entry
                .text_chars
                .saturating_add(content_parsed.text_chars);
            acc.bash_cmds.append(&mut content_parsed.bash_cmds);
            continue;
        }

        // Skip synthetic entries. Claude Code / the Agent SDK writes
        // `model: "<synthetic>"` rows for internal routing (skill listings,
        // queue ops, tool dispatch, etc.) — these never hit the LLM and have
        // all-zero token counts. Counting them would inflate turn counts
        // without representing real model activity.
        let model = msg.model.unwrap_or_default();
        if model == "<synthetic>" {
            continue;
        }

        let usage = msg.usage.unwrap_or_default();
        let timestamp_ms = raw
            .timestamp
            .as_deref()
            .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
            .map(|dt| dt.timestamp_millis().max(0) as u64)
            .unwrap_or(0);

        // Cache-write tokens: prefer the larger of the legacy flat total and the
        // 5m+1h split (guards partial/missing fields across Claude Code
        // versions). Break out the 1-hour subset for tiered pricing.
        let cw_flat = usage.cache_creation_input_tokens.unwrap_or(0);
        let (eph_5m, eph_1h) = usage
            .cache_creation
            .as_ref()
            .map(|c| {
                (
                    c.ephemeral_5m_input_tokens.unwrap_or(0),
                    c.ephemeral_1h_input_tokens.unwrap_or(0),
                )
            })
            .unwrap_or((0, 0));
        let cache_write_tokens = cw_flat.max(eph_5m + eph_1h);
        let cache_write_1h_tokens = eph_1h.min(cache_write_tokens);
        let web_search_requests = usage
            .server_tool_use
            .as_ref()
            .map(|s| s.web_search_requests.unwrap_or(0))
            .unwrap_or(0);
        let speed = usage.speed.clone();

        // First row for this message: push placeholder entry with the content
        // we've seen so far. Activity is classified at the end of the file
        // against the merged content from all rows sharing this `message.id`.
        accums.insert(
            mid.clone(),
            EntryAccumulator {
                out_idx: out.len(),
                bash_cmds: std::mem::take(&mut content_parsed.bash_cmds),
                user_text_at_first: last_user_text.clone(),
            },
        );
        out.push(UsageEntry {
            session_id: session_id.clone(),
            timestamp_ms,
            model,
            input_tokens: usage.input_tokens.unwrap_or(0),
            output_tokens: usage.output_tokens.unwrap_or(0),
            cache_read_tokens: usage.cache_read_input_tokens.unwrap_or(0),
            cache_write_tokens,
            cache_write_1h_tokens,
            web_search_requests,
            speed,
            tool_uses: content_parsed.tool_uses,
            text_chars: content_parsed.text_chars,
            activity: Activity::General,
            entrypoint: raw.entrypoint.clone(),
        });
    }

    // Classify each accumulated entry using the merged content from all rows
    // that shared its `message.id`. Order doesn't matter — we mutate in place.
    for acc in accums.values() {
        let entry = &mut out[acc.out_idx];
        let tool_refs: Vec<&str> = entry.tool_uses.iter().map(|s| s.as_str()).collect();
        let bash_refs: Vec<&str> = acc.bash_cmds.iter().map(|s| s.as_str()).collect();
        entry.activity = classify(
            &tool_refs,
            &bash_refs,
            acc.user_text_at_first.as_deref(),
            entry.text_chars,
        );
    }

    Ok(ParsedJsonl {
        entries: out,
        hooks,
    })
}

/// Find the JSONL file for the current session by looking up Claude Code's
/// active sessions directory, matching on project path.
/// Falls back to finding the newest JSONL created after `spawned_at`.
pub fn find_current_session_jsonl(
    config_dir: &str,
    project_path: &str,
    spawned_at: SystemTime,
) -> Option<PathBuf> {
    let config = Path::new(config_dir);
    let encoded = encode_project_path(project_path);
    let projects_dir = config.join("projects").join(&encoded);

    if !projects_dir.exists() {
        return None;
    }

    // Strategy 1: Look up Claude Code's sessions/ directory for an active
    // session matching our project path. This gives us the exact session ID.
    let sessions_dir = config.join("sessions");
    if sessions_dir.exists() {
        if let Some(session_id) = find_active_session_id(&sessions_dir, project_path, spawned_at) {
            let jsonl_path = projects_dir.join(format!("{}.jsonl", session_id));
            if jsonl_path.exists() {
                return Some(jsonl_path);
            }
        }
    }

    // Strategy 2: Fall back to finding the earliest-created JSONL after spawn
    // time. "Earliest" is critical: with two concurrent sessions for the same
    // project, the older session must claim the first JSONL created after its
    // spawn, not the latest one (which belongs to the newer session).
    let mut candidates: Vec<(PathBuf, SystemTime)> = Vec::new();

    if let Ok(entries) = fs::read_dir(&projects_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            if let Ok(meta) = path.metadata() {
                let created = meta.created().unwrap_or(SystemTime::UNIX_EPOCH);
                if created >= spawned_at {
                    candidates.push((path, created));
                }
            }
        }
    }

    // Pick the earliest-created file after our spawn time
    candidates.sort_by_key(|a| a.1);
    candidates.into_iter().next().map(|(p, _)| p)
}

/// Search Claude Code's sessions/ directory for an active session matching
/// the project path and started after our spawn time.
fn find_active_session_id(
    sessions_dir: &Path,
    project_path: &str,
    spawned_at: SystemTime,
) -> Option<String> {
    let spawned_ms = spawned_at
        .duration_since(SystemTime::UNIX_EPOCH)
        .ok()?
        .as_millis() as u64;

    // Allow 10s grace period (Claude Code may start slightly after PTY spawn)
    let threshold_ms = spawned_ms.saturating_sub(10_000);

    let normalized_project = normalize_path(project_path);

    let mut best: Option<(String, u64)> = None;

    if let Ok(entries) = fs::read_dir(sessions_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            if let Ok(content) = fs::read_to_string(&path) {
                if let Ok(session) = serde_json::from_str::<ActiveSession>(&content) {
                    let session_cwd = normalize_path(&session.cwd);
                    if session_cwd == normalized_project && session.started_at >= threshold_ms {
                        // Pick the earliest session started after our spawn
                        // threshold. With multiple concurrent sessions for the
                        // same project, each has a different spawned_at: the
                        // older session's threshold is lower, so it must claim
                        // the first matching Claude session, not the latest one.
                        if best.as_ref().is_none_or(|(_, t)| session.started_at < *t) {
                            best = Some((session.session_id, session.started_at));
                        }
                    }
                }
            }
        }
    }

    best.map(|(id, _)| id)
}

/// Normalize a path for comparison: lowercase, forward slashes, no trailing slash.
fn normalize_path(p: &str) -> String {
    p.replace('\\', "/")
        .trim_end_matches('/')
        .to_lowercase()
}

/// Reduce a list of `UsageEntry` for a single session into a `SessionUsage`.
///
/// Preserves existing semantics:
/// - Primary model = the model used by the most messages (mode).
/// - Context window % uses the LAST entry's total input (API resends the full
///   conversation each turn; the last turn's input is the current usage).
/// - `launched_model` (from launch options) is used for context window sizing
///   because JSONL strips the `[1m]` suffix; fall back to mode when empty.
pub fn reduce_session(
    entries: &[UsageEntry],
    launched_model: &str,
    session_id_hint: &str,
) -> Option<SessionUsage> {
    if entries.is_empty() {
        return None;
    }

    let mut input_tokens = 0u64;
    let mut output_tokens = 0u64;
    let mut cache_read = 0u64;
    let mut cache_write = 0u64;
    let mut model_counts: HashMap<&str, u64> = HashMap::new();

    for e in entries {
        input_tokens += e.input_tokens;
        output_tokens += e.output_tokens;
        cache_read += e.cache_read_tokens;
        cache_write += e.cache_write_tokens;
        if !e.model.is_empty() {
            *model_counts.entry(e.model.as_str()).or_insert(0) += 1;
        }
    }

    let primary_model = model_counts
        .into_iter()
        .max_by_key(|(_, c)| *c)
        .map(|(m, _)| m.to_string())
        .unwrap_or_else(|| {
            entries
                .last()
                .map(|e| e.model.clone())
                .unwrap_or_default()
        });

    // Sum per-entry cost so mixed-model sessions, the 1-hour cache premium, the
    // fast-mode multiplier, and web-search fees are all priced correctly — the
    // single source of truth is `cost_for_entry`.
    let estimated_cost: f64 = entries.iter().map(cost_for_entry).sum();

    let context_model = if launched_model.is_empty() {
        &primary_model
    } else {
        launched_model
    };
    let context_window = context_window_for_model(context_model);

    let last = entries.last().unwrap();
    let last_context_used =
        last.input_tokens + last.cache_read_tokens + last.cache_write_tokens;
    let context_pct = if context_window > 0 {
        (last_context_used as f64 / context_window as f64 * 100.0).min(100.0)
    } else {
        0.0
    };

    let total = input_tokens + output_tokens + cache_read + cache_write;
    let total_context_sent = input_tokens + cache_read + cache_write;

    // Cache hit % reflects "what fraction of billable input-side tokens came
    // from cache". Denominator includes cache_write because writes are fresh
    // input being laid down for later reuse (billed at ~125% of input rate) —
    // they are NOT a hit. Only cache_read counts as reusing prior work.
    let cache_denom = input_tokens + cache_read + cache_write;
    let cache_hit_pct = if cache_denom > 0 {
        (cache_read as f64 / cache_denom as f64) * 100.0
    } else {
        0.0
    };

    let session_id = entries
        .first()
        .map(|e| e.session_id.clone())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| session_id_hint.to_string());

    Some(SessionUsage {
        model: primary_model,
        input_tokens,
        output_tokens,
        cache_read_tokens: cache_read,
        cache_write_tokens: cache_write,
        total_tokens: total,
        estimated_cost_usd: estimated_cost,
        context_window_size: context_window,
        context_window_used_pct: context_pct,
        current_context_tokens: last_context_used,
        total_context_sent,
        cache_hit_pct,
        message_count: entries.len() as u64,
        session_id,
    })
}

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

    #[test]
    fn test_encode_project_path_drive_root() {
        assert_eq!(encode_project_path("S:\\Loom"), "S--Loom");
    }

    #[test]
    fn test_encode_project_path_deep() {
        assert_eq!(
            encode_project_path("C:\\Users\\Seven\\Desktop\\SF\\project"),
            "C--Users-Seven-Desktop-SF-project"
        );
    }

    #[test]
    fn test_encode_project_path_forward_slashes() {
        assert_eq!(encode_project_path("S:/Loom"), "S--Loom");
    }

    #[test]
    fn test_encode_project_path_trailing_slash() {
        assert_eq!(encode_project_path("S:\\Loom\\"), "S--Loom");
    }

    #[test]
    fn test_encode_project_path_macos() {
        assert_eq!(
            encode_project_path("/Users/seven/Loom"),
            "-Users-seven-Loom"
        );
    }

    #[test]
    fn test_encode_project_path_linux() {
        assert_eq!(
            encode_project_path("/home/alice/projects/foo"),
            "-home-alice-projects-foo"
        );
    }

    #[test]
    fn test_encode_project_path_unix_trailing_slash() {
        assert_eq!(encode_project_path("/Users/seven/Loom/"), "-Users-seven-Loom");
    }

    #[test]
    fn test_normalize_path() {
        assert_eq!(normalize_path("S:\\Loom\\"), "s:/loom");
        assert_eq!(normalize_path("S:/Loom"), "s:/loom");
        assert_eq!(normalize_path("C:\\Users\\Seven\\"), "c:/users/seven");
    }

    fn write_jsonl(lines: &[&str]) -> (TempDir, PathBuf) {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("abc123.jsonl");
        let mut f = fs::File::create(&path).unwrap();
        for l in lines {
            writeln!(f, "{}", l).unwrap();
        }
        (tmp, path)
    }

    fn assistant_line(id: &str, model: &str, ts: &str, inp: u64, out: u64, cr: u64, cw: u64) -> String {
        format!(
            r#"{{"type":"assistant","timestamp":"{ts}","message":{{"id":"{id}","model":"{model}","usage":{{"input_tokens":{inp},"output_tokens":{out},"cache_read_input_tokens":{cr},"cache_creation_input_tokens":{cw}}}}}}}"#
        )
    }

    #[test]
    fn parse_deduplicates_repeated_message_ids() {
        // Mirrors real Claude Code JSONL: each assistant message is written 2-3
        // times with identical usage as the stream progresses.
        let a1 = assistant_line("msg_01", "claude-opus-4-6", "2026-04-14T08:27:38.895Z", 15, 1463, 16397, 25661);
        let a1_dup = a1.clone();
        let a2 = assistant_line("msg_02", "claude-opus-4-6", "2026-04-14T08:34:37.200Z", 10, 401, 42058, 1668);
        let a2_dup = a2.clone();
        let a2_dup2 = a2.clone();
        let (_tmp, path) = write_jsonl(&[&a1, &a1_dup, &a2, &a2_dup, &a2_dup2]);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 2, "should dedup by message.id");
        assert_eq!(entries[0].input_tokens, 15);
        assert_eq!(entries[0].output_tokens, 1463);
        assert_eq!(entries[1].input_tokens, 10);
    }

    #[test]
    fn parse_captures_entrypoint_from_assistant_row() {
        // Headless `claude -p` writes JSONL with entrypoint="sdk-cli" on every
        // assistant row. Interactive Claude Code writes "cli". A row missing
        // the field (legacy/malformed) yields None.
        let headless = r#"{"type":"assistant","timestamp":"2026-05-13T07:19:12.573Z","entrypoint":"sdk-cli","message":{"id":"msg_h1","model":"claude-opus-4-7","usage":{"input_tokens":5,"output_tokens":628,"cache_read_input_tokens":0,"cache_creation_input_tokens":14266}}}"#;
        let interactive = r#"{"type":"assistant","timestamp":"2026-05-13T08:00:00.000Z","entrypoint":"cli","message":{"id":"msg_i1","model":"claude-opus-4-6","usage":{"input_tokens":10,"output_tokens":20,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}"#;
        let legacy = r#"{"type":"assistant","timestamp":"2026-05-13T09:00:00.000Z","message":{"id":"msg_l1","model":"claude-sonnet-4-6","usage":{"input_tokens":3,"output_tokens":4,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}"#;
        let (_tmp, path) = write_jsonl(&[headless, interactive, legacy]);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].entrypoint.as_deref(), Some("sdk-cli"));
        assert_eq!(entries[1].entrypoint.as_deref(), Some("cli"));
        assert_eq!(entries[2].entrypoint, None);
    }

    #[test]
    fn parse_skips_non_assistant_entries() {
        let lines = [
            r#"{"type":"user","message":{"role":"user","content":"hi"}}"#.to_string(),
            r#"{"type":"permission-mode"}"#.to_string(),
            r#"{"type":"file-history-snapshot"}"#.to_string(),
            r#"{"type":"attachment","timestamp":"2026-04-14T08:27:26.236Z"}"#.to_string(),
            assistant_line("msg_01", "claude-sonnet-4-6", "2026-04-14T08:28:00.000Z", 100, 200, 0, 0),
        ];
        let line_refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
        let (_tmp, path) = write_jsonl(&line_refs);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].model, "claude-sonnet-4-6");
    }

    #[test]
    fn parse_tolerates_malformed_lines_and_empty_lines() {
        let good = assistant_line("msg_01", "claude-opus-4-6", "2026-04-14T08:27:38.895Z", 5, 10, 0, 0);
        let lines = vec![
            "",
            "not json at all",
            r#"{"type":"assistant","message":null}"#,
            r#"{"type":"assistant","message":{"id":null}}"#,
            &good,
            "   ",
            r#"{"broken":"trailing"#,
        ];
        let (_tmp, path) = write_jsonl(&lines);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn parse_extracts_session_id_from_file_stem() {
        let line = assistant_line("msg_01", "claude-opus-4-6", "2026-04-14T08:27:38.895Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].session_id, "abc123");
    }

    #[test]
    fn parse_parses_iso_timestamps() {
        let line = assistant_line("msg_01", "claude-opus-4-6", "2026-04-14T08:27:38.895Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        // 2026-04-14T08:27:38.895Z → 1776155258895 ms
        assert_eq!(entries[0].timestamp_ms, 1_776_155_258_895);
    }

    #[test]
    fn parse_skips_synthetic_model_rows() {
        // Claude Code / Agent SDK writes `model: "<synthetic>"` for internal
        // routing (skill listings, queue ops). These must not count as turns.
        let real = assistant_line("msg_real", "claude-opus-4-6", "2026-04-11T00:27:38.895Z", 15, 100, 0, 0);
        let synthetic = r#"{"type":"assistant","timestamp":"2026-04-11T00:27:39.000Z","message":{"id":"msg_synth","model":"<synthetic>","usage":{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}"#;
        let (_tmp, path) = write_jsonl(&[&real, synthetic]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].model, "claude-opus-4-6");
    }

    #[test]
    fn parse_handles_missing_usage_fields() {
        let line = r#"{"type":"assistant","timestamp":"2026-04-14T08:27:38.895Z","message":{"id":"msg_01","model":"claude-opus-4-6"}}"#;
        let (_tmp, path) = write_jsonl(&[line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].input_tokens, 0);
        assert_eq!(entries[0].cache_read_tokens, 0);
    }

    #[test]
    fn reduce_computes_primary_model_by_mode() {
        let e = |m: &str| UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            model: m.into(),
            input_tokens: 1,
            output_tokens: 1,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            cache_write_1h_tokens: 0,
            web_search_requests: 0,
            speed: None,
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        };
        let entries = vec![
            e("claude-opus-4-6"),
            e("claude-opus-4-6"),
            e("claude-opus-4-6"),
            e("claude-sonnet-4-6"),
        ];
        let u = reduce_session(&entries, "", "sid").unwrap();
        assert_eq!(u.model, "claude-opus-4-6");
        assert_eq!(u.message_count, 4);
    }

    #[test]
    fn reduce_uses_launched_model_for_context_window() {
        let entries = vec![UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            // JSONL strips the [1m] suffix
            model: "claude-opus-4-6".into(),
            input_tokens: 1000,
            output_tokens: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            cache_write_1h_tokens: 0,
            web_search_requests: 0,
            speed: None,
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        }];
        let with_1m = reduce_session(&entries, "claude-opus-4-6[1m]", "sid").unwrap();
        let without = reduce_session(&entries, "", "sid").unwrap();
        assert_eq!(with_1m.context_window_size, 1_000_000);
        assert_eq!(without.context_window_size, 200_000);
    }

    #[test]
    fn reduce_context_pct_uses_last_entry_only() {
        // Claude's context window reflects the LAST turn's input, not the sum.
        let mk = |input: u64, cr: u64, cw: u64| UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            model: "claude-opus-4-6".into(),
            input_tokens: input,
            output_tokens: 0,
            cache_read_tokens: cr,
            cache_write_tokens: cw,
            cache_write_1h_tokens: 0,
            web_search_requests: 0,
            speed: None,
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        };
        let entries = vec![
            mk(1000, 0, 0),
            mk(500, 0, 0),
            mk(5, 160_000, 0), // last: 160_005 / 200_000 = 80.0025%
        ];
        let u = reduce_session(&entries, "", "sid").unwrap();
        assert_eq!(u.current_context_tokens, 160_005);
        assert!((u.context_window_used_pct - 80.0025).abs() < 0.01);
    }

    #[test]
    fn reduce_cache_hit_pct() {
        let e = |input: u64, cr: u64, cw: u64| UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            model: "claude-opus-4-6".into(),
            input_tokens: input,
            output_tokens: 1,
            cache_read_tokens: cr,
            cache_write_tokens: cw,
            cache_write_1h_tokens: 0,
            web_search_requests: 0,
            speed: None,
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        };
        // 3 fresh + 97 cache_read + 0 cache_write → 97 / 100 = 97%
        let u = reduce_session(&[e(3, 97, 0)], "", "sid").unwrap();
        assert!((u.cache_hit_pct - 97.0).abs() < 0.01);

        // Cache writes count as NOT a hit: 10 fresh + 80 read + 10 write → 80%
        let u = reduce_session(&[e(10, 80, 10)], "", "sid").unwrap();
        assert!((u.cache_hit_pct - 80.0).abs() < 0.01);

        // zero activity → 0 (not NaN)
        let u = reduce_session(&[e(0, 0, 0)], "", "sid").unwrap();
        assert_eq!(u.cache_hit_pct, 0.0);
    }

    #[test]
    fn reduce_total_context_sent_is_cumulative() {
        let mk = |input: u64, cr: u64, cw: u64| UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            model: "claude-opus-4-6".into(),
            input_tokens: input,
            output_tokens: 0,
            cache_read_tokens: cr,
            cache_write_tokens: cw,
            cache_write_1h_tokens: 0,
            web_search_requests: 0,
            speed: None,
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        };
        let u = reduce_session(
            &[mk(15, 16_397, 25_661), mk(10, 42_058, 1_668)],
            "",
            "sid",
        )
        .unwrap();
        assert_eq!(u.total_context_sent, 15 + 16_397 + 25_661 + 10 + 42_058 + 1_668);
    }

    #[test]
    fn reduce_cost_matches_opus_pricing() {
        // Opus: $5/$25 input/output, $0.50 read, $6.25 write per 1M tokens
        let entries = vec![UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            model: "claude-opus-4-6".into(),
            input_tokens: 1_000_000,   // $5
            output_tokens: 1_000_000,  // $25
            cache_read_tokens: 1_000_000, // $0.50
            cache_write_tokens: 1_000_000, // $6.25
            cache_write_1h_tokens: 0,
            web_search_requests: 0,
            speed: None,
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        }];
        let u = reduce_session(&entries, "", "sid").unwrap();
        assert!((u.estimated_cost_usd - 36.75).abs() < 0.001);
    }

    #[test]
    fn reduce_empty_returns_none() {
        assert!(reduce_session(&[], "", "sid").is_none());
    }

    // ---------- content extraction ----------

    fn assistant_with_content(id: &str, ts: &str, content_json: &str) -> String {
        format!(
            r#"{{"type":"assistant","timestamp":"{ts}","message":{{"id":"{id}","model":"claude-opus-4-6","usage":{{"input_tokens":1,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}},"content":{content_json}}}}}"#
        )
    }

    #[test]
    fn parse_extracts_tool_use_names() {
        let content = r#"[{"type":"tool_use","id":"tu_1","name":"Edit","input":{"file_path":"a.rs"}},{"type":"tool_use","id":"tu_2","name":"Read","input":{"file_path":"b.rs"}}]"#;
        let line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].tool_uses, vec!["Edit".to_string(), "Read".to_string()]);
    }

    #[test]
    fn parse_captures_text_char_count() {
        let content = r#"[{"type":"text","text":"Hello world"},{"type":"text","text":"!"}]"#;
        let line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].text_chars, 12); // "Hello world" + "!"
    }

    #[test]
    fn parse_handles_missing_content_gracefully() {
        // Most existing JSONL rows have no `content` field at all (older
        // Claude Code versions, or when we parse a row before content arrives).
        let line = assistant_line("msg_1", "claude-opus-4-6", "2026-04-14T08:27:38.895Z", 5, 10, 0, 0);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert!(entries[0].tool_uses.is_empty());
        assert_eq!(entries[0].text_chars, 0);
        assert_eq!(entries[0].activity, Activity::General);
    }

    #[test]
    fn parse_classifies_edit_plus_debug_as_debugging() {
        // Real-world flow: user asks to fix a bug, assistant runs Edit.
        let user_line = r#"{"type":"user","timestamp":"2026-04-14T08:27:30.000Z","message":{"role":"user","content":"Please fix the bug in login.rs"}}"#.to_string();
        let content = r#"[{"type":"tool_use","id":"tu_1","name":"Edit","input":{"file_path":"login.rs"}}]"#;
        let asst_line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&user_line, &asst_line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].activity, Activity::Debugging);
    }

    #[test]
    fn parse_classifies_bash_pytest_as_testing() {
        let user_line = r#"{"type":"user","timestamp":"2026-04-14T08:27:30.000Z","message":{"role":"user","content":"run the tests"}}"#.to_string();
        let content = r#"[{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"pytest tests/unit"}}]"#;
        let asst_line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&user_line, &asst_line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].activity, Activity::Testing);
    }

    #[test]
    fn parse_classifies_bash_git_as_gitops() {
        let content = r#"[{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"git push origin main"}}]"#;
        let line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].activity, Activity::GitOps);
    }

    #[test]
    fn parse_tool_result_row_does_not_overwrite_user_text() {
        // Sequence: user says "refactor the store", assistant runs a tool, the
        // injected tool_result row is also type="user", then another assistant
        // follow-up. The follow-up should still attribute to the original
        // "refactor" intent — tool_result rows must NOT overwrite last_user_text.
        let user_real = r#"{"type":"user","timestamp":"2026-04-14T08:27:30.000Z","message":{"role":"user","content":"refactor the usage store"}}"#.to_string();
        let asst1 = assistant_with_content(
            "msg_1",
            "2026-04-14T08:27:35.000Z",
            r#"[{"type":"tool_use","id":"tu_1","name":"Read","input":{"file_path":"store.ts"}}]"#,
        );
        let tool_result = r#"{"type":"user","timestamp":"2026-04-14T08:27:36.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tu_1","content":"file contents..."}]}}"#.to_string();
        let asst2 = assistant_with_content(
            "msg_2",
            "2026-04-14T08:27:40.000Z",
            r#"[{"type":"tool_use","id":"tu_2","name":"Edit","input":{"file_path":"store.ts"}}]"#,
        );
        let (_tmp, path) = write_jsonl(&[&user_real, &asst1, &tool_result, &asst2]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 2);
        // First assistant: Read only → Exploration
        assert_eq!(entries[0].activity, Activity::Exploration);
        // Second assistant: Edit after "refactor" intent → Refactor (not Coding),
        // proving the tool_result row didn't wipe last_user_text.
        assert_eq!(entries[1].activity, Activity::Refactor);
    }

    #[test]
    fn parse_classifies_agent_turn_as_delegation() {
        let content = r#"[{"type":"tool_use","id":"tu_1","name":"Agent","input":{"description":"explore"}}]"#;
        let line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].activity, Activity::Delegation);
    }

    #[test]
    fn parse_pure_text_turn_is_conversation() {
        let user_line = r#"{"type":"user","timestamp":"2026-04-14T08:27:30.000Z","message":{"role":"user","content":"thanks"}}"#.to_string();
        let content = r#"[{"type":"text","text":"You're welcome — anything else?"}]"#;
        let asst_line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&user_line, &asst_line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].activity, Activity::Conversation);
        assert!(entries[0].text_chars > 0);
    }

    #[test]
    fn parse_user_array_content_extracts_text_blocks() {
        // Some Claude Code versions write user content as an array even for
        // plain text. Ensure we pull the text out, not skip the row.
        let user_line = r#"{"type":"user","timestamp":"2026-04-14T08:27:30.000Z","message":{"role":"user","content":[{"type":"text","text":"fix the crash"}]}}"#.to_string();
        let content = r#"[{"type":"tool_use","id":"tu_1","name":"Edit","input":{}}]"#;
        let asst_line = assistant_with_content("msg_1", "2026-04-14T08:27:38.895Z", content);
        let (_tmp, path) = write_jsonl(&[&user_line, &asst_line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].activity, Activity::Debugging);
    }

    // ---------- split-row content merge (Claude Code one-block-per-row) ----------

    /// Helper: builds an assistant row that carries the same token usage
    /// numbers as the other rows for this `id` (matches what Claude Code
    /// actually writes — every row of a message repeats the final usage block).
    fn assistant_split_row(id: &str, ts: &str, content_json: &str) -> String {
        format!(
            r#"{{"type":"assistant","timestamp":"{ts}","message":{{"id":"{id}","model":"claude-opus-4-7","usage":{{"input_tokens":6,"output_tokens":746,"cache_read_input_tokens":21859,"cache_creation_input_tokens":33027}},"content":{content_json}}}}}"#
        )
    }

    #[test]
    fn parse_merges_tool_uses_across_split_content_rows() {
        // Claude Code 2.1.x emits one JSONL row per content block of an
        // assistant message: a `thinking` row, an optional `text` row, then
        // one row per `tool_use`. All rows share the same `message.id` and
        // the same `usage` block. The parser must merge tool_uses across rows
        // rather than dropping every row after the first.
        let thinking = assistant_split_row(
            "msg_01M6AvUVpAFjzSWcXeyGzUwV",
            "2026-05-13T09:09:03.500Z",
            r#"[{"type":"thinking","thinking":"plan"}]"#,
        );
        let text = assistant_split_row(
            "msg_01M6AvUVpAFjzSWcXeyGzUwV",
            "2026-05-13T09:09:03.550Z",
            r#"[{"type":"text","text":"Running tools in parallel."}]"#,
        );
        let tu1 = assistant_split_row(
            "msg_01M6AvUVpAFjzSWcXeyGzUwV",
            "2026-05-13T09:09:03.600Z",
            r#"[{"type":"tool_use","id":"tu_1","name":"mcp__example__list_configs","input":{"area":"rules"}}]"#,
        );
        let tu2 = assistant_split_row(
            "msg_01M6AvUVpAFjzSWcXeyGzUwV",
            "2026-05-13T09:09:03.700Z",
            r#"[{"type":"tool_use","id":"tu_2","name":"mcp__example__get_report","input":{}}]"#,
        );
        let tu3 = assistant_split_row(
            "msg_01M6AvUVpAFjzSWcXeyGzUwV",
            "2026-05-13T09:09:03.800Z",
            r#"[{"type":"tool_use","id":"tu_3","name":"Edit","input":{"file_path":"a.rs"}}]"#,
        );
        let (_tmp, path) = write_jsonl(&[&thinking, &text, &tu1, &tu2, &tu3]);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1, "still one entry per message.id");

        let e = &entries[0];
        assert_eq!(
            e.tool_uses,
            vec![
                "mcp__example__list_configs".to_string(),
                "mcp__example__get_report".to_string(),
                "Edit".to_string(),
            ],
            "all tool_use names merged in row order"
        );
        assert!(e.text_chars > 0, "text from the text row is preserved");

        // Billing fields come from the first row (they repeat identically, so
        // first == last in practice). Importantly, the merged content must
        // NOT cause tokens to multiply.
        assert_eq!(e.input_tokens, 6);
        assert_eq!(e.output_tokens, 746);
        assert_eq!(e.cache_read_tokens, 21859);
        assert_eq!(e.cache_write_tokens, 33027);
    }

    #[test]
    fn parse_split_row_classifies_against_merged_content() {
        // Bug pre-fix: first row is `thinking`, so `tool_uses` was empty and
        // activity classified as Conversation/General. After the fix the merged
        // content includes Edit, and a "fix the bug" user intent must route to
        // Debugging.
        let user = r#"{"type":"user","timestamp":"2026-05-13T09:09:00.000Z","message":{"role":"user","content":"please fix the bug in auth.rs"}}"#.to_string();
        let thinking = assistant_split_row(
            "msg_split",
            "2026-05-13T09:09:01.000Z",
            r#"[{"type":"thinking","thinking":"investigating"}]"#,
        );
        let edit = assistant_split_row(
            "msg_split",
            "2026-05-13T09:09:02.000Z",
            r#"[{"type":"tool_use","id":"tu_1","name":"Edit","input":{"file_path":"auth.rs"}}]"#,
        );
        let (_tmp, path) = write_jsonl(&[&user, &thinking, &edit]);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].activity, Activity::Debugging);
        assert_eq!(entries[0].tool_uses, vec!["Edit".to_string()]);
    }

    #[test]
    fn parse_split_row_bash_commands_feed_classifier() {
        // bash_cmds accumulate across rows too — pytest in a separate row
        // from the assistant's text must still classify as Testing.
        let user = r#"{"type":"user","timestamp":"2026-05-13T09:09:00.000Z","message":{"role":"user","content":"run tests"}}"#.to_string();
        let text = assistant_split_row(
            "msg_bash",
            "2026-05-13T09:09:01.000Z",
            r#"[{"type":"text","text":"Running the unit tests."}]"#,
        );
        let bash = assistant_split_row(
            "msg_bash",
            "2026-05-13T09:09:02.000Z",
            r#"[{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"pytest tests/"}}]"#,
        );
        let (_tmp, path) = write_jsonl(&[&user, &text, &bash]);

        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries[0].activity, Activity::Testing);
    }

    // ---------- hook extraction ----------

    #[test]
    fn parse_extracts_hook_success_events() {
        let hook_line = r#"{"type":"attachment","timestamp":"2026-04-15T18:08:50.000Z","attachment":{"type":"hook_success","hookName":"PostToolUse:Edit","hookEvent":"PostToolUse","toolUseID":"tu_abc","command":"verify-edit.sh","exitCode":0,"durationMs":90}}"#;
        let hook_fail = r#"{"type":"attachment","timestamp":"2026-04-15T18:09:00.000Z","attachment":{"type":"hook_success","hookName":"PreToolUse:Bash","hookEvent":"PreToolUse","toolUseID":"tu_def","command":"lint-check.sh","exitCode":1,"durationMs":250}}"#;
        // hook_system_message should be ignored (no execution data)
        let hook_msg = r#"{"type":"attachment","timestamp":"2026-04-15T18:09:01.000Z","attachment":{"type":"hook_system_message","hookName":"Stop","hookEvent":"Stop","content":"reminder text"}}"#;
        let asst = assistant_line("msg_01", "claude-opus-4-6", "2026-04-15T18:08:51.000Z", 5, 10, 0, 0);
        let (_tmp, path) = write_jsonl(&[hook_line, hook_fail, hook_msg, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.entries.len(), 1, "assistant entries unaffected");
        assert_eq!(parsed.hooks.len(), 2, "two hook_success events");

        assert_eq!(parsed.hooks[0].hook_name, "PostToolUse:Edit");
        assert_eq!(parsed.hooks[0].hook_event, "PostToolUse");
        assert_eq!(parsed.hooks[0].command, "verify-edit.sh");
        assert_eq!(parsed.hooks[0].exit_code, 0);
        assert_eq!(parsed.hooks[0].duration_ms, 90);

        assert_eq!(parsed.hooks[0].tool_use_id.as_deref(), Some("tu_abc"));

        assert_eq!(parsed.hooks[1].hook_name, "PreToolUse:Bash");
        assert_eq!(parsed.hooks[1].exit_code, 1);
        assert_eq!(parsed.hooks[1].duration_ms, 250);
        assert_eq!(parsed.hooks[1].tool_use_id.as_deref(), Some("tu_def"));
    }

    #[test]
    fn parse_ignores_attachment_without_hook_data() {
        // Non-hook attachments (e.g. file-history-snapshot) should be skipped.
        let non_hook = r#"{"type":"attachment","timestamp":"2026-04-14T08:27:26.236Z","attachment":{"type":"file_content","path":"foo.rs"}}"#;
        let asst = assistant_line("msg_01", "claude-opus-4-6", "2026-04-14T08:28:00.000Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[non_hook, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.entries.len(), 1);
        assert!(parsed.hooks.is_empty());
    }

    #[test]
    fn snake_to_pascal_converts_correctly() {
        assert_eq!(snake_to_pascal("stop"), "Stop");
        assert_eq!(snake_to_pascal("pre_tool_use"), "PreToolUse");
        assert_eq!(snake_to_pascal("post_tool_use"), "PostToolUse");
        assert_eq!(snake_to_pascal("session_start"), "SessionStart");
    }

    #[test]
    fn parse_extracts_system_hook_summary_v2() {
        // v2.1.119+ format: type=system, subtype=*_hook_summary
        let stop_summary = r#"{"type":"system","subtype":"stop_hook_summary","hookCount":1,"hookInfos":[{"command":"Running build checks...","durationMs":5227}],"hookErrors":[],"preventedContinuation":false,"stopReason":"","hasOutput":false,"level":"suggestion","timestamp":"2026-04-25T09:06:12.854Z","uuid":"abc","toolUseID":"tu_xyz","sessionId":"sess-1","version":"2.1.119"}"#;
        let asst = assistant_line("msg_01", "claude-opus-4-6", "2026-04-25T09:06:13.000Z", 5, 10, 0, 0);
        let (_tmp, path) = write_jsonl(&[stop_summary, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.entries.len(), 1);
        assert_eq!(parsed.hooks.len(), 1);

        let h = &parsed.hooks[0];
        assert_eq!(h.hook_event, "Stop");
        assert_eq!(h.command, "Running build checks...");
        assert_eq!(h.duration_ms, 5227);
        assert_eq!(h.exit_code, 0, "no errors and not prevented = success");
        assert_eq!(h.tool_use_id.as_deref(), Some("tu_xyz"));
    }

    #[test]
    fn parse_system_hook_summary_with_errors() {
        let summary = r#"{"type":"system","subtype":"stop_hook_summary","hookCount":1,"hookInfos":[{"command":"cargo check","durationMs":3000}],"hookErrors":["something broke"],"preventedContinuation":true,"timestamp":"2026-04-25T10:00:00.000Z","uuid":"def","toolUseID":"tu_err","sessionId":"sess-2","version":"2.1.119"}"#;
        let asst = assistant_line("msg_02", "claude-opus-4-6", "2026-04-25T10:00:01.000Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[summary, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.hooks.len(), 1);
        assert_eq!(parsed.hooks[0].exit_code, 1, "errors or prevented = failure");
    }

    #[test]
    fn parse_system_hook_summary_multiple_hooks() {
        let summary = r#"{"type":"system","subtype":"stop_hook_summary","hookCount":2,"hookInfos":[{"command":"tsc --noEmit","durationMs":1200},{"command":"cargo check","durationMs":3500}],"hookErrors":[],"preventedContinuation":false,"timestamp":"2026-04-25T11:00:00.000Z","uuid":"ghi","toolUseID":"tu_multi","sessionId":"sess-3","version":"2.1.119"}"#;
        let asst = assistant_line("msg_03", "claude-opus-4-6", "2026-04-25T11:00:01.000Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[summary, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.hooks.len(), 2);
        assert_eq!(parsed.hooks[0].command, "tsc --noEmit");
        assert_eq!(parsed.hooks[0].duration_ms, 1200);
        assert_eq!(parsed.hooks[1].command, "cargo check");
        assert_eq!(parsed.hooks[1].duration_ms, 3500);
        assert_eq!(parsed.hooks[0].tool_use_id, parsed.hooks[1].tool_use_id);
    }

    #[test]
    fn hook_name_label_sanitizes_long_multiline_commands() {
        // /goal-style stop hook: command is a multi-line goal statement.
        // The synthesized hook_name must NOT include the full body — otherwise
        // every distinct goal creates a unique bucket and breaks the Usage page.
        let long_cmd = "Goal statement: Achieve >=3x better compression ratio than zstd -19 --long=27 and xz -9e on the Lichess 2024-01 corpus.\n\n3. Validation strategy:\n- (a) Fixed + held-out corpora.";
        let escaped = serde_json::to_string(long_cmd).unwrap();
        let summary = format!(
            r#"{{"type":"system","subtype":"stop_hook_summary","hookCount":1,"hookInfos":[{{"command":{escaped},"durationMs":42}}],"hookErrors":[],"preventedContinuation":false,"timestamp":"2026-04-25T12:00:00.000Z","uuid":"goal","toolUseID":"tu_goal","sessionId":"sess-goal","version":"2.1.119"}}"#
        );
        let asst = assistant_line("msg_goal", "claude-opus-4-6", "2026-04-25T12:00:01.000Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[&summary, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.hooks.len(), 1);
        let h = &parsed.hooks[0];

        assert_eq!(h.command, long_cmd, "full command preserved on the entry");
        assert!(h.hook_name.starts_with("Stop:"), "name still scoped by event");
        // Total label length is bounded: event prefix + ":" + max 64 chars + 1-char ellipsis.
        assert!(h.hook_name.chars().count() <= "Stop:".len() + 65);
        assert!(h.hook_name.ends_with('…'), "long commands get ellipsis: {}", h.hook_name);
        assert!(!h.hook_name.contains('\n'), "no newlines in bucket key");
    }

    #[test]
    fn hook_name_label_preserves_short_commands() {
        let summary = r#"{"type":"system","subtype":"stop_hook_summary","hookCount":1,"hookInfos":[{"command":"cargo check","durationMs":3000}],"hookErrors":[],"preventedContinuation":false,"timestamp":"2026-04-25T13:00:00.000Z","uuid":"short","toolUseID":"tu_short","sessionId":"sess-short","version":"2.1.119"}"#;
        let asst = assistant_line("msg_short", "claude-opus-4-6", "2026-04-25T13:00:01.000Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[summary, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.hooks[0].hook_name, "Stop:cargo check");
    }

    #[test]
    fn parse_handles_both_formats_in_same_file() {
        // Old v2.1.101 attachment format
        let old_hook = r#"{"type":"attachment","timestamp":"2026-04-23T14:05:05.937Z","attachment":{"type":"hook_success","hookName":"PostToolUse:Edit","hookEvent":"PostToolUse","toolUseID":"tu_old","command":"lint.sh","exitCode":0,"durationMs":90}}"#;
        // New v2.1.119 system format
        let new_hook = r#"{"type":"system","subtype":"stop_hook_summary","hookCount":1,"hookInfos":[{"command":"cargo check","durationMs":5000}],"hookErrors":[],"preventedContinuation":false,"timestamp":"2026-04-25T09:06:12.854Z","uuid":"both","toolUseID":"tu_new","sessionId":"sess-both","version":"2.1.119"}"#;
        let asst = assistant_line("msg_both", "claude-opus-4-6", "2026-04-25T09:07:00.000Z", 1, 1, 0, 0);
        let (_tmp, path) = write_jsonl(&[old_hook, new_hook, &asst]);

        let parsed = parse_jsonl_entries(&path).unwrap();
        assert_eq!(parsed.hooks.len(), 2, "both formats parsed");
        assert_eq!(parsed.hooks[0].hook_event, "PostToolUse");
        assert_eq!(parsed.hooks[1].hook_event, "Stop");
    }

    // ---------- tiered cache / fast mode / web search pricing ----------

    #[allow(clippy::too_many_arguments)]
    fn entry_for_cost(
        model: &str,
        input: u64,
        output: u64,
        cr: u64,
        cw_total: u64,
        cw_1h: u64,
        web: u64,
        speed: Option<&str>,
    ) -> UsageEntry {
        UsageEntry {
            session_id: "s".into(),
            timestamp_ms: 0,
            model: model.into(),
            input_tokens: input,
            output_tokens: output,
            cache_read_tokens: cr,
            cache_write_tokens: cw_total,
            cache_write_1h_tokens: cw_1h,
            web_search_requests: web,
            speed: speed.map(|s| s.to_string()),
            tool_uses: Vec::new(),
            text_chars: 0,
            activity: Activity::General,
            entrypoint: None,
        }
    }

    #[test]
    fn fable_pricing_all_token_classes() {
        // Fable 5: $10 in / $50 out / $1 read / $12.50 5m-write / $20 1h-write per MTok.
        let input = entry_for_cost("claude-fable-5", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&input) - 10.0).abs() < 1e-6);
        let output = entry_for_cost("claude-fable-5", 0, 1_000_000, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&output) - 50.0).abs() < 1e-6);
        let read = entry_for_cost("claude-fable-5", 0, 0, 1_000_000, 0, 0, 0, None);
        assert!((cost_for_entry(&read) - 1.0).abs() < 1e-6);
        let w5m = entry_for_cost("claude-fable-5", 0, 0, 0, 1_000_000, 0, 0, None);
        assert!((cost_for_entry(&w5m) - 12.5).abs() < 1e-6);
        let w1h = entry_for_cost("claude-fable-5", 0, 0, 0, 1_000_000, 1_000_000, 0, None);
        assert!((cost_for_entry(&w1h) - 20.0).abs() < 1e-6);
    }

    #[test]
    fn fable_has_no_fast_premium() {
        // Fast mode is Opus-only; an (unexpected) fast-tagged Fable turn must
        // not be multiplied — never overcount on a guess.
        let fast = entry_for_cost("claude-fable-5", 1_000_000, 0, 0, 0, 0, 0, Some("fast"));
        assert!((cost_for_entry(&fast) - 10.0).abs() < 1e-6);
    }

    #[test]
    fn fable_context_window_is_natively_1m() {
        // No `[1m]` suffix variant exists for Fable — 1M is the default.
        assert_eq!(context_window_for_model("claude-fable-5"), 1_000_000);
        assert_eq!(context_window_for_model("claude-opus-4-8"), 200_000);
        assert_eq!(context_window_for_model("claude-opus-4-8[1m]"), 1_000_000);
    }

    #[test]
    fn cost_splits_5m_and_1h_cache_writes() {
        // Opus: 5m write $6.25/M, 1h write $10/M.
        let all_1h = entry_for_cost("claude-opus-4-8", 0, 0, 0, 1_000_000, 1_000_000, 0, None);
        assert!((cost_for_entry(&all_1h) - 10.0).abs() < 1e-6);
        let all_5m = entry_for_cost("claude-opus-4-8", 0, 0, 0, 1_000_000, 0, 0, None);
        assert!((cost_for_entry(&all_5m) - 6.25).abs() < 1e-6);
        // 400k 1h + 600k 5m = 0.4*10 + 0.6*6.25 = $7.75.
        let mixed = entry_for_cost("claude-opus-4-8", 0, 0, 0, 1_000_000, 400_000, 0, None);
        assert!((cost_for_entry(&mixed) - 7.75).abs() < 1e-6);
    }

    #[test]
    fn cost_adds_flat_web_search_fee() {
        // 3 web searches → $0.03, independent of tokens.
        let e = entry_for_cost("claude-sonnet-4-6", 0, 0, 0, 0, 0, 3, None);
        assert!((cost_for_entry(&e) - 0.03).abs() < 1e-9);
    }

    #[test]
    fn fast_mode_multiplier_scales_token_cost_not_web_fee() {
        // Opus 4.8 fast = 2x: 1M input $5 → $10.
        let std = entry_for_cost("claude-opus-4-8", 1_000_000, 0, 0, 0, 0, 0, Some("standard"));
        assert!((cost_for_entry(&std) - 5.0).abs() < 1e-6);
        let fast = entry_for_cost("claude-opus-4-8", 1_000_000, 0, 0, 0, 0, 0, Some("fast"));
        assert!((cost_for_entry(&fast) - 10.0).abs() < 1e-6);
        // Opus 4.6 fast = 6x → $30.
        let fast46 = entry_for_cost("claude-opus-4-6", 1_000_000, 0, 0, 0, 0, 0, Some("fast"));
        assert!((cost_for_entry(&fast46) - 30.0).abs() < 1e-6);
        // Web fee is flat even under fast: $10 token + $0.01 search.
        let fast_web = entry_for_cost("claude-opus-4-8", 1_000_000, 0, 0, 0, 0, 1, Some("fast"));
        assert!((cost_for_entry(&fast_web) - 10.01).abs() < 1e-6);
    }

    #[test]
    fn fast_multiplier_only_for_known_opus() {
        assert_eq!(fast_multiplier_for_model("claude-opus-4-8"), 2.0);
        assert_eq!(fast_multiplier_for_model("claude-opus-4-7"), 6.0);
        assert_eq!(fast_multiplier_for_model("claude-opus-4-6"), 6.0);
        assert_eq!(fast_multiplier_for_model("claude-opus-5"), 2.0);
        assert_eq!(fast_multiplier_for_model("claude-opus-5[1m]"), 2.0);
        assert_eq!(fast_multiplier_for_model("claude-opus-5-5"), 2.0);
        assert_eq!(fast_multiplier_for_model("claude-opus-5-5[1m]"), 2.0);
        assert_eq!(fast_multiplier_for_model("claude-sonnet-4-6"), 1.0);
        assert_eq!(fast_multiplier_for_model("claude-fable-5-1"), 1.0);
        // Unknown future model → no premium (never overcount on a guess).
        assert_eq!(fast_multiplier_for_model("claude-opus-6"), 1.0);
    }

    #[test]
    fn fable_5_1_reads_cache_at_a_quarter_of_fable_5() {
        // Fable 5.1: reads at 0.025× input ($0.25/MTok) instead of Fable 5's
        // 0.1× ($1/MTok). Every other rate is identical.
        let read51 = entry_for_cost("claude-fable-5-1", 0, 0, 1_000_000, 0, 0, 0, None);
        assert!((cost_for_entry(&read51) - 0.25).abs() < 1e-6);
        let read5 = entry_for_cost("claude-fable-5", 0, 0, 1_000_000, 0, 0, 0, None);
        assert!((cost_for_entry(&read5) - 1.0).abs() < 1e-6);

        let input = entry_for_cost("claude-fable-5-1", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&input) - 10.0).abs() < 1e-6);
        let output = entry_for_cost("claude-fable-5-1", 0, 1_000_000, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&output) - 50.0).abs() < 1e-6);
        let w5m = entry_for_cost("claude-fable-5-1", 0, 0, 0, 1_000_000, 0, 0, None);
        assert!((cost_for_entry(&w5m) - 12.5).abs() < 1e-6);
        let w1h = entry_for_cost("claude-fable-5-1", 0, 0, 0, 1_000_000, 1_000_000, 0, None);
        assert!((cost_for_entry(&w1h) - 20.0).abs() < 1e-6);
    }

    #[test]
    fn opus_5_5_is_cheaper_than_opus_5() {
        // Opus 5.5: $4/$20, 5m write $5, 1h write $8, cache read $0.20
        // (0.05× input). Opus 5 stays at $5/$25 with the 0.1× read.
        let in55 = entry_for_cost("claude-opus-5-5", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&in55) - 4.0).abs() < 1e-6);
        let out55 = entry_for_cost("claude-opus-5-5", 0, 1_000_000, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&out55) - 20.0).abs() < 1e-6);
        let read55 = entry_for_cost("claude-opus-5-5", 0, 0, 1_000_000, 0, 0, 0, None);
        assert!((cost_for_entry(&read55) - 0.2).abs() < 1e-6);
        let w5m = entry_for_cost("claude-opus-5-5", 0, 0, 0, 1_000_000, 0, 0, None);
        assert!((cost_for_entry(&w5m) - 5.0).abs() < 1e-6);
        let w1h = entry_for_cost("claude-opus-5-5", 0, 0, 0, 1_000_000, 1_000_000, 0, None);
        assert!((cost_for_entry(&w1h) - 8.0).abs() < 1e-6);

        // The 1M-context spelling and fast mode (2×) price the same model.
        let in55_1m = entry_for_cost("claude-opus-5-5[1m]", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&in55_1m) - 4.0).abs() < 1e-6);
        let fast = entry_for_cost("claude-opus-5-5", 1_000_000, 0, 0, 0, 0, 0, Some("fast"));
        assert!((cost_for_entry(&fast) - 8.0).abs() < 1e-6);

        // Opus 5 and the bare alias keep the older, dearer tier.
        let in5 = entry_for_cost("claude-opus-5", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&in5) - 5.0).abs() < 1e-6);
        assert_eq!(pricing_for_model("opus").input, 5.0);
        assert_eq!(pricing_for_model("opus").cache_read, 0.5);
    }

    #[test]
    fn sonnet_5_is_cheaper_than_sonnet_4_6() {
        // Sonnet 5: $2/$10 (standard price since 2026-09-01). Sonnet 4.6 and
        // earlier stay at $3/$15.
        let in5 = entry_for_cost("claude-sonnet-5", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&in5) - 2.0).abs() < 1e-6);
        let out5 = entry_for_cost("claude-sonnet-5", 0, 1_000_000, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&out5) - 10.0).abs() < 1e-6);
        let read5 = entry_for_cost("claude-sonnet-5", 0, 0, 1_000_000, 0, 0, 0, None);
        assert!((cost_for_entry(&read5) - 0.2).abs() < 1e-6);
        let w5m = entry_for_cost("claude-sonnet-5", 0, 0, 0, 1_000_000, 0, 0, None);
        assert!((cost_for_entry(&w5m) - 2.5).abs() < 1e-6);
        let w1h = entry_for_cost("claude-sonnet-5", 0, 0, 0, 1_000_000, 1_000_000, 0, None);
        assert!((cost_for_entry(&w1h) - 4.0).abs() < 1e-6);

        let in46 = entry_for_cost("claude-sonnet-4-6", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&in46) - 3.0).abs() < 1e-6);

        // The 1M-context spelling is the same model, not an unknown one.
        let in5_1m = entry_for_cost("claude-sonnet-5[1m]", 1_000_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&in5_1m) - 2.0).abs() < 1e-6);
    }

    #[test]
    fn haiku_5_5_is_a_tenth_of_haiku_4_5() {
        // Up to 100k: $0.10/$0.50, 5m write $0.125, 1h write $0.20, read $0.01.
        for id in ["claude-haiku-5-5", "claude-haiku-5-5-20261007"] {
            let p = pricing_for_model(id);
            assert_eq!(p.input, 0.1, "{id}");
            assert_eq!(p.output, 0.5, "{id}");
            assert_eq!(p.cache_read, 0.01, "{id}");
            assert_eq!(p.cache_write, 0.125, "{id}");
            assert_eq!(p.cache_write_1h, 0.2, "{id}");
        }
        // Haiku 4.5 and the bare alias keep the older, dearer tier.
        for id in ["claude-haiku-4-5", "claude-haiku-4-5-20251001", "haiku"] {
            let p = pricing_for_model(id);
            assert_eq!(p.input, 1.0, "{id}");
            assert_eq!(p.output, 5.0, "{id}");
            assert_eq!(p.cache_read, 0.1, "{id}");
        }
    }

    #[test]
    fn haiku_5_5_long_prompts_bill_the_higher_tier() {
        let model = "claude-haiku-5-5";
        // Prompt = input + cache read + cache write; exactly 100k stays on the base tier.
        let at = entry_for_cost(model, 50_000, 0, 30_000, 20_000, 0, 0, None);
        let want_at = (50_000.0 * 0.1 + 30_000.0 * 0.01 + 20_000.0 * 0.125) / 1e6;
        assert!((cost_for_entry(&at) - want_at).abs() < 1e-9);
        let over = entry_for_cost(model, 50_000, 0, 30_000, 20_001, 0, 0, None);
        let want_over = (50_000.0 * 0.5 + 30_000.0 * 0.05 + 20_001.0 * 0.625) / 1e6;
        assert!((cost_for_entry(&over) - want_over).abs() < 1e-9);

        // Long tier: $2.50 output, $1 1h write.
        let out = entry_for_cost(model, 100_001, 1_000_000, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&out) - (100_001.0 * 0.5 + 2_500_000.0) / 1e6).abs() < 1e-9);
        let w1h = entry_for_cost(model, 0, 0, 0, 200_000, 200_000, 0, None);
        assert!((cost_for_entry(&w1h) - 0.2).abs() < 1e-9);

        // Other models are flat regardless of prompt size.
        let h45 = entry_for_cost("claude-haiku-4-5", 200_000, 0, 0, 0, 0, 0, None);
        assert!((cost_for_entry(&h45) - 0.2).abs() < 1e-9);
    }

    #[test]
    fn haiku_5_5_context_window_is_natively_1m() {
        assert_eq!(context_window_for_model("claude-haiku-5-5"), 1_000_000);
        assert_eq!(context_window_for_model("claude-haiku-4-5"), 200_000);
        assert_eq!(context_window_for_model("claude-haiku-4-5-20251001"), 200_000);
    }

    #[test]
    fn unknown_models_keep_the_conservative_sonnet_rate() {
        // An id with no parseable family version must not pick up the newer,
        // cheaper tier — undercounting a real spend is worse than the default.
        for id in ["", "<unknown>", "sonnet", "claude-3-5-sonnet-20241022"] {
            let p = pricing_for_model(id);
            assert_eq!(p.input, 3.0, "{id} should price at the Sonnet default");
        }
        // …except "fable", which is still recognised as the Fable family and
        // prices at the older (more expensive) cache-read rate.
        assert_eq!(pricing_for_model("fable").cache_read, 1.0);
    }

    #[test]
    fn family_version_reads_minor_and_ignores_date_snapshots() {
        assert_eq!(family_version("claude-fable-5-1", "fable"), Some((5, 1)));
        assert_eq!(family_version("claude-fable-5", "fable"), Some((5, 0)));
        assert_eq!(family_version("claude-sonnet-5", "sonnet"), Some((5, 0)));
        assert_eq!(family_version("claude-sonnet-4-6", "sonnet"), Some((4, 6)));
        assert_eq!(family_version("claude-opus-5-5", "opus"), Some((5, 5)));
        assert_eq!(family_version("claude-opus-5-5[1m]", "opus"), Some((5, 5)));
        assert_eq!(
            family_version("claude-haiku-4-5-20251001", "haiku"),
            Some((4, 5))
        );
        // 8-digit segment is a date, not a minor version.
        assert_eq!(
            family_version("claude-sonnet-5-20260701", "sonnet"),
            Some((5, 0))
        );
        assert_eq!(family_version("fable", "fable"), None);
        assert_eq!(family_version("claude-opus-4-8", "sonnet"), None);
        // Legacy ids carry the version before the family name, so the segment
        // after it is a date — not major version 20241022.
        assert_eq!(family_version("claude-3-5-sonnet-20241022", "sonnet"), None);
    }

    #[test]
    fn parse_extracts_cache_split_speed_and_web_search() {
        let line = r#"{"type":"assistant","timestamp":"2026-05-29T10:00:00.000Z","message":{"id":"msg_1","model":"claude-opus-4-8","usage":{"input_tokens":2,"output_tokens":673,"cache_read_input_tokens":0,"cache_creation_input_tokens":40702,"cache_creation":{"ephemeral_5m_input_tokens":700,"ephemeral_1h_input_tokens":40002},"server_tool_use":{"web_search_requests":2,"web_fetch_requests":5},"speed":"fast"}}}"#;
        let (_tmp, path) = write_jsonl(&[line]);
        let entries = parse_jsonl_entries(&path).unwrap().entries;
        assert_eq!(entries.len(), 1);
        let e = &entries[0];
        assert_eq!(e.cache_write_tokens, 40702, "flat total preserved (== 5m+1h)");
        assert_eq!(e.cache_write_1h_tokens, 40002);
        assert_eq!(e.web_search_requests, 2);
        assert_eq!(e.speed.as_deref(), Some("fast"));
    }

    #[test]
    fn parse_cache_write_takes_max_of_flat_and_split() {
        // Nested split sums higher than the flat field → prefer the split.
        let line = r#"{"type":"assistant","timestamp":"2026-05-29T10:00:00.000Z","message":{"id":"msg_2","model":"claude-opus-4-8","usage":{"input_tokens":1,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":500,"ephemeral_1h_input_tokens":900}}}}"#;
        let (_tmp, path) = write_jsonl(&[line]);
        let e = &parse_jsonl_entries(&path).unwrap().entries[0];
        assert_eq!(e.cache_write_tokens, 1400, "max(100, 500+900)");
        assert_eq!(e.cache_write_1h_tokens, 900);
    }

    #[test]
    fn parse_missing_nested_cache_falls_back_to_flat() {
        // Older rows: only the flat field → 1h = 0 (all treated as 5m), no speed/web.
        let line = assistant_line("msg_3", "claude-opus-4-8", "2026-05-29T10:00:00.000Z", 5, 10, 0, 30000);
        let (_tmp, path) = write_jsonl(&[&line]);
        let e = &parse_jsonl_entries(&path).unwrap().entries[0];
        assert_eq!(e.cache_write_tokens, 30000);
        assert_eq!(e.cache_write_1h_tokens, 0);
        assert_eq!(e.web_search_requests, 0);
        assert_eq!(e.speed, None);
    }

    #[test]
    fn reduce_session_prices_1h_cache_premium() {
        // 1M of 1h cache writes on opus = $10, not the old single-rate $6.25.
        let e = entry_for_cost("claude-opus-4-8", 0, 0, 0, 1_000_000, 1_000_000, 0, None);
        let u = reduce_session(&[e], "", "sid").unwrap();
        assert!((u.estimated_cost_usd - 10.0).abs() < 1e-6);
    }
}