ctxone 1.3.2

The `ctx` CLI for CTXone, memory and context for AI agents
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
//! Session ingestion: parse agent transcripts, extract structured memories via
//! a configurable LLM provider (anthropic/openai/gemini/openai-compatible), and
//! store token usage + facts in the Hub.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Truncate `s` to at most `max_bytes` bytes on a UTF-8 char boundary.
///
/// A naive `&s[..max_bytes]` panics when `max_bytes` lands inside a
/// multibyte char (e.g. an em-dash spanning bytes 118..121 when the cut is
/// at 120). We back the cut up to the nearest boundary instead. Returns the
/// original string when it already fits.
fn truncate_on_char_boundary(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

// ── Extraction watermark ──────────────────────────────────────────────────────
//
// Memory extraction (the Haiku pass) must run EXACTLY ONCE per turn, but the
// incremental sync skip is per-SESSION: an active session that grew by one turn
// re-ingests in full, which would otherwise re-extract every prior turn on every
// sweep — duplicate memories and repeated Haiku cost. We track, per session, how
// many leading turns have already been extracted and skip those on re-ingest.
//
// Stored per-machine (the scraper is inherently local — transcripts live on the
// machine that produced them), in a single JSON file. Advances only, never
// rewinds; best-effort so a lost/corrupt file just re-extracts once.

/// Path to the per-machine extraction watermark file (`~/.ctxone/…`).
fn extraction_watermark_path() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home)
        .join(".ctxone")
        .join("extraction-watermarks.json")
}

fn load_watermarks_at(p: &Path) -> BTreeMap<String, usize> {
    std::fs::read(p)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default()
}

fn set_watermark_at(p: &Path, session_id: &str, count: usize) {
    if let Some(dir) = p.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    let mut map = load_watermarks_at(p);
    let entry = map.entry(session_id.to_string()).or_insert(0);
    if count <= *entry {
        return; // monotonic: nothing new, avoid a needless rewrite
    }
    *entry = count;
    if let Ok(bytes) = serde_json::to_vec(&map) {
        let tmp = p.with_extension("json.tmp");
        if std::fs::write(&tmp, &bytes).is_ok() {
            let _ = std::fs::rename(&tmp, p);
        }
    }
}

/// Number of leading turns of `session_id` already extracted on this machine.
pub fn extraction_watermark(session_id: &str) -> usize {
    load_watermarks_at(&extraction_watermark_path())
        .get(session_id)
        .copied()
        .unwrap_or(0)
}

/// Record that `count` leading turns of `session_id` have been extracted.
/// Monotonic (never moves backward), atomic (temp + rename), best-effort.
pub fn set_extraction_watermark(session_id: &str, count: usize) {
    set_watermark_at(&extraction_watermark_path(), session_id, count);
}

// ── JSONL structures ──────────────────────────────────────────────────────────

#[derive(Debug, Default, Serialize)]
pub struct TurnTokens {
    pub input: u64,
    pub output: u64,
    pub cache_read: u64,
    pub cache_creation: u64,
    /// Token classes these four fields cannot express, under the reporting
    /// agent's own names — Codex `reasoning_output_tokens`, Gemini
    /// `thoughts`/`tool`. Carried verbatim to the Hub's `extra_tokens` so a
    /// class we cannot yet display is still never lost.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, u64>,
}

impl TurnTokens {
    pub fn is_empty(&self) -> bool {
        self.input == 0 && self.output == 0 && self.extra.is_empty()
    }

    pub fn add(&mut self, other: &TurnTokens) {
        self.input += other.input;
        self.output += other.output;
        self.cache_read += other.cache_read;
        self.cache_creation += other.cache_creation;
        for (k, v) in &other.extra {
            *self.extra.entry(k.clone()).or_insert(0) += *v;
        }
    }
}

#[derive(Debug)]
pub struct Turn {
    pub user_text: String,
    pub assistant_text: String,
    pub tool_calls: Vec<String>,
    /// Full tool_use blocks as they appeared in the JSONL — preserves the
    /// real arguments (Bash command, full Edit diff, etc.) that the
    /// summarized `tool_calls` list throws away.
    pub tool_calls_raw: Vec<Value>,
    pub tokens: TurnTokens,
    pub model: String,
    pub timestamp: String,
    /// Working directory this turn ran in, as the agent recorded it.
    pub cwd: Option<String>,
    /// Every git branch this turn touched, in first-seen order.
    ///
    /// A set rather than one value because the branch can change *within* a
    /// turn — the user types on one branch and the agent works on another, or
    /// a checkout happens mid-turn. Recording only the assistant's branch
    /// silently dropped those: a real transcript had a branch that appeared on
    /// a user entry alone, and it vanished from the rollup entirely.
    ///
    /// Per-turn rather than per-session because a session is not one branch
    /// either: of the 12 largest transcripts measured, 7 spanned several.
    /// `HEAD` is kept verbatim rather than normalised away — a detached HEAD
    /// (common in worktrees) is signal, not noise.
    pub git_branches: Vec<String>,
    /// Commit the working tree was on. Codex records this; Claude Code does
    /// not, so it is usually `None`.
    pub git_commit: Option<String>,
}

impl Turn {
    /// True if this turn has enough substance to extract memories from.
    pub fn is_substantial(&self) -> bool {
        self.assistant_text.len() > 100 || !self.tool_calls.is_empty()
    }

    /// Render turn as text for the extraction LLM.
    pub fn to_exchange_text(&self) -> String {
        let mut out = String::new();
        out.push_str("USER:\n");
        out.push_str(&self.user_text);
        out.push_str("\n\nASSISTANT:\n");
        // Truncate very long assistant text to keep Haiku call cheap.
        let text = if self.assistant_text.len() > 8000 {
            format!(
                "{}…[truncated]",
                truncate_on_char_boundary(&self.assistant_text, 8000)
            )
        } else {
            self.assistant_text.clone()
        };
        out.push_str(&text);
        if !self.tool_calls.is_empty() {
            out.push_str("\n\nTOOLS USED:\n");
            for t in &self.tool_calls {
                out.push_str("- ");
                out.push_str(t);
                out.push('\n');
            }
        }
        out
    }
}

/// Parse a Claude Code JSONL file into a list of turns.
pub fn parse_turns(path: &Path) -> Vec<Turn> {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("  warn: could not read {}: {}", path.display(), e);
            return vec![];
        }
    };

    let entries: Vec<Value> = content
        .lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(|l| serde_json::from_str(l).ok())
        .collect();

    let mut turns: Vec<Turn> = vec![];
    let mut current_user: Option<String> = None;
    let mut current_ts: String = String::new();
    let mut current_cwd: Option<String> = None;
    let mut current_branch: Option<String> = None;

    for entry in &entries {
        let typ = entry.get("type").and_then(|v| v.as_str()).unwrap_or("");
        match typ {
            "user" => {
                // Start a new turn. Strip harness-injected system content
                // (task notifications / reminders / local-command output) so
                // it isn't attributed to the user. A message that had text but
                // was fully synthetic still opens a turn (with empty user
                // text) — the agent's reply then renders as agent-only.
                // A message with NO text at all (a bare tool_result) is part
                // of the current turn, so we leave `current_user` untouched.
                let raw = extract_text_content(entry.get("message"));
                if !raw.trim().is_empty() {
                    current_user = Some(strip_synthetic_blocks(&raw));
                    current_ts = entry
                        .get("timestamp")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    // The user side carries provenance too, and it is not
                    // always the same as the assistant's — capture it so a
                    // branch that only ever appears here is not lost.
                    current_cwd = str_field(entry, "cwd");
                    current_branch = str_field(entry, "gitBranch");
                } else {
                    // A textless entry is a bare tool_result, which belongs to
                    // the turn already in flight — but it still records where
                    // it ran, and a checkout DURING a tool call shows up here
                    // and nowhere else. One real transcript's third branch
                    // existed only on an entry like this.
                    let branch = str_field(entry, "gitBranch");
                    match turns.last_mut() {
                        Some(last) => push_unique(&mut last.git_branches, branch),
                        // Nothing to attach to yet; hand it to the next turn.
                        None => push_unique_opt(&mut current_branch, branch),
                    }
                }
            }
            "assistant" => {
                let Some(ref user_text) = current_user else {
                    continue;
                };
                let msg = match entry.get("message") {
                    Some(m) => m,
                    None => continue,
                };

                let assistant_text = extract_text_content(Some(msg));
                let tool_calls = extract_tool_calls(msg);
                let tool_calls_raw = extract_tool_calls_raw(msg);
                let tokens = extract_tokens(msg);
                let model = msg
                    .get("model")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown")
                    .to_string();

                // Merge with previous turn if same user message (split responses).
                if let Some(last) = turns.last_mut() {
                    if last.user_text == *user_text {
                        last.assistant_text.push('\n');
                        last.assistant_text.push_str(&assistant_text);
                        last.tool_calls.extend(tool_calls);
                        last.tool_calls_raw.extend(tool_calls_raw);
                        last.tokens.add(&tokens);
                        if !model.is_empty() && model != "unknown" {
                            last.model = model;
                        }
                        // A split response can carry provenance the first
                        // fragment lacked, or move to another branch mid-turn.
                        if last.cwd.is_none() {
                            last.cwd = str_field(entry, "cwd");
                        }
                        push_unique(&mut last.git_branches, str_field(entry, "gitBranch"));
                        continue;
                    }
                }

                turns.push(Turn {
                    user_text: user_text.clone(),
                    assistant_text,
                    tool_calls,
                    tool_calls_raw,
                    tokens,
                    model,
                    timestamp: current_ts.clone(),
                    // `cwd` and `gitBranch` are top-level on every Claude Code
                    // record, so a turn carries the branches it actually ran
                    // on rather than one inferred for the whole session. The
                    // user side is listed first because it came first.
                    cwd: str_field(entry, "cwd").or_else(|| current_cwd.clone()),
                    git_branches: {
                        let mut b = Vec::new();
                        push_unique(&mut b, current_branch.clone());
                        push_unique(&mut b, str_field(entry, "gitBranch"));
                        b
                    },
                    git_commit: None, // Claude Code does not record it
                });
            }
            _ => {}
        }
    }

    turns
}

/// Fill `slot` from `v` only when it is currently empty.
///
/// Used for provenance seen before any turn exists: the first branch observed
/// wins, and later ones attach to the turn in flight instead.
fn push_unique_opt(slot: &mut Option<String>, v: Option<String>) {
    if slot.is_none() {
        *slot = v;
    }
}

/// Append `v` if it is present and not already there, preserving order.
fn push_unique(list: &mut Vec<String>, v: Option<String>) {
    if let Some(v) = v
        && !list.iter().any(|x| *x == v)
    {
        list.push(v);
    }
}

/// A non-empty string field, or `None`. Empty strings are treated as absent
/// so a blank `gitBranch` never becomes a branch name in the rollup.
fn str_field(v: &Value, key: &str) -> Option<String> {
    v.get(key)
        .and_then(|x| x.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

/// Harness-injected tags that arrive inside a "user" turn but are NOT
/// human input: background-task notifications, system reminders, and the
/// output of local slash-commands. Left in place they mis-attribute
/// system/agent content to the USER in the transcript.
const SYNTHETIC_TAGS: &[&str] = &[
    "system-reminder",
    "task-notification",
    "local-command-caveat",
    "local-command-stdout",
    "local-command-message",
    "local-command-name",
    "local-command-args",
];

/// Remove synthetic `<tag>…</tag>` blocks from a user message, returning
/// the genuine human remainder. A fully-synthetic message reduces to an
/// empty string — the caller still opens a turn for it, so the agent's
/// reply renders as agent-only (no false USER bubble).
fn strip_synthetic_blocks(text: &str) -> String {
    let mut s = text.to_string();
    for tag in SYNTHETIC_TAGS {
        let open = format!("<{tag}>");
        let close = format!("</{tag}>");
        loop {
            let Some(start) = s.find(&open) else { break };
            match s[start + open.len()..].find(&close) {
                Some(rel) => {
                    let end = start + open.len() + rel + close.len();
                    s.replace_range(start..end, "");
                }
                // Unclosed tag — drop from the marker to the end, defensively.
                None => {
                    s.truncate(start);
                    break;
                }
            }
        }
    }
    // Some notifications carry a bare "[SYSTEM NOTIFICATION - NOT USER
    // INPUT]" preamble ahead of the tag; strip a leading one if it's left.
    let trimmed = s.trim_start();
    if trimmed.starts_with("[SYSTEM NOTIFICATION") {
        if let Some(nl) = trimmed.find("\n\n") {
            return trimmed[nl..].trim().to_string();
        }
    }
    s.trim().to_string()
}

fn extract_text_content(msg: Option<&Value>) -> String {
    let msg = match msg {
        Some(m) => m,
        None => return String::new(),
    };
    // content can be a string or array of blocks.
    match msg.get("content") {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Array(blocks)) => {
            let mut out = String::new();
            for block in blocks {
                let btype = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
                match btype {
                    "text" => {
                        if let Some(t) = block.get("text").and_then(|v| v.as_str()) {
                            if !out.is_empty() {
                                out.push('\n');
                            }
                            out.push_str(t);
                        }
                    }
                    // Skip "thinking" blocks — they're internal reasoning.
                    // Skip "tool_use" blocks — handled separately.
                    _ => {}
                }
            }
            out
        }
        _ => String::new(),
    }
}

fn extract_tool_calls(msg: &Value) -> Vec<String> {
    let blocks = match msg.get("content").and_then(|v| v.as_array()) {
        Some(b) => b,
        None => return vec![],
    };
    let mut calls = vec![];
    for block in blocks {
        if block.get("type").and_then(|v| v.as_str()) != Some("tool_use") {
            continue;
        }
        let name = block
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown");
        let input = block.get("input").cloned().unwrap_or(Value::Null);
        let summary = match name {
            "Bash" => input
                .get("command")
                .and_then(|v| v.as_str())
                .map(|c| {
                    let c = c.trim();
                    if c.len() > 120 {
                        format!("{}…", truncate_on_char_boundary(c, 120))
                    } else {
                        c.to_string()
                    }
                })
                .unwrap_or_default(),
            "Write" | "Read" | "Edit" | "Glob" | "Grep" => input
                .get("file_path")
                .or_else(|| input.get("path"))
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            "Agent" => input
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("sub-agent")
                .to_string(),
            _ => String::new(),
        };
        if summary.is_empty() {
            calls.push(name.to_string());
        } else {
            calls.push(format!("{}: {}", name, summary));
        }
    }
    calls
}

/// Like `extract_tool_calls` but returns the raw `{name, input}` pairs so
/// we can persist the full call (e.g., the actual Bash command, the full
/// Edit diff) rather than just the human-readable summary.
fn extract_tool_calls_raw(msg: &Value) -> Vec<Value> {
    let blocks = match msg.get("content").and_then(|v| v.as_array()) {
        Some(b) => b,
        None => return vec![],
    };
    let mut out = vec![];
    for block in blocks {
        if block.get("type").and_then(|v| v.as_str()) != Some("tool_use") {
            continue;
        }
        let name = block.get("name").cloned().unwrap_or(Value::Null);
        let input = block.get("input").cloned().unwrap_or(Value::Null);
        let id = block.get("id").cloned().unwrap_or(Value::Null);
        out.push(serde_json::json!({ "id": id, "name": name, "input": input }));
    }
    out
}

fn extract_tokens(msg: &Value) -> TurnTokens {
    let usage = match msg.get("usage") {
        Some(u) => u,
        None => return TurnTokens::default(),
    };
    TurnTokens {
        input: usage
            .get("input_tokens")
            .and_then(|v| v.as_u64())
            .unwrap_or(0),
        output: usage
            .get("output_tokens")
            .and_then(|v| v.as_u64())
            .unwrap_or(0),
        cache_read: usage
            .get("cache_read_input_tokens")
            .and_then(|v| v.as_u64())
            .unwrap_or(0),
        cache_creation: usage
            .get("cache_creation_input_tokens")
            .and_then(|v| v.as_u64())
            .unwrap_or(0),
        // Claude's usage has no classes beyond the four; extras stay empty.
        extra: BTreeMap::new(),
    }
}

// ── Extraction via Haiku ──────────────────────────────────────────────────────

const EXTRACTION_SYSTEM: &str = r#"You extract structured facts from AI coding conversations.
Given a conversation exchange, return a JSON array of memory objects.

Each object:
{
  "path": "/category/subcategory/slug",
  "title": "Short descriptive title (under 80 chars)",
  "body": "The fact plus reasoning. Include why if a decision was made (1-3 sentences).",
  "importance": "high|medium|low",
  "context": "topic-tag"
}

Path categories:
  /decisions/   — architectural or design choices and their rationale
  /problems/    — issues encountered and how they were solved
  /preferences/ — user preferences revealed through corrections or feedback
  /conventions/ — coding, naming, or process conventions established
  /constraints/ — technical or business limitations discovered
  /progress/    — significant milestones or completions
  /next-steps/  — what was explicitly deferred or planned next

Rules:
- Include options that were REJECTED and why — this is as valuable as what was chosen
- Capture user corrections ("no, do X instead") as /preferences/
- Only extract facts that will be useful to a future agent on this project
- Skip: routine file reads, search results, compilation output unless something important was revealed
- Return ONLY a valid JSON array. No markdown fences, no explanation."#;

// ── Extraction provider ───────────────────────────────────────────────────────
//
// The extraction LLM is pluggable: the shared, provider-neutral prompt
// (EXTRACTION_SYSTEM) is sent to whichever provider the user configured, and the
// per-provider request/response shape is handled by `call_extraction_llm`.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExtractionProvider {
    Anthropic,
    OpenAi,
    Gemini,
    /// Any OpenAI `/chat/completions`-compatible endpoint (base_url required).
    OpenAiCompatible,
}

impl ExtractionProvider {
    fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "anthropic" | "claude" => Some(Self::Anthropic),
            "openai" => Some(Self::OpenAi),
            "gemini" | "google" => Some(Self::Gemini),
            "openai-compatible" | "openai_compatible" | "compatible" => {
                Some(Self::OpenAiCompatible)
            }
            _ => None,
        }
    }
    /// Env var conventionally holding this provider's key.
    fn key_env(self) -> &'static str {
        match self {
            Self::Anthropic => "ANTHROPIC_API_KEY",
            Self::OpenAi | Self::OpenAiCompatible => "OPENAI_API_KEY",
            Self::Gemini => "GEMINI_API_KEY",
        }
    }
    /// Slug for the `~/.ctxone/keys/<slug>` fallback key file, also used as the
    /// provider label recorded on the analysis record.
    pub fn key_slug(self) -> &'static str {
        match self {
            Self::Anthropic => "anthropic",
            Self::OpenAi => "openai",
            Self::Gemini => "gemini",
            Self::OpenAiCompatible => "openai-compatible",
        }
    }
}

// ── Hub-stored analysis status ────────────────────────────────────────────────
//
// The authoritative record of what has been analyzed lives on the hub (so CLI +
// Lens + other devices all see it); the local watermark is just the sweep's
// fast-path cache. `analyzed_through` is the number of leading turns analyzed.

/// GET the hub's `analyzed_through` for a session (0 when absent/unreachable).
pub async fn hub_analyzed_through(hub: &str, session: &str, client: &reqwest::Client) -> usize {
    let url = format!("{}/api/sessions/{}/analysis", hub, urlencode(session));
    let Ok(resp) = client
        .get(&url)
        .header("X-CTXone-Session", session)
        .send()
        .await
    else {
        return 0;
    };
    if !resp.status().is_success() {
        return 0;
    }
    let v: Value = resp.json().await.unwrap_or(Value::Null);
    v.get("analyzed_through")
        .and_then(|x| x.as_u64())
        .unwrap_or(0) as usize
}

/// PUT a full analysis record body for a session. Best-effort.
pub async fn put_analysis(hub: &str, session: &str, body: &Value, client: &reqwest::Client) {
    let url = format!("{}/api/sessions/{}/analysis", hub, urlencode(session));
    let _ = client
        .put(&url)
        .header("X-CTXone-Session", session)
        .json(body)
        .send()
        .await;
}

// ── Session structure analysis (summary + topic arcs / pseudo-branches) ────────

const SESSION_ANALYSIS_SYSTEM: &str = r#"You analyze an AI coding-agent session.
You are given a compact, turn-indexed transcript (one line per turn, "T<i> [branch] U: <user> | A: <assistant>").

Return ONLY a JSON object, no markdown fences:
{
  "summary": "2-4 sentence summary of the whole session",
  "topics": [
    {"start": <first turn index>, "end": <last turn index>, "label": "short topic label", "summary": "1-2 sentence summary of this topic"}
  ]
}

A "topic" is a contiguous run of turns on one subject. A topic SHIFT (the work moves to a different subject) starts a new topic — these topic arcs act as pseudo-branches for clients that do not branch natively. Cover every turn; topics must be contiguous and non-overlapping, in order."#;

#[derive(Serialize, Deserialize, Debug)]
pub struct TopicArc {
    pub start: usize,
    pub end: usize,
    pub label: String,
    #[serde(default)]
    pub summary: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SessionAnalysis {
    #[serde(default)]
    pub summary: String,
    #[serde(default)]
    pub topics: Vec<TopicArc>,
}

fn first_line(s: &str, max: usize) -> String {
    let line = s
        .lines()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("")
        .trim();
    truncate_on_char_boundary(line, max).replace('\n', " ")
}

/// A compact, index-tagged transcript so the model can segment the whole
/// session by topic within a bounded context budget.
fn condensed_transcript(turns: &[Turn]) -> String {
    let mut out = String::new();
    for (i, t) in turns.iter().enumerate() {
        let branch = t.git_branches.first().map(|s| s.as_str()).unwrap_or("");
        out.push_str(&format!(
            "T{i} [{branch}] U: {} | A: {}\n",
            first_line(&t.user_text, 160),
            first_line(&t.assistant_text, 200),
        ));
    }
    out
}

/// Produce a session summary + topic arcs (pseudo-branch structure) via one LLM
/// call. `None` on any error or empty input.
pub async fn analyze_session(
    turns: &[Turn],
    cfg: &ExtractionConfig,
    client: &reqwest::Client,
) -> Option<SessionAnalysis> {
    if turns.is_empty() {
        return None;
    }
    let transcript = condensed_transcript(turns);
    let transcript = truncate_on_char_boundary(&transcript, 24_000).to_string();
    let raw = call_extraction_llm(cfg, SESSION_ANALYSIS_SYSTEM, &transcript, client).await?;
    let json_str = raw
        .trim()
        .trim_start_matches("```json")
        .trim_start_matches("```")
        .trim_end_matches("```")
        .trim();
    match serde_json::from_str::<SessionAnalysis>(json_str) {
        Ok(a) => Some(a),
        Err(e) => {
            eprintln!("  warn: could not parse session analysis: {e}");
            None
        }
    }
}

/// Minimal percent-encoding for a session id in a URL path segment (session
/// ids can carry a `:` namespace prefix, e.g. `codex:<uuid>`).
fn urlencode(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' => c.to_string(),
            _ => format!("%{:02X}", c as u32),
        })
        .collect()
}

/// Fully-resolved extraction config: which provider/model to call and the key.
pub struct ExtractionConfig {
    pub provider: ExtractionProvider,
    pub model: String,
    /// Required for `OpenAiCompatible`; ignored otherwise.
    pub base_url: Option<String>,
    pub api_key: String,
}

#[derive(Deserialize, Default)]
struct ExtractionToml {
    /// Master switch. `enabled = false` disables analysis even when a key is
    /// present (the user-level "disable analysis" control). Defaults to on.
    enabled: Option<bool>,
    provider: Option<String>,
    model: Option<String>,
    base_url: Option<String>,
    key_file: Option<String>,
}

fn ctxone_home() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home).join(".ctxone")
}

/// Read a key from an explicit file path (trimmed); `None` if missing/empty.
fn read_key_file(path: &Path) -> Option<String> {
    let k = std::fs::read_to_string(path).ok()?.trim().to_string();
    (!k.is_empty()).then_some(k)
}

/// Resolve the extraction config from `~/.ctxone/extraction.toml` + env + key
/// files. Returns `None` when no API key can be found — extraction is then
/// simply skipped (turns + tokens are still captured).
///
/// Precedence: explicit `key_file` in the toml → the provider's env var →
/// `~/.ctxone/keys/<provider>`. Defaults to Anthropic Haiku when the toml is
/// absent, preserving prior behaviour.
pub fn resolve_extraction_config() -> Option<ExtractionConfig> {
    let cfg: ExtractionToml = std::fs::read_to_string(ctxone_home().join("extraction.toml"))
        .ok()
        .and_then(|s| toml::from_str(&s).ok())
        .unwrap_or_default();

    // User-level control: `enabled = false` turns analysis off entirely.
    if cfg.enabled == Some(false) {
        return None;
    }

    let provider = cfg
        .provider
        .as_deref()
        .and_then(ExtractionProvider::parse)
        .unwrap_or(ExtractionProvider::Anthropic);

    let model = cfg.model.unwrap_or_else(|| match provider {
        ExtractionProvider::Anthropic => "claude-haiku-4-5-20251001".to_string(),
        ExtractionProvider::OpenAi | ExtractionProvider::OpenAiCompatible => {
            "gpt-5-mini".to_string()
        }
        ExtractionProvider::Gemini => "gemini-3-flash".to_string(),
    });

    let api_key = cfg
        .key_file
        .as_deref()
        .and_then(|p| read_key_file(Path::new(&shellexpand_home(p))))
        .or_else(|| {
            std::env::var(provider.key_env())
                .ok()
                .filter(|s| !s.is_empty())
        })
        .or_else(|| read_key_file(&ctxone_home().join("keys").join(provider.key_slug())))?;

    Some(ExtractionConfig {
        provider,
        model,
        base_url: cfg.base_url,
        api_key,
    })
}

/// Expand a leading `~/` to `$HOME` in a config-supplied path.
fn shellexpand_home(p: &str) -> String {
    if let Some(rest) = p.strip_prefix("~/") {
        let home = std::env::var("HOME").unwrap_or_default();
        format!("{home}/{rest}")
    } else {
        p.to_string()
    }
}

#[derive(Serialize)]
struct AnthropicRequest {
    model: String,
    max_tokens: u32,
    system: String,
    messages: Vec<AnthropicMessage>,
}

#[derive(Serialize)]
struct AnthropicMessage {
    role: String,
    content: String,
}

#[derive(Deserialize)]
struct AnthropicResponse {
    content: Vec<AnthropicContent>,
}

#[derive(Deserialize)]
struct AnthropicContent {
    #[serde(rename = "type")]
    content_type: String,
    text: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct ExtractedMemory {
    pub path: String,
    pub title: String,
    pub body: String,
    pub importance: String,
    pub context: String,
}

pub async fn extract_memories(
    turn: &Turn,
    cfg: &ExtractionConfig,
    client: &reqwest::Client,
) -> Vec<ExtractedMemory> {
    let exchange = turn.to_exchange_text();
    let raw = match call_extraction_llm(cfg, EXTRACTION_SYSTEM, &exchange, client).await {
        Some(r) => r,
        None => return vec![],
    };

    // Strip markdown fences if the model added them despite instructions.
    let json_str = raw
        .trim()
        .trim_start_matches("```json")
        .trim_start_matches("```")
        .trim_end_matches("```")
        .trim();

    match serde_json::from_str::<Vec<ExtractedMemory>>(json_str) {
        Ok(memories) => memories,
        Err(e) => {
            eprintln!("  warn: could not parse extracted memories: {}", e);
            eprintln!("  raw: {}", truncate_on_char_boundary(json_str, 300));
            vec![]
        }
    }
}

/// Send `system` + `user` to the configured provider; return the model's raw
/// text, or `None` on any error (logged). Dispatches the per-provider shape.
async fn call_extraction_llm(
    cfg: &ExtractionConfig,
    system: &str,
    user: &str,
    client: &reqwest::Client,
) -> Option<String> {
    match cfg.provider {
        ExtractionProvider::Anthropic => call_anthropic(cfg, system, user, client).await,
        ExtractionProvider::OpenAi | ExtractionProvider::OpenAiCompatible => {
            call_openai(cfg, system, user, client).await
        }
        ExtractionProvider::Gemini => call_gemini(cfg, system, user, client).await,
    }
}

/// Log a non-success HTTP response and return `None`.
async fn warn_bad_response(who: &str, resp: reqwest::Response) -> Option<String> {
    let status = resp.status();
    let body = resp.text().await.unwrap_or_default();
    eprintln!(
        "  warn: {who} returned {status}: {}",
        truncate_on_char_boundary(&body, 200)
    );
    None
}

async fn call_anthropic(
    cfg: &ExtractionConfig,
    system: &str,
    user: &str,
    client: &reqwest::Client,
) -> Option<String> {
    let req = AnthropicRequest {
        model: cfg.model.clone(),
        max_tokens: 4096,
        system: system.to_string(),
        messages: vec![AnthropicMessage {
            role: "user".to_string(),
            content: user.to_string(),
        }],
    };
    let resp = client
        .post("https://api.anthropic.com/v1/messages")
        .header("x-api-key", &cfg.api_key)
        .header("anthropic-version", "2023-06-01")
        .header("content-type", "application/json")
        .json(&req)
        .send()
        .await
        .map_err(|e| eprintln!("  warn: Anthropic call failed: {e}"))
        .ok()?;
    if !resp.status().is_success() {
        return warn_bad_response("Anthropic", resp).await;
    }
    let ar: AnthropicResponse = resp
        .json()
        .await
        .map_err(|e| eprintln!("  warn: parse Anthropic response: {e}"))
        .ok()?;
    Some(
        ar.content
            .iter()
            .filter(|c| c.content_type == "text")
            .filter_map(|c| c.text.as_deref())
            .collect::<Vec<_>>()
            .join(""),
    )
}

async fn call_openai(
    cfg: &ExtractionConfig,
    system: &str,
    user: &str,
    client: &reqwest::Client,
) -> Option<String> {
    let base = cfg
        .base_url
        .as_deref()
        .unwrap_or("https://api.openai.com")
        .trim_end_matches('/');
    let req = OpenAiRequest {
        model: cfg.model.clone(),
        messages: vec![
            OpenAiMessage {
                role: "system",
                content: system.to_string(),
            },
            OpenAiMessage {
                role: "user",
                content: user.to_string(),
            },
        ],
    };
    let resp = client
        .post(format!("{base}/v1/chat/completions"))
        .bearer_auth(&cfg.api_key)
        .json(&req)
        .send()
        .await
        .map_err(|e| eprintln!("  warn: OpenAI call failed: {e}"))
        .ok()?;
    if !resp.status().is_success() {
        return warn_bad_response("OpenAI", resp).await;
    }
    let or: OpenAiResponse = resp
        .json()
        .await
        .map_err(|e| eprintln!("  warn: parse OpenAI response: {e}"))
        .ok()?;
    or.choices.into_iter().next().map(|c| c.message.content)
}

async fn call_gemini(
    cfg: &ExtractionConfig,
    system: &str,
    user: &str,
    client: &reqwest::Client,
) -> Option<String> {
    let url = format!(
        "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent",
        cfg.model
    );
    let req = GeminiRequest {
        system_instruction: GeminiContent {
            role: None,
            parts: vec![GeminiPart {
                text: system.to_string(),
            }],
        },
        contents: vec![GeminiContent {
            role: Some("user".to_string()),
            parts: vec![GeminiPart {
                text: user.to_string(),
            }],
        }],
    };
    let resp = client
        .post(&url)
        .header("x-goog-api-key", &cfg.api_key)
        .json(&req)
        .send()
        .await
        .map_err(|e| eprintln!("  warn: Gemini call failed: {e}"))
        .ok()?;
    if !resp.status().is_success() {
        return warn_bad_response("Gemini", resp).await;
    }
    let gr: GeminiResponse = resp
        .json()
        .await
        .map_err(|e| eprintln!("  warn: parse Gemini response: {e}"))
        .ok()?;
    let cand = gr.candidates.into_iter().next()?;
    Some(
        cand.content
            .parts
            .into_iter()
            .map(|p| p.text)
            .collect::<Vec<_>>()
            .join(""),
    )
}

// OpenAI / OpenAI-compatible chat-completions shapes.
#[derive(Serialize)]
struct OpenAiRequest {
    model: String,
    messages: Vec<OpenAiMessage>,
}
#[derive(Serialize)]
struct OpenAiMessage {
    role: &'static str,
    content: String,
}
#[derive(Deserialize)]
struct OpenAiResponse {
    choices: Vec<OpenAiChoice>,
}
#[derive(Deserialize)]
struct OpenAiChoice {
    message: OpenAiRespMessage,
}
#[derive(Deserialize)]
struct OpenAiRespMessage {
    #[serde(default)]
    content: String,
}

// Gemini generateContent shapes.
#[derive(Serialize)]
struct GeminiRequest {
    system_instruction: GeminiContent,
    contents: Vec<GeminiContent>,
}
#[derive(Serialize, Deserialize)]
struct GeminiContent {
    #[serde(skip_serializing_if = "Option::is_none")]
    role: Option<String>,
    parts: Vec<GeminiPart>,
}
#[derive(Serialize, Deserialize)]
struct GeminiPart {
    text: String,
}
#[derive(Deserialize)]
struct GeminiResponse {
    #[serde(default)]
    candidates: Vec<GeminiCandidate>,
}
#[derive(Deserialize)]
struct GeminiCandidate {
    content: GeminiContent,
}

// ── Hub writes ────────────────────────────────────────────────────────────────

/// Best-effort provider for a model name.
///
/// The provider used to be hardcoded to "anthropic", which was true while
/// Claude Code was the only source and silently wrong the moment a Codex or
/// Gemini turn came through the same path. Derived from the model rather than
/// threaded from the source so turns keep the right provider even when they
/// are replayed outside their originating adapter.
pub fn provider_for_model(model: &str) -> &'static str {
    let m = model.to_ascii_lowercase();
    if m.starts_with("claude") {
        "anthropic"
    } else if m.starts_with("gpt") || m.starts_with("o1") || m.starts_with("o3") {
        "openai"
    } else if m.starts_with("gemini") {
        "google"
    } else {
        "unknown"
    }
}

pub async fn record_turn_tokens(
    tokens: &TurnTokens,
    model: &str,
    provider: &str,
    hub: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    if tokens.is_empty() {
        return;
    }
    let body = serde_json::json!({
        "input_tokens": tokens.input,
        "output_tokens": tokens.output,
        "cache_read_tokens": tokens.cache_read,
        "cache_creation_tokens": tokens.cache_creation,
        "extra_tokens": tokens.extra,
        "model": model,
        "provider": provider,
    });
    let mut req = client
        .post(format!("{}/api/stats/llm_usage", hub))
        .json(&body);
    if let Some(sid) = session {
        req = req.header("X-CTXone-Session", sid);
    }
    let _ = req.send().await;
}

/// After a session's turns are written, ask the hub to recompute that session's
/// per-model LLM usage from those turns (`POST /api/stats/backfill_by_model?
/// session=<id>`). The recompute REPLACES the split, so re-ingesting the same
/// session is idempotent — unlike the old additive `record_llm_usage` post,
/// which re-added the whole session total on every ingest and inflated the
/// counters N×. Best-effort: a failure just leaves the split as it was.
pub async fn trigger_session_by_model_backfill(
    hub: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    let Some(sid) = session else {
        return;
    };
    let url = format!(
        "{}/api/stats/backfill_by_model?session={}",
        hub,
        crate::urlencoding(sid)
    );
    // The client already carries X-CTXone-Namespace (workspace-scoped); add the
    // session header for parity with the rest of the ingest posts.
    let _ = client
        .post(url)
        .header("X-CTXone-Session", sid)
        .send()
        .await;
}

/// Persist the full turn (request, assistant response, tool calls with
/// real arguments, token usage, model, timestamp) as a memory at a
/// deterministic per-session path. This complements the Haiku-extracted
/// memories: extraction loses fidelity, the raw turn keeps everything.
///
/// Path: `/sessions/{session}/turns/{idx:04}` so turns sort lexically.
/// `idx` is the per-session turn number (0-based).
///
/// The stored JSON for one turn. Shared by the per-turn and bulk writers so
/// the shape can't drift between them.
pub fn turn_snapshot(turn: &Turn, idx: usize, sid: &str, source_file: &str) -> Value {
    serde_json::json!({
        "session": sid,
        "turn_index": idx,
        "timestamp": turn.timestamp,
        "model": turn.model,
        "source_file": source_file,
        "user_text": turn.user_text,
        "assistant_text": turn.assistant_text,
        "tool_calls": turn.tool_calls,
        "tool_calls_raw": turn.tool_calls_raw,
        "tokens": turn.tokens,
        // Provenance. Omitted when unknown rather than written as null or "",
        // so a reader can distinguish "this turn ran on no recorded branch"
        // from "this turn predates provenance capture".
        "cwd": turn.cwd,
        "git_branches": turn.git_branches,
        "git_commit": turn.git_commit,
    })
}

/// True when `hub` (a base URL such as `http://127.0.0.1:3001`) is on this
/// machine: `localhost` or a `*.localhost` name, a 127.0.0.0/8 or `::1`
/// address, or the unspecified address (`0.0.0.0`, `::`), which connects here
/// too. Anything else counts as remote: a LAN address, a host name, a hosted
/// hub. There is no DNS lookup, so a name that resolves to loopback still
/// counts as remote, which errs toward keeping turns on this machine.
pub fn hub_is_local(hub: &str) -> bool {
    let Ok(url) = reqwest::Url::parse(hub) else {
        return false;
    };
    let Some(host) = url.host_str() else {
        return false;
    };
    let host = host.trim_start_matches('[').trim_end_matches(']');
    let lower = host.to_ascii_lowercase();
    if lower == "localhost" || lower.ends_with(".localhost") {
        return true;
    }
    match host.parse::<std::net::IpAddr>() {
        Ok(std::net::IpAddr::V6(v6)) => {
            v6.is_loopback()
                || v6.is_unspecified()
                || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
        }
        Ok(ip) => ip.is_loopback() || ip.is_unspecified(),
        Err(_) => false,
    }
}

/// `hub`'s scheme, host and port, for messages: never its path or any
/// credentials in the URL.
pub fn hub_origin(hub: &str) -> String {
    reqwest::Url::parse(hub)
        .map(|u| u.origin().ascii_serialization())
        .unwrap_or_else(|_| "the configured hub".to_string())
}

/// Write one turn (the real-time per-turn hook path; the bulk sync uses
/// [`store_turns_bulk`]).
pub async fn store_full_turn(
    turn: &Turn,
    idx: usize,
    source_file: &str,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    let sid = session.unwrap_or("default");
    let snapshot = turn_snapshot(turn, idx, sid, source_file);
    let url = format!(
        "{}/api/sessions/{}/turns/{}?ref={}",
        hub,
        crate::urlencoding(sid),
        idx,
        crate::urlencoding(branch),
    );
    let mut req = client.post(url).json(&snapshot);
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    let _ = req.send().await;
}

/// Write every full turn for a session in ONE request → one graph commit.
///
/// Replaces N per-turn POSTs (N commits, N write-transactions) with a single
/// `PUT /api/sessions/{sid}/turns` — the change that takes a full sync from
/// hours to minutes. `turns` are keyed `t0000`, `t0001`, … so they sort and
/// land exactly where the per-turn path put them.
pub async fn store_turns_bulk(
    turns: &[Turn],
    source_file: &str,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) -> usize {
    let sid = session.unwrap_or("default");
    let mut map = serde_json::Map::with_capacity(turns.len());
    for (idx, turn) in turns.iter().enumerate() {
        map.insert(
            format!("t{idx:04}"),
            turn_snapshot(turn, idx, sid, source_file),
        );
    }
    let url = format!(
        "{}/api/sessions/{}/turns?ref={}",
        hub,
        crate::urlencoding(sid),
        crate::urlencoding(branch),
    );
    let mut req = client.put(url).json(&serde_json::Value::Object(map));
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    // A silent failure here loses a session's entire transcript, so surface
    // the reason rather than returning 0 quietly.
    match req.send().await {
        Ok(r) if r.status().is_success() => turns.len(),
        Ok(r) => {
            let st = r.status();
            let b = r.text().await.unwrap_or_default();
            eprintln!(
                "  bulk turn write for {sid} failed: {st} {}",
                b.lines().next().unwrap_or("").trim()
            );
            0
        }
        Err(e) => {
            eprintln!("  bulk turn write for {sid} errored: {e}");
            0
        }
    }
}

/// Max length of a derived session title (chars), before an ellipsis.
const TITLE_MAX_CHARS: usize = 70;

/// True when a user message is substantive enough to title a session by.
///
/// Skips the noise Claude Code injects as `user`-role entries: slash commands
/// (`/clear`, `/init`), XML-ish meta wrappers (`<command-name>`,
/// `<local-command-stdout>`, `<system-reminder>`), and the caveat preamble.
/// Tool-result echoes are already dropped upstream — `parse_turns` only keeps
/// user text extracted from `text` blocks, so a tool_result turn arrives here
/// as empty and is filtered by the `is_empty` guard.
fn is_substantive_user_text(text: &str) -> bool {
    let t = text.trim();
    if t.is_empty() {
        return false;
    }
    // Slash-command invocations (the whole message is the command).
    if t.starts_with('/') {
        return false;
    }
    // Meta/wrapper blocks Claude Code emits as user turns.
    if t.starts_with('<') {
        return false;
    }
    if t.starts_with("Caveat:") {
        return false;
    }
    // Require at least one alphanumeric char so pure punctuation is skipped.
    t.chars().any(|c| c.is_alphanumeric())
}

/// Derive a session title from parsed turns: the first substantive user
/// message, truncated to [`TITLE_MAX_CHARS`]. Returns `None` when no turn
/// qualifies (caller supplies the `<project> · <date>` fallback).
pub fn derive_session_title(turns: &[Turn]) -> Option<String> {
    let raw = turns
        .iter()
        .map(|t| t.user_text.as_str())
        .find(|txt| is_substantive_user_text(txt))?;
    // Collapse internal whitespace/newlines into single spaces for a clean
    // one-line title.
    let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
    Some(truncate_title(&collapsed))
}

/// Truncate to [`TITLE_MAX_CHARS`] on a char boundary, appending an ellipsis
/// when the text was cut.
pub fn truncate_title(s: &str) -> String {
    if s.chars().count() <= TITLE_MAX_CHARS {
        return s.to_string();
    }
    let truncated: String = s.chars().take(TITLE_MAX_CHARS).collect();
    format!("{}…", truncated.trim_end())
}

/// Persist a session's human-readable title at `/sessions/{session}/title`
/// via the Hub. Idempotent — re-ingesting overwrites. No-op on empty title.
pub async fn store_session_title(
    title: &str,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    if title.trim().is_empty() {
        return;
    }
    let sid = session.unwrap_or("default");
    let url = format!(
        "{}/api/sessions/{}/title?ref={}",
        hub,
        crate::urlencoding(sid),
        crate::urlencoding(branch),
    );
    let mut req = client.put(url).json(&serde_json::json!(title));
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    let _ = req.send().await;
}

/// Persist a session's meta object `{source, started_at, updated_at}` at
/// `/sessions/{session}/meta` via the Hub. Idempotent; drives the Lens
/// agent-type filter and date sort. No-op when all fields are empty.
#[allow(clippy::too_many_arguments)]
pub async fn store_session_meta(
    source: &str,
    started_at: &str,
    updated_at: &str,
    models_used: &[String],
    // The source's change-detector, stored so the next sync can skip an
    // unchanged transcript without parsing or re-writing it.
    fingerprint: Option<&str>,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    if source.is_empty() && started_at.is_empty() && updated_at.is_empty() && models_used.is_empty()
    {
        return;
    }
    let sid = session.unwrap_or("default");
    let url = format!(
        "{}/api/sessions/{}/meta?ref={}",
        hub,
        crate::urlencoding(sid),
        crate::urlencoding(branch),
    );
    let mut meta = serde_json::Map::new();
    if !source.is_empty() {
        meta.insert("source".into(), serde_json::json!(source));
    }
    if !started_at.is_empty() {
        meta.insert("started_at".into(), serde_json::json!(started_at));
    }
    if !updated_at.is_empty() {
        meta.insert("updated_at".into(), serde_json::json!(updated_at));
    }
    if !models_used.is_empty() {
        meta.insert("models_used".into(), serde_json::json!(models_used));
    }
    if let Some(fp) = fingerprint {
        meta.insert("fp".into(), serde_json::json!(fp));
    }
    let mut req = client.put(url).json(&serde_json::Value::Object(meta));
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    let _ = req.send().await;
}

/// Read the fingerprint stored on a session's last ingest, if any.
///
/// One small GET (the meta node) that decides whether the whole session can
/// be skipped — cheap next to the hundreds of writes a full ingest costs.
/// Any failure (no such session, older hub, unreachable) returns `None`, which
/// means "not known unchanged" → the session is ingested, never wrongly
/// skipped.
pub async fn fetch_stored_fingerprint(
    hub: &str,
    branch: &str,
    session: &str,
    client: &reqwest::Client,
) -> Option<String> {
    let url = format!(
        "{}/api/state/{}?path=/sessions/{}/meta",
        hub,
        crate::urlencoding(branch),
        crate::urlencoding(session),
    );
    let resp = client.get(url).send().await.ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let v: Value = resp.json().await.ok()?;
    v.get("fp").and_then(|f| f.as_str()).map(str::to_string)
}

/// Roll a session's turns up into the provenance summary.
///
/// Reports **every** branch the session touched with its turn count, not a
/// single dominant one: 7 of the 12 largest transcripts measured span more
/// than one branch, so collapsing to one label would be wrong more often than
/// not. Branch names are kept verbatim, `HEAD` included — a detached HEAD is
/// what a worktree session legitimately ran on.
///
/// Returns `None` when no turn carried provenance, so callers can skip the
/// write entirely rather than store an empty object that a reader could not
/// distinguish from "this session ran nowhere".
pub fn build_provenance(turns: &[Turn]) -> Option<serde_json::Value> {
    let mut cwds: Vec<String> = Vec::new();
    // (branch, turns, first_ts, last_ts, commit) in first-seen order, which
    // keeps the list stable across re-ingests of the same transcript.
    let mut branches: Vec<(String, u64, String, String, Option<String>)> = Vec::new();

    for t in turns {
        if let Some(c) = &t.cwd
            && !cwds.iter().any(|x| x == c)
        {
            cwds.push(c.clone());
        }
        // A turn can touch more than one branch; each gets the credit.
        for b in &t.git_branches {
            match branches.iter_mut().find(|(name, ..)| name == b) {
                Some((_, count, first, last, commit)) => {
                    *count += 1;
                    if !t.timestamp.is_empty() {
                        if first.is_empty() || t.timestamp < *first {
                            *first = t.timestamp.clone();
                        }
                        if t.timestamp > *last {
                            *last = t.timestamp.clone();
                        }
                    }
                    if commit.is_none() {
                        *commit = t.git_commit.clone();
                    }
                }
                None => branches.push((
                    b.clone(),
                    1,
                    t.timestamp.clone(),
                    t.timestamp.clone(),
                    t.git_commit.clone(),
                )),
            }
        }
    }

    if cwds.is_empty() && branches.is_empty() {
        return None;
    }

    // Busiest branch first: the eye should land on where the work happened,
    // while the long tail stays visible.
    branches.sort_by(|a, b| b.1.cmp(&a.1));

    let branches: Vec<serde_json::Value> = branches
        .into_iter()
        .map(|(branch, turns, first_ts, last_ts, commit_hash)| {
            let mut o = serde_json::Map::new();
            o.insert("branch".into(), serde_json::json!(branch));
            o.insert("turns".into(), serde_json::json!(turns));
            if !first_ts.is_empty() {
                o.insert("first_ts".into(), serde_json::json!(first_ts));
            }
            if !last_ts.is_empty() {
                o.insert("last_ts".into(), serde_json::json!(last_ts));
            }
            if let Some(c) = commit_hash {
                o.insert("commit_hash".into(), serde_json::json!(c));
            }
            serde_json::Value::Object(o)
        })
        .collect();

    let mut out = serde_json::Map::new();
    if !cwds.is_empty() {
        out.insert("cwds".into(), serde_json::json!(cwds));
    }
    if !branches.is_empty() {
        out.insert("branches".into(), serde_json::json!(branches));
    }
    Some(serde_json::Value::Object(out))
}

/// Persist the provenance rollup at `/sessions/{session}/provenance`.
///
/// Separate from `meta` on purpose: `meta` has a fixed shape the Lens filters
/// read and a different writer, so widening it would risk existing readers for
/// no gain.
#[allow(clippy::too_many_arguments)]
pub async fn store_session_provenance(
    provenance: &serde_json::Value,
    namespace: Option<&str>,
    project_id: Option<&str>,
    source_file: &str,
    archived: bool,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    let sid = session.unwrap_or("default");
    let url = format!(
        "{}/api/sessions/{}/provenance?ref={}",
        hub,
        crate::urlencoding(sid),
        crate::urlencoding(branch),
    );
    let mut body = provenance.as_object().cloned().unwrap_or_default();
    if let Some(ns) = namespace {
        body.insert("namespace".into(), serde_json::json!(ns));
    }
    if let Some(p) = project_id {
        body.insert("project_id".into(), serde_json::json!(p));
    }
    if !source_file.is_empty() {
        body.insert("source_file".into(), serde_json::json!(source_file));
    }
    if archived {
        // A state, not a deletion — an archived Codex session is still real
        // history and still ingests.
        body.insert("archived".into(), serde_json::json!(true));
    }
    // Which machine the session ran on (ctx-hub-sync t-001).
    if let Some(device) = crate::device::device_id() {
        body.insert("device".into(), serde_json::json!(device));
    }
    let mut req = client.put(url).json(&serde_json::Value::Object(body));
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    let _ = req.send().await;
}

/// Persist a session's burn summary at `/sessions/{session}/burn`.
///
/// Stored so the dashboard's burn board can rank sessions without
/// re-downloading and re-scanning every transcript. The body carries the
/// session's `updated_at`, so a reader can tell a current score from a stale
/// one and skip the transcript only when they match.
pub async fn store_session_burn(
    burn: &serde_json::Value,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    let sid = session.unwrap_or("default");
    let url = format!(
        "{}/api/sessions/{}/burn?ref={}",
        hub,
        crate::urlencoding(sid),
        crate::urlencoding(branch),
    );
    let mut req = client.put(url).json(burn);
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    let _ = req.send().await;
}

/// Whether a model reports `input_tokens` with the cached tokens inside them,
/// as OpenAI and Codex models do, where Anthropic reports them apart. Kept in
/// lockstep with `is_openai_family` in the Hub's `http.rs`, whose backfill from
/// stored turns this rollup must agree with, and with web/src/lib/pricing.ts.
fn is_openai_family(model: &str) -> bool {
    let m = model.to_ascii_lowercase();
    m.starts_with("gpt-")
        || m.starts_with("codex")
        || m.starts_with("o1")
        || m.starts_with("o3")
        || m.starts_with("o4")
}

/// The session's LLM usage by model, from every turn of its transcript
/// (ctx-hub-sync t-005): `{by_model: {<model>: {input_tokens, output_tokens,
/// cache_read_tokens, cache_create_tokens, call_count}}, last_model}`.
///
/// It follows the Hub's backfill from stored turns exactly, so a Hub that has
/// the turns and one that has only this agree: turns with no real model
/// (empty, `unknown`, or a `<synthetic>`-style marker) are skipped, and an
/// OpenAI-family model's cached tokens come out of its input.
pub fn session_usage(turns: &[Turn]) -> Value {
    let mut by_model: BTreeMap<String, Value> = BTreeMap::new();
    let mut last_model = None;
    for turn in turns {
        let model = turn.model.as_str();
        if model.is_empty() || model == "unknown" || model.starts_with('<') {
            continue;
        }
        let t = &turn.tokens;
        let input = if is_openai_family(model) {
            t.input.saturating_sub(t.cache_read)
        } else {
            t.input
        };
        let entry = by_model.entry(model.to_string()).or_insert_with(|| {
            serde_json::json!({
                "input_tokens": 0u64,
                "output_tokens": 0u64,
                "cache_read_tokens": 0u64,
                "cache_create_tokens": 0u64,
                "call_count": 0u64,
            })
        });
        for (field, n) in [
            ("input_tokens", input),
            ("output_tokens", t.output),
            ("cache_read_tokens", t.cache_read),
            ("cache_create_tokens", t.cache_creation),
            ("call_count", 1),
        ] {
            let sum = entry[field].as_u64().unwrap_or(0) + n;
            entry[field] = sum.into();
        }
        last_model = Some(model.to_string());
    }
    serde_json::json!({ "by_model": by_model, "last_model": last_model })
}

/// What became of a usage rollup sent to the Hub.
#[derive(Debug, PartialEq)]
pub enum UsageStored {
    Stored,
    /// The Hub predates `PUT /api/sessions/{sid}/usage`.
    NotSupported,
    Failed,
}

/// Send the session's usage rollup (`session_usage`) to the Hub, which keeps
/// it in the session's envelope and replaces its per-model split with it.
pub async fn store_session_usage(
    usage: &Value,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) -> UsageStored {
    let sid = session.unwrap_or("default");
    let url = format!(
        "{}/api/sessions/{}/usage?ref={}",
        hub,
        crate::urlencoding(sid),
        crate::urlencoding(branch),
    );
    let mut req = client.put(url).json(usage);
    if let Some(s) = session {
        req = req.header("X-CTXone-Session", s);
    }
    match req.send().await {
        Ok(r) if r.status().is_success() => UsageStored::Stored,
        Ok(r) if matches!(r.status().as_u16(), 404 | 405) => UsageStored::NotSupported,
        _ => UsageStored::Failed,
    }
}

pub async fn store_memory(
    mem: &ExtractedMemory,
    hub: &str,
    branch: &str,
    session: Option<&str>,
    client: &reqwest::Client,
) {
    let body = serde_json::json!({
        "fact": mem.body,
        "path": mem.path,
        "importance": mem.importance,
        "context": mem.context,
        "ref": branch,
        "source": "ingest",
    });
    let mut req = client
        .post(format!("{}/api/memory/remember", hub))
        .json(&body);
    if let Some(sid) = session {
        req = req.header("X-CTXone-Session", sid);
    }
    let _ = req.send().await;
}

// ── File discovery ────────────────────────────────────────────────────────────

/// Find Claude Code session JSONL files for a given project directory.
///
/// Thin wrapper over the Claude Code [`SessionSource`](crate::sources::SessionSource);
/// kept so existing call sites keep working while sources are added.
pub fn find_session_files(project_dir: &Path) -> Vec<PathBuf> {
    use crate::sources::SessionSource;
    crate::sources::ClaudeCode
        .discover_for_project(project_dir)
        .into_iter()
        .map(|r| r.path)
        .collect()
}

/// Find the single most-recent session file (for capture-turn).
pub fn latest_session_file(project_dir: &Path) -> Option<PathBuf> {
    find_session_files(project_dir).into_iter().last()
}

/// Scan EVERY project under `~/.claude/projects/*` for Claude Code session
/// JSONL files and return them grouped by project as `(label, files)` pairs.
///
/// Each subdirectory of `~/.claude/projects/` is a hashed project path
/// (Claude Code replaces `/` with `-`). We derive a short human-readable
/// `label` from the last two path components of the recovered path so
/// `ctx ingest-session --all` can report per-project counts. Files within
/// each project are sorted oldest-first (by mtime); projects are sorted by
/// label for stable output. Projects with no `.jsonl` files are omitted.
///
/// This is the `--all` counterpart to [`find_session_files`], which scans
/// only the single project matching a given directory.
pub fn find_all_session_files() -> Vec<(String, Vec<PathBuf>)> {
    use crate::sources::SessionSource;
    crate::sources::group_by_label(crate::sources::ClaudeCode.discover_all())
}

/// Return the last N turns from a session file (for per-turn hook capture).
pub fn last_turns(path: &Path, n: usize) -> Vec<Turn> {
    let all = parse_turns(path);
    let skip = all.len().saturating_sub(n);
    all.into_iter().skip(skip).collect()
}

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

    #[test]
    fn hubs_on_this_machine_are_local() {
        for hub in [
            "http://localhost:3001",
            "http://LOCALHOST:3001/",
            "http://ctx.localhost:3001",
            "http://127.0.0.1:3001",
            "http://127.1.2.3",
            "http://[::1]:3001",
            "http://[::ffff:127.0.0.1]:3001",
            "http://0.0.0.0:3001",
            "http://[::]:3001",
            "https://user:secret@127.0.0.1:3001/base",
        ] {
            assert!(hub_is_local(hub), "{hub} should be local");
        }
    }

    #[test]
    fn every_other_hub_is_remote() {
        for hub in [
            "https://alice.ctxone.example/",
            "http://192.168.1.20:3001",
            "http://10.0.0.5:3001",
            "http://[2001:db8::1]:3001",
            "http://localhost.example.com:3001",
            "http://notlocalhost:3001",
            "not a url",
            "",
        ] {
            assert!(!hub_is_local(hub), "{hub:?} should be remote");
        }
    }

    #[test]
    fn hub_origin_drops_credentials_and_path() {
        assert_eq!(
            hub_origin("https://user:secret@hub.example:8443/base?x=1"),
            "https://hub.example:8443"
        );
        assert_eq!(hub_origin("not a url"), "the configured hub");
    }

    #[test]
    fn session_analysis_parses_summary_and_topics() {
        let json = r#"{"summary":"did X then Y",
            "topics":[{"start":0,"end":3,"label":"setup","summary":"set up repo"},
                      {"start":4,"end":9,"label":"bugfix","summary":"fixed panic"}]}"#;
        let a: SessionAnalysis = serde_json::from_str(json).unwrap();
        assert_eq!(a.summary, "did X then Y");
        assert_eq!(a.topics.len(), 2);
        assert_eq!(a.topics[1].label, "bugfix");
        assert_eq!(a.topics[1].start, 4);
        // Tolerates a missing topic summary.
        let a2: SessionAnalysis =
            serde_json::from_str(r#"{"summary":"s","topics":[{"start":0,"end":1,"label":"x"}]}"#)
                .unwrap();
        assert_eq!(a2.topics[0].summary, "");
    }

    #[test]
    fn first_line_takes_first_nonblank_trimmed() {
        assert_eq!(
            first_line("\n\n  hello world  \nsecond", 100),
            "hello world"
        );
        assert_eq!(first_line("verylongword", 4), "very");
        assert_eq!(first_line("", 10), "");
    }

    #[test]
    fn extraction_provider_parse_accepts_aliases() {
        use ExtractionProvider::*;
        assert_eq!(ExtractionProvider::parse("anthropic"), Some(Anthropic));
        assert_eq!(ExtractionProvider::parse("Claude"), Some(Anthropic));
        assert_eq!(ExtractionProvider::parse("openai"), Some(OpenAi));
        assert_eq!(ExtractionProvider::parse("gemini"), Some(Gemini));
        assert_eq!(ExtractionProvider::parse("google"), Some(Gemini));
        assert_eq!(
            ExtractionProvider::parse("openai-compatible"),
            Some(OpenAiCompatible)
        );
        assert_eq!(ExtractionProvider::parse("nope"), None);
    }

    #[test]
    fn provider_key_env_and_slug() {
        assert_eq!(ExtractionProvider::Anthropic.key_env(), "ANTHROPIC_API_KEY");
        assert_eq!(ExtractionProvider::OpenAi.key_env(), "OPENAI_API_KEY");
        assert_eq!(
            ExtractionProvider::OpenAiCompatible.key_env(),
            "OPENAI_API_KEY"
        );
        assert_eq!(ExtractionProvider::Gemini.key_slug(), "gemini");
    }

    #[test]
    fn shellexpand_home_expands_leading_tilde() {
        // Absolute paths pass through; `~/` expands under $HOME (no env mutation,
        // so we assert the suffix rather than the full path).
        assert_eq!(shellexpand_home("/abs/path"), "/abs/path");
        assert!(shellexpand_home("~/.ctxone/k").ends_with("/.ctxone/k"));
    }

    #[test]
    fn extraction_watermark_is_monotonic_and_per_session() {
        let dir = std::env::temp_dir().join(format!("ctx-wm-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let p = dir.join("watermarks.json");

        assert_eq!(load_watermarks_at(&p).get("s1").copied().unwrap_or(0), 0);

        set_watermark_at(&p, "s1", 3);
        assert_eq!(load_watermarks_at(&p)["s1"], 3);

        // Monotonic: a lower count does not rewind.
        set_watermark_at(&p, "s1", 2);
        assert_eq!(load_watermarks_at(&p)["s1"], 3);

        // Advances forward.
        set_watermark_at(&p, "s1", 5);
        assert_eq!(load_watermarks_at(&p)["s1"], 5);

        // Independent per session.
        set_watermark_at(&p, "codex:abc", 1);
        assert_eq!(load_watermarks_at(&p)["codex:abc"], 1);
        assert_eq!(load_watermarks_at(&p)["s1"], 5);

        let _ = std::fs::remove_dir_all(&dir);
    }

    fn turn_on(branches: &[&str], ts: &str) -> Turn {
        Turn {
            user_text: "u".into(),
            assistant_text: "a".into(),
            tool_calls: vec![],
            tool_calls_raw: vec![],
            tokens: TurnTokens::default(),
            model: "m".into(),
            timestamp: ts.into(),
            cwd: Some("/repo".into()),
            git_branches: branches.iter().map(|s| s.to_string()).collect(),
            git_commit: None,
        }
    }

    fn turn_using(model: &str, input: u64, output: u64, cache_read: u64) -> Turn {
        let mut t = turn_on(&["main"], "2026-05-01T00:00:00Z");
        t.model = model.into();
        t.tokens = TurnTokens {
            input,
            output,
            cache_read,
            cache_creation: 2,
            extra: BTreeMap::new(),
        };
        t
    }

    #[test]
    fn session_usage_sums_each_model_and_skips_placeholders() {
        let turns = vec![
            turn_using("claude-opus-4-8", 100, 10, 50),
            turn_using("<synthetic>", 999, 999, 999),
            turn_using("claude-opus-4-8", 200, 20, 60),
            turn_using("", 999, 999, 999),
            turn_using("unknown", 999, 999, 999),
            turn_using("gpt-5.5", 1000, 30, 400),
        ];
        let u = session_usage(&turns);
        let opus = &u["by_model"]["claude-opus-4-8"];
        assert_eq!(opus["input_tokens"], 300);
        assert_eq!(opus["output_tokens"], 30);
        assert_eq!(opus["cache_read_tokens"], 110);
        assert_eq!(opus["cache_create_tokens"], 4);
        assert_eq!(opus["call_count"], 2);
        // OpenAI counts cached tokens inside input; the rollup takes them out,
        // as the Hub's backfill from stored turns does.
        assert_eq!(u["by_model"]["gpt-5.5"]["input_tokens"], 600);
        assert_eq!(u["by_model"]["gpt-5.5"]["cache_read_tokens"], 400);
        assert_eq!(u["by_model"].as_object().unwrap().len(), 2);
        assert_eq!(u["last_model"], "gpt-5.5");
    }

    #[test]
    fn session_usage_of_no_turns_is_empty() {
        let u = session_usage(&[]);
        assert_eq!(u["by_model"], serde_json::json!({}));
        assert!(u["last_model"].is_null());
    }

    #[test]
    fn provenance_lists_every_branch_not_just_the_dominant_one() {
        // The whole point: a session is not one branch. Measured on real
        // transcripts, 7 of the 12 largest spanned several.
        let turns = vec![
            turn_on(&["main"], "2026-05-01T00:00:00Z"),
            turn_on(&["feature"], "2026-05-02T00:00:00Z"),
            turn_on(&["feature"], "2026-05-03T00:00:00Z"),
        ];
        let p = build_provenance(&turns).expect("has provenance");
        let branches = p["branches"].as_array().unwrap();
        assert_eq!(branches.len(), 2);
        // Busiest first.
        assert_eq!(branches[0]["branch"], "feature");
        assert_eq!(branches[0]["turns"], 2);
        assert_eq!(branches[1]["branch"], "main");
        assert_eq!(branches[0]["first_ts"], "2026-05-02T00:00:00Z");
        assert_eq!(branches[0]["last_ts"], "2026-05-03T00:00:00Z");
    }

    #[test]
    fn provenance_counts_a_turn_that_touched_two_branches_under_both() {
        // A checkout mid-turn: the user typed on one branch, the agent worked
        // on another. Attributing the turn to only one silently loses a branch.
        let turns = vec![turn_on(&["old", "new"], "2026-05-01T00:00:00Z")];
        let p = build_provenance(&turns).unwrap();
        let names: Vec<&str> = p["branches"]
            .as_array()
            .unwrap()
            .iter()
            .map(|b| b["branch"].as_str().unwrap())
            .collect();
        assert!(names.contains(&"old") && names.contains(&"new"));
    }

    #[test]
    fn provenance_keeps_head_verbatim() {
        // Detached HEAD is what a worktree session legitimately ran on;
        // normalising it away would erase real signal.
        let p = build_provenance(&[turn_on(&["HEAD"], "2026-05-01T00:00:00Z")]).unwrap();
        assert_eq!(p["branches"][0]["branch"], "HEAD");
    }

    #[test]
    fn provenance_is_none_when_nothing_was_recorded() {
        // Distinguishes "predates provenance capture" from "ran nowhere", so
        // the caller can skip the write instead of storing an empty object.
        let mut t = turn_on(&[], "2026-05-01T00:00:00Z");
        t.cwd = None;
        assert!(build_provenance(&[t]).is_none());
    }

    #[test]
    fn strip_synthetic_removes_task_notification() {
        let raw = "<task-notification>\n<task-id>abc</task-id>\n<summary>Agent finished</summary>\n</task-notification>";
        assert_eq!(strip_synthetic_blocks(raw), "");
    }

    #[test]
    fn strip_synthetic_keeps_genuine_and_drops_reminder() {
        let raw = "Do the thing.\n<system-reminder>internal context</system-reminder>";
        assert_eq!(strip_synthetic_blocks(raw), "Do the thing.");
    }

    #[test]
    fn strip_synthetic_removes_local_command_blocks() {
        let raw = "<local-command-caveat>Caveat: …</local-command-caveat>\n<local-command-stdout>Set model to x</local-command-stdout>";
        assert_eq!(strip_synthetic_blocks(raw), "");
    }

    #[test]
    fn strip_synthetic_leaves_plain_user_text_untouched() {
        let raw = "Just a normal message with < and > but no synthetic tags.";
        assert_eq!(strip_synthetic_blocks(raw), raw);
    }

    #[test]
    fn truncate_shorter_than_limit_is_unchanged() {
        assert_eq!(truncate_on_char_boundary("hello", 120), "hello");
    }

    #[test]
    fn truncate_backs_up_off_a_multibyte_boundary() {
        // Em-dash '—' is 3 bytes. Build a string whose byte 120 lands INSIDE
        // it — the exact case that panicked `&c[..120]` on real transcripts.
        let s = format!("{}—tail", "x".repeat(118)); // '—' occupies bytes 118..121
        assert!(!s.is_char_boundary(120));
        let out = truncate_on_char_boundary(&s, 120);
        // Cut backed up to byte 118 (start of the em-dash), never panicking.
        assert_eq!(out.len(), 118);
        assert_eq!(out, "x".repeat(118));
    }

    #[test]
    fn truncate_on_exact_boundary_keeps_full_bytes() {
        let s = "abcdef";
        assert_eq!(truncate_on_char_boundary(s, 6), "abcdef");
        assert_eq!(truncate_on_char_boundary(s, 3), "abc");
    }

    #[test]
    fn extract_tool_calls_survives_long_unicode_bash_command() {
        // Regression: a Bash command with a multibyte char straddling byte 120
        // must summarize without panicking.
        let cmd = format!("echo {}—done", "a".repeat(130));
        let msg = serde_json::json!({
            "content": [
                { "type": "tool_use", "name": "Bash", "input": { "command": cmd } }
            ]
        });
        let calls = extract_tool_calls(&msg);
        assert_eq!(calls.len(), 1);
        assert!(calls[0].starts_with("Bash: echo "));
    }
}