paceflow 0.2.4

Local-first CLI that turns AI coding session history and git metadata into engineering analytics.
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
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
use anyhow::Result;
use chrono::TimeZone;
use rusqlite::{Connection, OptionalExtension, params};
use serde::Deserialize;
use serde_json::Value as JsonValue;
use serde_json::value::RawValue;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::change_intel::line_hash::{diff_with_hashes, hash_line};
use crate::change_intel::types::{LineHashCount, LineSide, WriteMode};
use crate::ingest_progress::IngestProgressObserver;
use crate::path_utils::{
    detect_repo_root, normalize_filesystem_path, path_to_string, strip_file_scheme,
};

#[derive(Debug, Clone)]
pub(crate) struct CursorSessionGraph {
    pub composer_id: String,
    pub source_file: String,
    pub created_at_ms: Option<i64>,
    pub last_updated_at_ms: Option<i64>,
    pub started_at: Option<String>,
    pub ended_at: Option<String>,
    pub project_path: Option<String>,
    pub model_name: Option<String>,
    pub subtitle: Option<String>,
    pub files_changed_count: Option<i64>,
    pub total_lines_added: Option<i64>,
    pub total_lines_removed: Option<i64>,
    pub conversation_messages: Vec<CursorBubbleEvent>,
    pub bubble_events: Vec<CursorBubbleEvent>,
    pub tool_calls: Vec<CursorToolCall>,
    pub checkpoint_paths: HashSet<String>,
    pub strong_path_hints: HashSet<String>,
    pub weak_path_hints: HashSet<String>,
    pub original_file_states: HashMap<String, CursorOriginalFileState>,
    pub partial_targets: Vec<CursorPartialTarget>,
    pub legacy_targets: Vec<CursorLegacyTarget>,
    pub inline_hints: Vec<CursorInlineHint>,
    pub inline_undo_rows: Vec<CursorInlineUndoRow>,
    pub partial_fates: HashMap<String, JsonValue>,
    pub legacy_diff_payloads: HashMap<String, JsonValue>,
    /// Content-addressed edit blobs referenced by tool calls via
    /// `beforeContentId`/`afterContentId`, keyed by their full content-store key
    /// (e.g. `composer.content.<hash>`). Populated after tool calls are parsed.
    pub content_blobs: HashMap<String, String>,
}

impl CursorSessionGraph {
    pub fn last_seen_at(&self) -> Option<String> {
        self.ended_at.clone().or(self.started_at.clone())
    }

    pub fn messages(&self) -> &[CursorBubbleEvent] {
        if self.conversation_messages.is_empty() {
            &self.bubble_events
        } else {
            &self.conversation_messages
        }
    }

    /// For API-style token estimates, prefer hydrated `bubbleId:*` rows when present.
    /// Composer `conversation` can be empty while bubbles still hold the real exchange.
    pub(crate) fn events_for_text_token_estimate(&self) -> &[CursorBubbleEvent] {
        if !self.bubble_events.is_empty() {
            &self.bubble_events
        } else {
            &self.conversation_messages
        }
    }

    pub fn first_edit_path_by_bubble(&self) -> HashMap<String, String> {
        let mut out = HashMap::new();
        for (path, state) in &self.original_file_states {
            if let Some(bubble_id) = &state.first_edit_bubble_id {
                out.entry(bubble_id.clone()).or_insert_with(|| path.clone());
            }
        }
        out
    }

    pub fn is_candidate_edit_session(&self) -> bool {
        let subtitle = self.subtitle.as_deref().unwrap_or("").to_ascii_lowercase();

        self.files_changed_count.unwrap_or(0) > 0
            || self.total_lines_added.unwrap_or(0) > 0
            || self.total_lines_removed.unwrap_or(0) > 0
            || subtitle.contains("edited ")
            || subtitle.contains("updated ")
            || !self.partial_targets.is_empty()
            || !self.legacy_targets.is_empty()
            || !self.inline_hints.is_empty()
            || !self.inline_undo_rows.is_empty()
            || self.tool_calls.iter().any(|tool| tool.looks_like_write())
    }
}

#[derive(Debug, Clone)]
pub(crate) struct CursorBubbleEvent {
    pub role: Option<CursorBubbleRole>,
    pub text: Option<String>,
    pub order_key: i64,
    /// Per-message wall-clock timestamp (ISO-8601) sourced from the bubble's own
    /// `createdAt`. `None` for legacy inline `conversation` rows that don't carry one.
    pub timestamp: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CursorBubbleRole {
    User,
    Assistant,
}

#[derive(Debug, Clone)]
pub(crate) struct CursorToolCall {
    pub bubble_id: String,
    pub name: String,
    pub call_id: String,
    pub status: Option<String>,
    pub timestamp: Option<String>,
    pub path_hints: Vec<String>,
    pub patch_texts: Vec<String>,
    /// Newer Cursor agent edits store the diff by reference: the tool `result`
    /// carries `beforeContentId`/`afterContentId` that point at content-addressed
    /// blobs (the value is the full `cursorDiskKV` key, e.g.
    /// `composer.content.<hash>`) instead of an inline `streamingContent` patch.
    /// The referenced blobs are loaded into [`CursorSessionGraph::content_blobs`]
    /// during graph population.
    pub before_content_id: Option<String>,
    pub after_content_id: Option<String>,
}

impl CursorToolCall {
    pub fn looks_like_write(&self) -> bool {
        matches!(
            self.name.as_str(),
            "edit_file_v2" | "apply_patch" | "write_file" | "write_file_v2"
        )
    }

    pub fn can_emit_edit(&self) -> bool {
        if !self.looks_like_write() {
            return false;
        }

        if self.name == "apply_patch" {
            return self.status.as_deref() == Some("completed")
                || self
                    .patch_texts
                    .iter()
                    .any(|text| patch_has_real_changes(text));
        }

        self.status.as_deref() == Some("completed")
            && self
                .patch_texts
                .iter()
                .any(|text| patch_has_real_changes(text))
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct CursorOriginalFileState {
    pub content: Option<String>,
    pub first_edit_bubble_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct CursorPartialTarget {
    pub partial_id: String,
    pub abs_path: String,
}

#[derive(Debug, Clone)]
pub(crate) struct CursorLegacyTarget {
    pub diff_id: Option<String>,
    pub abs_path: String,
    pub version: i32,
    pub code_block_idx: i32,
    pub timestamp: Option<String>,
    pub content: Option<String>,
    pub bubble_id: Option<String>,
}

#[derive(Debug, Clone)]
pub(crate) struct CursorInlineHint {
    pub call_id: String,
    pub abs_path: String,
    pub timestamp: Option<String>,
    pub original_text_lines: Vec<String>,
}

#[derive(Debug, Clone)]
pub(crate) struct CursorInlineUndoRow {
    pub call_id: String,
    pub abs_path: String,
    pub timestamp: Option<String>,
    pub payload: JsonValue,
}

#[derive(Debug, Clone)]
pub(crate) struct ResolvedFileEdit {
    pub abs_path: String,
    pub call_id: String,
    pub op_index: i32,
    pub timestamp: Option<String>,
    pub write_mode: WriteMode,
    pub before_known: bool,
    pub added_lines: i64,
    pub removed_lines: i64,
    pub parser_name: String,
    pub line_hashes: Vec<LineHashCount>,
}

#[derive(Debug, Clone)]
pub(crate) struct AggregatedFileEdit {
    pub abs_path: String,
    pub added_lines: i64,
    pub removed_lines: i64,
    /// Earliest known edit timestamp for this path, so the accepted-change
    /// event reflects when the first edit actually happened.
    pub timestamp: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComposerData {
    composer_id: String,
    #[serde(default)]
    conversation: Vec<ConversationBubble>,
    #[serde(default)]
    full_conversation_headers_only: Vec<ConversationHeader>,
    total_lines_added: Option<i64>,
    total_lines_removed: Option<i64>,
    files_changed_count: Option<i64>,
    subtitle: Option<String>,
    context: Option<ComposerContext>,
    created_at: Option<i64>,
    last_updated_at: Option<i64>,
    #[serde(default)]
    code_block_data: HashMap<String, JsonValue>,
    #[serde(default)]
    all_attached_file_code_chunks_uris: Vec<String>,
    #[serde(default)]
    original_file_states: HashMap<String, JsonValue>,
}

#[derive(Debug, Clone, Deserialize)]
struct ConversationBubble {
    #[serde(rename = "type")]
    bubble_type: Option<i64>,
    text: Option<String>,
}

/// Minimal shape used by the hot `populate_bubbles` loop.
///
/// Bubble JSON values can be multi-hundred-KB each (tool args, streaming
/// content, etc.). Parsing them into a full `JsonValue` tree just to pull
/// out three fields was the dominant CPU cost on the Linux perf run
/// (frontend-bound ~46% on E-cores, 41% LLC-miss on P-cores).
///
/// `toolFormerData` is borrowed as `&RawValue` so we only materialize the
/// heavy tool-call sub-tree when we actually need it.
#[derive(Deserialize)]
struct BubbleSlim<'a> {
    #[serde(rename = "type")]
    bubble_type: Option<i64>,
    text: Option<String>,
    #[serde(rename = "modelInfo")]
    model_info: Option<ModelInfoSlim>,
    // Cursor stamps every bubble row with its own `createdAt`. Production data
    // stores it as an ISO-8601 string (e.g. "2026-06-01T07:19:41.178Z"); some
    // builds/fixtures use epoch-millis instead. Capture the raw value and
    // normalize later so we record real per-message timestamps instead of
    // collapsing the whole session onto the composer-level `createdAt`.
    #[serde(rename = "createdAt", default)]
    created_at: Option<JsonValue>,
    #[serde(rename = "toolFormerData", borrow, default)]
    tool_former_data: Option<&'a RawValue>,
}

#[derive(Deserialize)]
struct ModelInfoSlim {
    #[serde(rename = "modelName")]
    model_name: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
struct ConversationHeader {
    #[serde(rename = "bubbleId")]
    bubble_id: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ComposerContext {
    #[serde(default)]
    file_selections: Vec<FileSelection>,
}

#[derive(Debug, Clone, Deserialize)]
struct FileSelection {
    uri: Option<FileUri>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FileUri {
    fs_path: Option<String>,
}

pub(crate) fn load_cursor_session_graphs_from_rows_with_observer(
    vscdb: &Connection,
    source_file: &str,
    composer_rows: &[(String, String)],
    mut observer: Option<&mut dyn IngestProgressObserver>,
) -> Result<Vec<CursorSessionGraph>> {
    use rayon::prelude::*;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("seed graphs");
    }
    // `build_seed_graph` is pure CPU (`serde_json::from_str` twice on
    // potentially-large composer blobs). The Linux perf-stat showed the
    // ingest pinned at ~1.9 GHz on P-cores with 31-46% frontend-bound and
    // 41% LLC-miss - i.e. lots of serial JSON parsing - so this is the
    // cheap parallelism win. No sqlite is touched here; the writer stays
    // on the main thread.
    let mut graphs: Vec<CursorSessionGraph> = composer_rows
        .par_iter()
        .filter_map(|(key, raw)| build_seed_graph(key, raw, source_file))
        .collect();

    // Preserve the previous deterministic ordering (composer_rows order) so
    // downstream aggregation/snapshot tests don't depend on rayon scheduling.
    let order: HashMap<&str, usize> = composer_rows
        .iter()
        .enumerate()
        .map(|(i, (key, _))| (key.as_str(), i))
        .collect();
    graphs.sort_by_key(|g| {
        let key = format!("composerData:{}", g.composer_id);
        order.get(key.as_str()).copied().unwrap_or(usize::MAX)
    });

    let session_ids: HashSet<String> = graphs.iter().map(|g| g.composer_id.clone()).collect();

    populate_graph_details(vscdb, &mut graphs, &session_ids, observer)?;
    Ok(graphs)
}

#[cfg(test)]
pub(crate) fn load_cursor_session_graphs(
    vscdb: &Connection,
    source_file: &str,
) -> Result<Vec<CursorSessionGraph>> {
    load_cursor_session_graphs_with_observer(vscdb, source_file, None)
}

pub(crate) fn load_cursor_session_graphs_with_observer(
    vscdb: &Connection,
    source_file: &str,
    observer: Option<&mut dyn IngestProgressObserver>,
) -> Result<Vec<CursorSessionGraph>> {
    let mut stmt =
        vscdb.prepare("SELECT key, value FROM cursorDiskKV WHERE key LIKE 'composerData:%'")?;
    let rows = stmt
        .query_map([], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
        })?
        .filter_map(|row| match row {
            Ok((key, Some(value))) => Some(Ok((key, value))),
            Ok((_key, None)) => None,
            Err(err) => Some(Err(err)),
        })
        .collect::<std::result::Result<Vec<_>, _>>()?;

    load_cursor_session_graphs_from_rows_with_observer(vscdb, source_file, &rows, observer)
}

pub(crate) fn resolve_tool_call_edits(graph: &CursorSessionGraph) -> Vec<ResolvedFileEdit> {
    let first_edit_paths = graph.first_edit_path_by_bubble();
    let mut edits = Vec::new();

    for tool in &graph.tool_calls {
        let mut path_hints = tool.path_hints.clone();
        if path_hints.is_empty()
            && let Some(path) = first_edit_paths.get(&tool.bubble_id)
        {
            path_hints.push(path.clone());
        }
        if !tool.looks_like_write() {
            continue;
        }
        if path_hints.len() != 1 {
            continue;
        }

        let abs_path = path_hints[0].clone();

        // Newer agent edits reference before/after file content by id. Prefer
        // diffing those full snapshots when present; they are the source of truth
        // and also cover edits that carry no inline `streamingContent` patch.
        if let Some(edit) = resolve_content_edit(tool, graph, &abs_path) {
            edits.push(edit);
            continue;
        }

        if !tool.can_emit_edit() {
            continue;
        }

        let mut added_lines = Vec::new();
        let mut removed_lines = Vec::new();
        for patch in &tool.patch_texts {
            let (patch_added, patch_removed) = extract_patch_lines(patch);
            added_lines.extend(patch_added);
            removed_lines.extend(patch_removed);
        }

        if added_lines.is_empty() && removed_lines.is_empty() {
            continue;
        }

        let mut line_hashes = hash_counts_for_lines(&added_lines, LineSide::Added);
        line_hashes.extend(hash_counts_for_lines(&removed_lines, LineSide::Removed));

        edits.push(ResolvedFileEdit {
            abs_path,
            call_id: tool.call_id.clone(),
            op_index: 0,
            timestamp: tool.timestamp.clone().or_else(|| graph.last_seen_at()),
            write_mode: WriteMode::Patch,
            before_known: true,
            added_lines: added_lines.len() as i64,
            removed_lines: removed_lines.len() as i64,
            parser_name: format!("cursor_tool_{}_v1", tool.name),
            line_hashes,
        });
    }

    edits
}

/// Build a [`ResolvedFileEdit`] by diffing the before/after content blobs a tool
/// call references by id. Returns `None` when the edit uses the older inline
/// patch schema, the blobs are unavailable, or the diff is empty.
fn resolve_content_edit(
    tool: &CursorToolCall,
    graph: &CursorSessionGraph,
    abs_path: &str,
) -> Option<ResolvedFileEdit> {
    // Only completed edits carry a final, committed after-content snapshot.
    if tool.status.as_deref() != Some("completed") {
        return None;
    }

    let after_id = tool.after_content_id.as_ref()?;
    let after = graph.content_blobs.get(after_id)?;

    // A missing `beforeContentId` means a freshly created file: treat before as
    // empty so every line counts as added.
    let before_known = tool.before_content_id.is_some();
    let before = tool
        .before_content_id
        .as_ref()
        .and_then(|id| graph.content_blobs.get(id))
        .map(String::as_str)
        .unwrap_or("");

    // Cursor frequently stores the before snapshot with CRLF and the after with
    // LF (or vice versa) on Windows. `diff_with_hashes` diffs raw lines before
    // hashing, so a bare line-ending flip would mark every line as changed.
    // Normalize EOLs first so only real content edits are counted.
    let summary = diff_with_hashes(
        &normalize_line_endings(before),
        &normalize_line_endings(after),
    );
    if summary.added_lines == 0 && summary.removed_lines == 0 {
        return None;
    }

    Some(ResolvedFileEdit {
        abs_path: abs_path.to_string(),
        call_id: tool.call_id.clone(),
        op_index: 0,
        timestamp: tool.timestamp.clone().or_else(|| graph.last_seen_at()),
        write_mode: WriteMode::Patch,
        before_known,
        added_lines: summary.added_lines,
        removed_lines: summary.removed_lines,
        parser_name: format!("cursor_tool_{}_content_v1", tool.name),
        line_hashes: summary.line_hashes,
    })
}

pub(crate) fn aggregate_file_edits(edits: &[ResolvedFileEdit]) -> Vec<AggregatedFileEdit> {
    let mut by_path: HashMap<String, AggregatedFileEdit> = HashMap::new();
    for edit in edits {
        let entry = by_path
            .entry(edit.abs_path.clone())
            .or_insert(AggregatedFileEdit {
                abs_path: edit.abs_path.clone(),
                added_lines: 0,
                removed_lines: 0,
                timestamp: None,
            });
        entry.added_lines += edit.added_lines;
        entry.removed_lines += edit.removed_lines;
        // Keep the earliest timestamp across edits to the same path.
        entry.timestamp = min_timestamp(entry.timestamp.take(), edit.timestamp.clone());
    }

    let mut out: Vec<_> = by_path.into_values().collect();
    out.sort_by_key(|edit| edit.abs_path.clone());
    out
}

/// Return the earlier of two optional ISO-8601 timestamps. Lexicographic
/// comparison is correct for the zero-padded UTC strings Cursor emits.
fn min_timestamp(a: Option<String>, b: Option<String>) -> Option<String> {
    match (a, b) {
        (Some(a), Some(b)) => Some(if a <= b { a } else { b }),
        (Some(a), None) => Some(a),
        (None, b) => b,
    }
}

pub(crate) fn build_seed_graph(
    key: &str,
    raw: &str,
    source_file: &str,
) -> Option<CursorSessionGraph> {
    let raw_json: JsonValue = serde_json::from_str(raw).ok()?;
    let data: ComposerData = serde_json::from_str(raw).ok()?;

    let composer_id = raw_json
        .get("composerId")
        .and_then(|value| value.as_str())
        .map(ToOwned::to_owned)
        .or_else(|| key.strip_prefix("composerData:").map(ToOwned::to_owned))
        .unwrap_or(data.composer_id);

    let started_at = data.created_at.and_then(ms_to_iso);
    let ended_at = data.last_updated_at.and_then(ms_to_iso);

    let mut conversation_messages = Vec::new();
    for (idx, bubble) in data.conversation.iter().enumerate() {
        let role = match bubble.bubble_type {
            Some(1) => Some(CursorBubbleRole::User),
            Some(2) => Some(CursorBubbleRole::Assistant),
            _ => None,
        };
        conversation_messages.push(CursorBubbleEvent {
            role,
            text: bubble.text.clone(),
            order_key: idx as i64,
            timestamp: None,
        });
    }

    let original_file_states = extract_original_file_states(&data.original_file_states);
    let mut strong_path_hints = extract_strong_path_hints(
        data.context.as_ref(),
        &data.all_attached_file_code_chunks_uris,
        &data.code_block_data,
    );
    let weak_path_hints = extract_weak_path_hints(&original_file_states);
    let project_path = extract_project_path(
        data.context.as_ref(),
        &data.all_attached_file_code_chunks_uris,
        &data.original_file_states,
        &data.code_block_data,
    );

    for path in original_file_states.keys() {
        if !is_cursor_plan_path(path) {
            strong_path_hints.insert(path.clone());
        }
    }

    Some(CursorSessionGraph {
        composer_id,
        source_file: source_file.to_string(),
        created_at_ms: data.created_at,
        last_updated_at_ms: data.last_updated_at,
        started_at,
        ended_at,
        project_path: project_path.clone(),
        model_name: extract_model_name(&raw_json),
        subtitle: data.subtitle,
        files_changed_count: data.files_changed_count,
        total_lines_added: data.total_lines_added,
        total_lines_removed: data.total_lines_removed,
        conversation_messages,
        bubble_events: Vec::new(),
        tool_calls: Vec::new(),
        checkpoint_paths: HashSet::new(),
        strong_path_hints,
        weak_path_hints,
        original_file_states,
        partial_targets: extract_partial_targets(&data.code_block_data),
        legacy_targets: extract_legacy_targets(
            &data.code_block_data,
            ended_at_from_ms(data.last_updated_at, data.created_at),
        ),
        inline_hints: Vec::new(),
        inline_undo_rows: Vec::new(),
        partial_fates: HashMap::new(),
        legacy_diff_payloads: HashMap::new(),
        content_blobs: HashMap::new(),
    })
}

fn populate_graph_details(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    session_ids: &HashSet<String>,
    mut observer: Option<&mut dyn IngestProgressObserver>,
) -> Result<()> {
    if graphs.is_empty() {
        return Ok(());
    }

    let mut by_session: HashMap<String, usize> = HashMap::new();
    for (idx, graph) in graphs.iter().enumerate() {
        by_session.insert(graph.composer_id.clone(), idx);
    }

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("bubbles");
    }
    populate_bubbles(vscdb, graphs, &by_session)?;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("tool content");
    }
    populate_tool_content(vscdb, graphs)?;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("checkpoints");
    }
    populate_checkpoints(vscdb, graphs, &by_session)?;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("inline undo rows");
    }
    populate_inline_undo_rows(vscdb, graphs, &by_session)?;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("inline hints");
    }
    populate_inline_hints(vscdb, graphs, &by_session)?;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("partial fates");
    }
    populate_partial_fates(vscdb, graphs, &by_session)?;

    if let Some(obs) = observer.as_mut() {
        obs.set_phase("legacy diffs");
    }
    populate_legacy_diffs(vscdb, graphs, session_ids, &by_session)?;

    Ok(())
}

fn populate_bubbles(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    by_session: &HashMap<String, usize>,
) -> Result<()> {
    let header_orders: HashMap<String, HashMap<String, i64>> = graphs
        .iter()
        .map(|graph| {
            let Some(raw_headers) = query_conversation_headers(vscdb, &graph.composer_id)
                .ok()
                .flatten()
            else {
                return (graph.composer_id.clone(), HashMap::new());
            };
            (graph.composer_id.clone(), raw_headers)
        })
        .collect();

    // Range-scan `cursorDiskKV` per session instead of doing one
    // `LIKE 'bubbleId:%'` over every bubble in the database. The old query
    // also touched bubbles belonging to unrelated (already-ingested, planned-
    // out) sessions, which on large state DBs is the dominant cost of ingest.
    //
    // `key` is the primary key of `cursorDiskKV`, so `>= lower AND < upper`
    // resolves to a bounded index scan. The upper bound uses `;` (0x3B) which
    // sorts immediately after `:` (0x3A), covering every `bubbleId:<sid>:*` key.
    let mut stmt =
        vscdb.prepare("SELECT rowid, key, value FROM cursorDiskKV WHERE key >= ?1 AND key < ?2")?;

    // Iterate session_ids in a stable order so tests that snapshot output stay
    // deterministic across runs; `by_session` is a HashMap whose iteration order
    // is randomized.
    let mut session_ids: Vec<&str> = by_session.keys().map(String::as_str).collect();
    session_ids.sort_unstable();

    for session_id in session_ids {
        let graph_idx = by_session[session_id];
        let lower = format!("bubbleId:{session_id}:");
        let upper = format!("bubbleId:{session_id};");
        let rows = stmt.query_map(params![lower, upper], |row| {
            Ok((
                row.get::<_, i64>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, Option<String>>(2)?,
            ))
        })?;

        for row in rows {
            let (rowid, key, raw) = match row {
                Ok(row) => row,
                Err(_) => continue,
            };
            let Some(raw) = raw else {
                continue;
            };
            // The range predicate guarantees this is a `bubbleId:<session_id>:<bubble_id>`
            // key, but we still split it to recover `bubble_id` for ordering.
            let Some((_, bubble_id)) = bubble_key_parts(&key) else {
                continue;
            };

            // Fast path: typed deserialize into a slim struct so the majority
            // of bubbles (no `toolFormerData`) never allocate a full
            // `JsonValue` tree. Only when `toolFormerData` is present do we
            // parse that sub-object into `JsonValue` for the tool-call path.
            let slim: BubbleSlim = match serde_json::from_str(&raw) {
                Ok(value) => value,
                Err(_) => continue,
            };

            let role = slim.bubble_type.and_then(map_bubble_role);
            let text = slim.text.clone();
            let bubble_ts = normalize_bubble_timestamp(slim.created_at.as_ref());
            let order_key = header_orders
                .get(session_id)
                .and_then(|headers| headers.get(bubble_id))
                .copied()
                .unwrap_or(rowid);
            let model_name = slim.model_info.as_ref().and_then(|m| m.model_name.clone());

            graphs[graph_idx].bubble_events.push(CursorBubbleEvent {
                role,
                text,
                order_key,
                timestamp: bubble_ts.clone(),
            });

            if graphs[graph_idx].model_name.is_none() {
                graphs[graph_idx].model_name = model_name;
            }

            // Tool-call path: parse the `toolFormerData` sub-object lazily.
            let Some(tool_former_raw) = slim.tool_former_data else {
                continue;
            };
            let tool_former_value: JsonValue = match serde_json::from_str(tool_former_raw.get()) {
                Ok(value) => value,
                Err(_) => continue,
            };

            // Prefer the originating bubble's own `createdAt` for the tool call so
            // accepted edits are stamped when they actually happened, rather than
            // falling back to the session-level `last_seen_at` (= composer end).
            if let Some(tool_call) = parse_tool_call(
                bubble_id,
                &tool_former_value,
                graphs[graph_idx].project_path.as_deref(),
                bubble_ts.or_else(|| graphs[graph_idx].last_seen_at()),
                &graphs[graph_idx].first_edit_path_by_bubble(),
            ) {
                for path in &tool_call.path_hints {
                    if !is_cursor_plan_path(path) {
                        graphs[graph_idx].strong_path_hints.insert(path.clone());
                    }
                }
                graphs[graph_idx].tool_calls.push(tool_call);
            }
        }
    }

    for graph in graphs.iter_mut() {
        graph.bubble_events.sort_by_key(|event| event.order_key);
    }

    Ok(())
}

/// Loads `bubbleId:*` rows for a single session so token estimation and tooling see the full transcript.
pub(crate) fn hydrate_session_bubbles(
    vscdb: &Connection,
    graph: &mut CursorSessionGraph,
) -> Result<()> {
    let mut graphs = vec![graph.clone()];
    let mut by_session = HashMap::new();
    by_session.insert(graph.composer_id.clone(), 0);
    populate_bubbles(vscdb, &mut graphs, &by_session)?;
    if let Some(updated) = graphs.pop() {
        *graph = updated;
    }
    Ok(())
}

/// Loads the content-addressed before/after edit blobs referenced by tool calls
/// (newer agent edits store the diff by id rather than inline). Fetches each
/// referenced key once and stashes it on every graph whose tool calls use it so
/// [`resolve_tool_call_edits`] can diff before→after without DB access.
fn populate_tool_content(vscdb: &Connection, graphs: &mut [CursorSessionGraph]) -> Result<()> {
    let mut needed: HashSet<String> = HashSet::new();
    for graph in graphs.iter() {
        for tool in &graph.tool_calls {
            if let Some(id) = &tool.before_content_id {
                needed.insert(id.clone());
            }
            if let Some(id) = &tool.after_content_id {
                needed.insert(id.clone());
            }
        }
    }
    if needed.is_empty() {
        return Ok(());
    }

    // Keys are the full content-store keys (e.g. `composer.content.<hash>`), which
    // are the primary key of `cursorDiskKV`, so each lookup is a point query.
    let mut stmt = vscdb.prepare("SELECT value FROM cursorDiskKV WHERE key = ?1")?;
    let mut blobs: HashMap<String, String> = HashMap::with_capacity(needed.len());
    for id in &needed {
        let raw: Option<String> = stmt
            .query_row(params![id], |row| row.get(0))
            .optional()
            .ok()
            .flatten();
        if let Some(raw) = raw {
            blobs.insert(id.clone(), raw);
        }
    }

    for graph in graphs.iter_mut() {
        let referenced: Vec<String> = graph
            .tool_calls
            .iter()
            .flat_map(|tool| {
                [
                    tool.before_content_id.clone(),
                    tool.after_content_id.clone(),
                ]
                .into_iter()
            })
            .flatten()
            .collect();
        for id in referenced {
            if let Some(content) = blobs.get(&id) {
                graph
                    .content_blobs
                    .entry(id)
                    .or_insert_with(|| content.clone());
            }
        }
    }

    Ok(())
}

fn populate_checkpoints(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    by_session: &HashMap<String, usize>,
) -> Result<()> {
    // See `populate_bubbles` for the rationale behind per-session range scans.
    let mut stmt =
        vscdb.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ?1 AND key < ?2")?;

    let mut session_ids: Vec<&str> = by_session.keys().map(String::as_str).collect();
    session_ids.sort_unstable();

    for session_id in session_ids {
        let graph_idx = by_session[session_id];
        let lower = format!("checkpointId:{session_id}:");
        let upper = format!("checkpointId:{session_id};");
        let rows = stmt.query_map(params![lower, upper], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
        })?;

        for row in rows {
            let (_key, raw) = match row {
                Ok(row) => row,
                Err(_) => continue,
            };
            let Some(raw) = raw else {
                continue;
            };

            let parsed: JsonValue = match serde_json::from_str(&raw) {
                Ok(value) => value,
                Err(_) => continue,
            };
            let Some(files) = parsed.get("files").and_then(|value| value.as_array()) else {
                continue;
            };
            for file in files {
                let Some(path) = file.get("uri").and_then(extract_file_path_from_uri_value) else {
                    continue;
                };
                if is_cursor_plan_path(&path) {
                    continue;
                }
                graphs[graph_idx].checkpoint_paths.insert(path.clone());
                graphs[graph_idx].strong_path_hints.insert(path);
            }
        }
    }

    Ok(())
}

fn populate_inline_undo_rows(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    by_session: &HashMap<String, usize>,
) -> Result<()> {
    let mut stmt = vscdb
        .prepare("SELECT key, value FROM cursorDiskKV WHERE key LIKE 'inlineDiffUndoRedo-%'")?;
    let rows = stmt.query_map([], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
    })?;

    for row in rows {
        let (key, raw) = match row {
            Ok(row) => row,
            Err(_) => continue,
        };
        let Some(raw) = raw else {
            continue;
        };
        let payload: JsonValue = match serde_json::from_str(&raw) {
            Ok(value) => value,
            Err(_) => continue,
        };
        let Some(session_id) = payload
            .get("composerMetadata")
            .and_then(|value| value.get("composerId"))
            .and_then(|value| value.as_str())
        else {
            continue;
        };
        let Some(graph_idx) = by_session.get(session_id).copied() else {
            continue;
        };
        let Some(abs_path) = payload
            .get("uri")
            .and_then(extract_file_path_from_uri_value)
            .filter(|path| !is_cursor_plan_path(path))
        else {
            continue;
        };

        graphs[graph_idx]
            .inline_undo_rows
            .push(CursorInlineUndoRow {
                call_id: key,
                abs_path,
                timestamp: payload
                    .get("createdAt")
                    .and_then(|value| value.as_i64())
                    .and_then(ms_to_iso),
                payload,
            });
    }

    Ok(())
}

fn populate_inline_hints(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    by_session: &HashMap<String, usize>,
) -> Result<()> {
    let mut stmt = vscdb.prepare("SELECT value FROM cursorDiskKV WHERE key LIKE 'inlineDiff:%'")?;
    let rows = stmt.query_map([], |row| row.get::<_, Option<String>>(0))?;

    for row in rows {
        let Some(raw) = row? else {
            continue;
        };
        let payload: JsonValue = match serde_json::from_str(&raw) {
            Ok(value) => value,
            Err(_) => continue,
        };
        let Some(session_id) = payload
            .get("composerMetadata")
            .and_then(|value| value.get("composerId"))
            .and_then(|value| value.as_str())
        else {
            continue;
        };
        let Some(graph_idx) = by_session.get(session_id).copied() else {
            continue;
        };
        let Some(abs_path) = payload
            .get("uri")
            .and_then(extract_file_path_from_uri_value)
            .filter(|path| !is_cursor_plan_path(path))
        else {
            continue;
        };

        graphs[graph_idx].inline_hints.push(CursorInlineHint {
            call_id: payload
                .get("composerMetadata")
                .and_then(|value| value.get("toolCallId"))
                .and_then(|value| value.as_str())
                .or_else(|| {
                    payload
                        .get("composerMetadata")
                        .and_then(|value| value.get("codeblockId"))
                        .and_then(|value| value.as_str())
                })
                .or_else(|| payload.get("diffId").and_then(|value| value.as_str()))
                .unwrap_or("inlineDiff")
                .to_string(),
            abs_path: abs_path.clone(),
            timestamp: payload
                .get("createdAt")
                .and_then(|value| value.as_i64())
                .and_then(ms_to_iso),
            original_text_lines: parse_string_array(payload.get("originalTextLines")),
        });
        graphs[graph_idx].strong_path_hints.insert(abs_path);
    }

    Ok(())
}

fn populate_partial_fates(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    by_session: &HashMap<String, usize>,
) -> Result<()> {
    let mut stmt = vscdb.prepare(
        "SELECT key, value FROM cursorDiskKV WHERE key LIKE 'codeBlockPartialInlineDiffFates:%'",
    )?;
    let rows = stmt.query_map([], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
    })?;

    for row in rows {
        let (key, raw) = match row {
            Ok(row) => row,
            Err(_) => continue,
        };
        let Some(raw) = raw else {
            continue;
        };
        let Some((session_id, partial_id)) = partial_fates_key_parts(&key) else {
            continue;
        };
        let Some(graph_idx) = by_session.get(session_id).copied() else {
            continue;
        };
        let payload: JsonValue = match serde_json::from_str(&raw) {
            Ok(value) => value,
            Err(_) => continue,
        };
        graphs[graph_idx]
            .partial_fates
            .insert(partial_id.to_string(), payload);
    }

    Ok(())
}

fn populate_legacy_diffs(
    vscdb: &Connection,
    graphs: &mut [CursorSessionGraph],
    session_ids: &HashSet<String>,
    by_session: &HashMap<String, usize>,
) -> Result<()> {
    let mut stmt =
        vscdb.prepare("SELECT key, value FROM cursorDiskKV WHERE key LIKE 'codeBlockDiff:%'")?;
    let rows = stmt.query_map([], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
    })?;

    for row in rows {
        let (key, raw) = match row {
            Ok(row) => row,
            Err(_) => continue,
        };
        let Some(raw) = raw else {
            continue;
        };
        let Some((session_id, diff_id)) = code_block_diff_key_parts(&key) else {
            continue;
        };
        if !session_ids.contains(session_id) {
            continue;
        }
        let Some(graph_idx) = by_session.get(session_id).copied() else {
            continue;
        };
        let payload: JsonValue = match serde_json::from_str(&raw) {
            Ok(value) => value,
            Err(_) => continue,
        };
        graphs[graph_idx]
            .legacy_diff_payloads
            .insert(diff_id.to_string(), payload);
    }

    Ok(())
}

fn parse_tool_call(
    bubble_id: &str,
    tool_former_data: &JsonValue,
    project_path: Option<&str>,
    default_timestamp: Option<String>,
    first_edit_paths: &HashMap<String, String>,
) -> Option<CursorToolCall> {
    // Callers pass the `toolFormerData` sub-object directly so that the common
    // "not a tool call" path in `populate_bubbles` can avoid allocating a full
    // `JsonValue` for the entire bubble.
    let tool = tool_former_data.as_object()?;
    let name = tool.get("name")?.as_str()?.to_string();
    let status = tool
        .get("status")
        .and_then(|value| value.as_str())
        .map(ToOwned::to_owned);
    let call_id = tool
        .get("toolCallId")
        .and_then(|value| value.as_str())
        .or_else(|| tool.get("callId").and_then(|value| value.as_str()))
        .unwrap_or(bubble_id)
        .to_string();

    let params_json = tool.get("params").and_then(jsonish_to_value);
    let result_json = tool.get("result").and_then(jsonish_to_value);
    let raw_args = tool.get("rawArgs").and_then(|value| value.as_str());

    let mut path_hints = Vec::new();
    if let Some(params_json) = params_json.as_ref() {
        collect_tool_paths(params_json, project_path, &mut path_hints);
    }
    if path_hints.is_empty()
        && let Some(path) = first_edit_paths.get(bubble_id)
    {
        path_hints.push(path.clone());
    }
    dedupe_vec(&mut path_hints);

    let mut patch_texts = Vec::new();
    if name == "edit_file_v2"
        && let Some(params_json) = params_json.as_ref()
        && let Some(streaming) = params_json
            .get("streamingContent")
            .and_then(|value| value.as_str())
    {
        patch_texts.push(streaming.to_string());
    }
    if name == "apply_patch" {
        if status.as_deref() == Some("completed")
            && let Some(raw_args) = raw_args
        {
            patch_texts.push(raw_args.to_string());
        }
        if let Some(result_json) = result_json.as_ref() {
            collect_result_diff_strings(result_json, &mut patch_texts);
        }
    }
    if matches!(name.as_str(), "write_file" | "write_file_v2")
        && let Some(result_json) = result_json.as_ref()
    {
        collect_result_diff_strings(result_json, &mut patch_texts);
    }
    dedupe_vec(&mut patch_texts);

    // Newer agent edits reference the before/after file content by id instead of
    // embedding a patch. Capture the content-store keys so the blobs can be
    // resolved and diffed once they are loaded into the session graph.
    let before_content_id = result_json
        .as_ref()
        .and_then(content_id_from_result("beforeContentId"));
    let after_content_id = result_json
        .as_ref()
        .and_then(content_id_from_result("afterContentId"));

    Some(CursorToolCall {
        bubble_id: bubble_id.to_string(),
        name,
        call_id,
        status,
        timestamp: default_timestamp,
        path_hints,
        patch_texts,
        before_content_id,
        after_content_id,
    })
}

/// Build a closure that extracts a non-empty content-store key (e.g.
/// `beforeContentId`) from a tool `result` object.
fn content_id_from_result(field: &'static str) -> impl Fn(&JsonValue) -> Option<String> {
    move |result_json: &JsonValue| {
        result_json
            .get(field)
            .and_then(|value| value.as_str())
            .filter(|value| !value.is_empty())
            .map(ToOwned::to_owned)
    }
}

fn collect_tool_paths(value: &JsonValue, project_path: Option<&str>, out: &mut Vec<String>) {
    match value {
        JsonValue::Object(map) => {
            for key in [
                "relativeWorkspacePath",
                "targetFile",
                "effectiveUri",
                "path",
            ] {
                if let Some(raw) = map.get(key).and_then(|value| value.as_str())
                    && let Some(path) = normalize_tool_path(raw, project_path)
                {
                    out.push(path);
                }
            }
            if let Some(paths) = map.get("paths").and_then(|value| value.as_array()) {
                for path in paths {
                    if let Some(raw) = path.as_str()
                        && let Some(path) = normalize_tool_path(raw, project_path)
                    {
                        out.push(path);
                    } else if let Some(raw) = path
                        .get("relativeWorkspacePath")
                        .and_then(|value| value.as_str())
                        && let Some(path) = normalize_tool_path(raw, project_path)
                    {
                        out.push(path);
                    }
                }
            }
        }
        JsonValue::Array(values) => {
            for value in values {
                collect_tool_paths(value, project_path, out);
            }
        }
        _ => {}
    }
}

fn collect_result_diff_strings(value: &JsonValue, out: &mut Vec<String>) {
    match value {
        JsonValue::Object(map) => {
            if let Some(chunks) = map
                .get("diff")
                .and_then(|value| value.get("chunks"))
                .and_then(|value| value.as_array())
            {
                for chunk in chunks {
                    if let Some(diff) = chunk.get("diffString").and_then(|value| value.as_str()) {
                        out.push(diff.to_string());
                    }
                }
            }
            for value in map.values() {
                collect_result_diff_strings(value, out);
            }
        }
        JsonValue::Array(values) => {
            for value in values {
                collect_result_diff_strings(value, out);
            }
        }
        _ => {}
    }
}

fn jsonish_to_value(value: &JsonValue) -> Option<JsonValue> {
    match value {
        JsonValue::Object(_) | JsonValue::Array(_) => Some(value.clone()),
        JsonValue::String(raw) => serde_json::from_str(raw).ok(),
        _ => None,
    }
}

fn normalize_tool_path(raw: &str, project_path: Option<&str>) -> Option<String> {
    let normalized = if raw.starts_with("file://") {
        strip_file_scheme(raw)
    } else {
        normalize_filesystem_path(raw)
    };

    let path = Path::new(&normalized);
    if path.is_absolute() {
        return Some(normalized);
    }

    let project_path = project_path?;
    Some(join_project_relative_path(project_path, path))
}

fn join_project_relative_path(project_path: &str, relative_path: &Path) -> String {
    let base_components: Vec<_> = Path::new(project_path).components().collect();
    let rel_components: Vec<_> = relative_path.components().collect();

    let mut overlap = 0usize;
    let max_overlap = base_components.len().min(rel_components.len());
    for len in 1..=max_overlap {
        let base_suffix = &base_components[base_components.len() - len..];
        let rel_prefix = &rel_components[..len];
        if base_suffix == rel_prefix {
            overlap = len;
        }
    }

    let mut joined = PathBuf::new();
    for component in &base_components[..base_components.len().saturating_sub(overlap)] {
        joined.push(component.as_os_str());
    }
    for component in &rel_components {
        joined.push(component.as_os_str());
    }

    normalize_filesystem_path(joined.to_string_lossy().as_ref())
}

fn extract_original_file_states(
    original_file_states: &HashMap<String, JsonValue>,
) -> HashMap<String, CursorOriginalFileState> {
    let mut out = HashMap::new();
    for (raw_path, state) in original_file_states {
        let path = strip_file_scheme(raw_path);
        if is_cursor_plan_path(&path) {
            continue;
        }

        out.insert(
            path,
            CursorOriginalFileState {
                content: state
                    .get("content")
                    .and_then(|value| value.as_str())
                    .map(ToOwned::to_owned),
                first_edit_bubble_id: state
                    .get("firstEditBubbleId")
                    .and_then(|value| value.as_str())
                    .map(ToOwned::to_owned),
            },
        );
    }
    out
}

fn extract_strong_path_hints(
    context: Option<&ComposerContext>,
    attached_uris: &[String],
    code_block_data: &HashMap<String, JsonValue>,
) -> HashSet<String> {
    let mut out = HashSet::new();

    if let Some(context) = context {
        for selection in &context.file_selections {
            if let Some(uri) = &selection.uri
                && let Some(fs_path) = &uri.fs_path
            {
                let path = normalize_filesystem_path(fs_path);
                if !is_cursor_plan_path(&path) {
                    out.insert(path);
                }
            }
        }
    }

    for uri in attached_uris {
        let path = strip_file_scheme(uri);
        if !is_cursor_plan_path(&path) {
            out.insert(path);
        }
    }

    for file_key in code_block_data.keys() {
        if let Some(path) = extract_file_path_from_string(file_key)
            && !is_cursor_plan_path(&path)
        {
            out.insert(path);
        }
    }

    out
}

fn extract_weak_path_hints(
    original_file_states: &HashMap<String, CursorOriginalFileState>,
) -> HashSet<String> {
    original_file_states.keys().cloned().collect()
}

fn extract_partial_targets(
    code_block_data: &HashMap<String, JsonValue>,
) -> Vec<CursorPartialTarget> {
    let mut out = HashSet::new();

    for (file_key, value) in code_block_data {
        for entry in code_block_entries(value) {
            let Some(entry_obj) = entry.as_object() else {
                continue;
            };
            if entry_obj.get("status").and_then(|value| value.as_str()) != Some("accepted") {
                continue;
            }
            let Some(partial_id) = entry_obj
                .get("partialInlineDiffFatesId")
                .and_then(|value| value.as_str())
                .map(ToOwned::to_owned)
            else {
                continue;
            };
            let abs_path = entry_obj
                .get("uri")
                .and_then(extract_file_path_from_uri_value)
                .or_else(|| extract_file_path_from_string(file_key));
            let Some(abs_path) = abs_path else {
                continue;
            };
            if is_cursor_plan_path(&abs_path) {
                continue;
            }

            out.insert(CursorPartialTarget {
                partial_id,
                abs_path,
            });
        }
    }

    out.into_iter().collect()
}

fn extract_legacy_targets(
    code_block_data: &HashMap<String, JsonValue>,
    default_timestamp: Option<String>,
) -> Vec<CursorLegacyTarget> {
    let mut targets = Vec::new();

    for (file_key, value) in code_block_data {
        for entry in code_block_entries(value) {
            let Some(entry_obj) = entry.as_object() else {
                continue;
            };
            if entry_obj.get("status").and_then(|value| value.as_str()) != Some("accepted") {
                continue;
            }
            if entry_obj
                .get("isNotApplied")
                .and_then(|value| value.as_bool())
                == Some(true)
            {
                continue;
            }
            if entry_obj.get("isNoOp").and_then(|value| value.as_bool()) == Some(true) {
                continue;
            }

            let abs_path = entry_obj
                .get("uri")
                .and_then(extract_file_path_from_uri_value)
                .or_else(|| extract_file_path_from_string(file_key));
            let Some(abs_path) = abs_path else {
                continue;
            };
            if is_cursor_plan_path(&abs_path) {
                continue;
            }

            let diff_id = entry_obj
                .get("diffId")
                .and_then(|value| value.as_str())
                .map(ToOwned::to_owned);
            let content = entry_obj
                .get("content")
                .and_then(|value| value.as_str())
                .map(ToOwned::to_owned);
            if diff_id.is_none() && content.is_none() {
                continue;
            }

            targets.push(CursorLegacyTarget {
                diff_id,
                abs_path,
                version: entry_obj
                    .get("version")
                    .and_then(|value| value.as_i64())
                    .unwrap_or(0) as i32,
                code_block_idx: entry_obj
                    .get("codeBlockIdx")
                    .and_then(|value| value.as_i64())
                    .unwrap_or(0) as i32,
                timestamp: default_timestamp.clone(),
                content,
                bubble_id: entry_obj
                    .get("bubbleId")
                    .and_then(|value| value.as_str())
                    .map(ToOwned::to_owned),
            });
        }
    }

    targets
}

fn code_block_entries(value: &JsonValue) -> Vec<&JsonValue> {
    if let Some(list) = value.as_array() {
        return list.iter().collect();
    }
    if let Some(map) = value.as_object() {
        return map.values().collect();
    }
    Vec::new()
}

fn extract_project_path(
    context: Option<&ComposerContext>,
    attached_uris: &[String],
    original_file_states: &HashMap<String, JsonValue>,
    code_block_data: &HashMap<String, JsonValue>,
) -> Option<String> {
    let mut paths = Vec::new();

    if let Some(context) = context {
        for selection in &context.file_selections {
            if let Some(uri) = &selection.uri
                && let Some(fs_path) = &uri.fs_path
            {
                paths.push(normalize_filesystem_path(fs_path));
            }
        }
    }

    if paths.is_empty() {
        for uri in attached_uris {
            paths.push(strip_file_scheme(uri));
        }
    }

    if paths.is_empty() {
        for path in original_file_states.keys() {
            paths.push(strip_file_scheme(path));
        }
    }

    if paths.is_empty() {
        for path in code_block_data.keys() {
            paths.push(strip_file_scheme(path));
        }
    }

    if paths.is_empty() {
        return None;
    }

    let raw_path = common_ancestor_path(&paths).unwrap_or_else(|| PathBuf::from(&paths[0]));
    let path = raw_path.as_path();
    if let Some(root) = detect_repo_root(path) {
        return Some(path_to_string(&root));
    }

    if path.extension().is_some() {
        path.parent()
            .map(|parent| normalize_filesystem_path(parent.to_string_lossy().as_ref()))
    } else {
        Some(normalize_filesystem_path(
            raw_path.to_string_lossy().as_ref(),
        ))
    }
}

fn common_ancestor_path(paths: &[String]) -> Option<PathBuf> {
    let mut common: Vec<_> = Path::new(paths.first()?).components().collect();

    for raw_path in paths.iter().skip(1) {
        let components: Vec<_> = Path::new(raw_path).components().collect();
        let shared_len = common
            .iter()
            .zip(components.iter())
            .take_while(|(left, right)| left == right)
            .count();
        common.truncate(shared_len);
        if common.is_empty() {
            break;
        }
    }

    if common.is_empty() {
        return None;
    }

    let mut out = PathBuf::new();
    for component in common {
        out.push(component.as_os_str());
    }
    Some(out)
}

fn extract_model_name(raw: &JsonValue) -> Option<String> {
    const MODEL_KEYS: &[&str] = &[
        "model",
        "modelName",
        "currentModel",
        "selectedModel",
        "defaultModel",
        "defaultModelSlug",
        "chatModel",
    ];

    fn visit(value: &JsonValue, include_default: bool) -> Option<String> {
        match value {
            JsonValue::Object(map) => {
                if let Some(candidate) = usage_data_model_key(map, include_default) {
                    return Some(candidate);
                }
                for key in MODEL_KEYS {
                    if let Some(candidate) = map
                        .get(*key)
                        .and_then(|value| model_string_from_value(value, include_default))
                    {
                        return Some(candidate);
                    }
                }
                for value in map.values() {
                    if let Some(candidate) = visit(value, include_default) {
                        return Some(candidate);
                    }
                }
                None
            }
            JsonValue::Array(values) => values
                .iter()
                .find_map(|value| visit(value, include_default)),
            _ => None,
        }
    }

    visit(raw, false).or_else(|| visit(raw, true))
}

fn usage_data_model_key(
    map: &serde_json::Map<String, JsonValue>,
    include_default: bool,
) -> Option<String> {
    map.get("usageData")
        .and_then(|value| value.as_object())
        .and_then(|usage_data| {
            usage_data
                .keys()
                .find_map(|key| model_string_from_candidate(key, include_default))
        })
}

fn model_string_from_value(value: &JsonValue, include_default: bool) -> Option<String> {
    match value {
        JsonValue::String(value) => model_string_from_candidate(value.trim(), include_default),
        JsonValue::Object(map) => {
            for key in ["name", "slug", "id", "model"] {
                if let Some(candidate) = map
                    .get(key)
                    .and_then(|value| model_string_from_value(value, include_default))
                {
                    return Some(candidate);
                }
            }
            None
        }
        _ => None,
    }
}

fn model_string_from_candidate(candidate: &str, include_default: bool) -> Option<String> {
    if candidate.is_empty() {
        return None;
    }

    let lowered = candidate.to_ascii_lowercase();
    if lowered == "default" {
        return include_default.then(|| "default".to_string());
    }

    if lowered.contains("gpt")
        || lowered.contains("claude")
        || lowered.contains("gemini")
        || lowered.contains("sonnet")
        || lowered.contains("haiku")
        || lowered.contains("opus")
        || lowered.contains("o1")
        || lowered.contains("o3")
        || lowered.contains("deepseek")
        || lowered.contains("llama")
        || lowered.contains("qwen")
    {
        return Some(candidate.to_string());
    }

    None
}

fn query_conversation_headers(
    vscdb: &Connection,
    composer_id: &str,
) -> Result<Option<HashMap<String, i64>>> {
    let raw: Option<String> = vscdb
        .query_row(
            "SELECT value FROM cursorDiskKV WHERE key = ?1",
            params![format!("composerData:{composer_id}")],
            |row| row.get(0),
        )
        .optional()?;
    let Some(raw) = raw else {
        return Ok(None);
    };
    let data: ComposerData = match serde_json::from_str(&raw) {
        Ok(value) => value,
        Err(_) => return Ok(None),
    };

    let mut out = HashMap::new();
    for (idx, header) in data.full_conversation_headers_only.iter().enumerate() {
        out.insert(header.bubble_id.clone(), idx as i64);
    }
    Ok(Some(out))
}

fn ended_at_from_ms(last_updated_at: Option<i64>, created_at: Option<i64>) -> Option<String> {
    last_updated_at
        .and_then(ms_to_iso)
        .or_else(|| created_at.and_then(ms_to_iso))
}

fn map_bubble_role(value: i64) -> Option<CursorBubbleRole> {
    match value {
        1 => Some(CursorBubbleRole::User),
        2 => Some(CursorBubbleRole::Assistant),
        _ => None,
    }
}

fn bubble_key_parts(key: &str) -> Option<(&str, &str)> {
    let mut parts = key.splitn(3, ':');
    if parts.next()? != "bubbleId" {
        return None;
    }
    Some((parts.next()?, parts.next()?))
}

fn partial_fates_key_parts(key: &str) -> Option<(&str, &str)> {
    let mut parts = key.splitn(3, ':');
    if parts.next()? != "codeBlockPartialInlineDiffFates" {
        return None;
    }
    Some((parts.next()?, parts.next()?))
}

fn code_block_diff_key_parts(key: &str) -> Option<(&str, &str)> {
    let mut parts = key.splitn(3, ':');
    if parts.next()? != "codeBlockDiff" {
        return None;
    }
    Some((parts.next()?, parts.next()?))
}

pub(crate) fn parse_string_array(value: Option<&JsonValue>) -> Vec<String> {
    let Some(value) = value else {
        return Vec::new();
    };
    let Some(arr) = value.as_array() else {
        return Vec::new();
    };
    arr.iter()
        .filter_map(|value| value.as_str().map(ToOwned::to_owned))
        .collect()
}

pub(crate) fn extract_patch_lines(text: &str) -> (Vec<String>, Vec<String>) {
    let mut added = Vec::new();
    let mut removed = Vec::new();
    for line in text.lines() {
        if line.starts_with("+++") || line.starts_with("---") || line.starts_with("@@") {
            continue;
        }
        if line.starts_with("*** ") {
            continue;
        }
        if line.starts_with("\\ No newline at end of file") {
            continue;
        }
        if let Some(rest) = line.strip_prefix('+') {
            added.push(rest.to_string());
        } else if let Some(rest) = line.strip_prefix('-') {
            removed.push(rest.to_string());
        }
    }
    (added, removed)
}

pub(crate) fn patch_has_real_changes(text: &str) -> bool {
    let (added, removed) = extract_patch_lines(text);
    !added.is_empty() || !removed.is_empty()
}

pub(crate) fn hash_counts_for_lines(lines: &[String], side: LineSide) -> Vec<LineHashCount> {
    let mut counts: HashMap<String, i64> = HashMap::new();
    for line in lines {
        *counts.entry(hash_line(line)).or_insert(0) += 1;
    }
    counts
        .into_iter()
        .map(|(line_hash, count)| LineHashCount {
            side,
            line_hash,
            count,
        })
        .collect()
}

pub(crate) fn extract_file_path_from_uri_value(uri: &JsonValue) -> Option<String> {
    match uri {
        JsonValue::Object(map) => {
            if let Some(scheme) = map.get("scheme").and_then(|value| value.as_str())
                && scheme != "file"
            {
                return None;
            }

            if let Some(fs_path) = map.get("fsPath").and_then(|value| value.as_str()) {
                return Some(normalize_filesystem_path(fs_path));
            }
            if let Some(external) = map.get("external").and_then(|value| value.as_str()) {
                return extract_file_path_from_string(external);
            }
            if let Some(path) = map.get("path").and_then(|value| value.as_str()) {
                return Some(normalize_filesystem_path(path));
            }
            None
        }
        JsonValue::String(raw) => extract_file_path_from_string(raw),
        _ => None,
    }
}

pub(crate) fn extract_file_path_from_string(raw: &str) -> Option<String> {
    if raw.starts_with("file://") {
        return Some(strip_file_scheme(raw));
    }
    if raw.starts_with("vscode-notebook-cell:") {
        return None;
    }
    if raw.contains("://") {
        return None;
    }
    Some(normalize_filesystem_path(raw))
}

pub(crate) fn is_cursor_plan_path(path: &str) -> bool {
    let normalized = normalize_filesystem_path(path);
    normalized.contains("/.cursor/plans/") || normalized.contains("/.cursor/plans\\")
}

pub(crate) fn ms_to_iso(ms: i64) -> Option<String> {
    chrono::Utc
        .timestamp_millis_opt(ms)
        .single()
        .map(|dt| dt.to_rfc3339())
}

/// Normalize a bubble's raw `createdAt` value into an ISO-8601 string. Cursor
/// production data stores it as an ISO string; some builds/fixtures store epoch
/// millis. Anything else (missing/empty/unexpected shape) yields `None`.
fn normalize_bubble_timestamp(value: Option<&JsonValue>) -> Option<String> {
    match value {
        Some(JsonValue::String(s)) => {
            let trimmed = s.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        }
        Some(JsonValue::Number(n)) => n.as_i64().and_then(ms_to_iso),
        _ => None,
    }
}

fn dedupe_vec(values: &mut Vec<String>) {
    let mut seen = HashSet::new();
    values.retain(|value| seen.insert(value.clone()));
}

/// Collapse `\r\n` and lone `\r` line endings to `\n` so line-based diffing is
/// not confused by cosmetic EOL differences between content snapshots.
fn normalize_line_endings(text: &str) -> String {
    text.replace("\r\n", "\n").replace('\r', "\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use rusqlite::{Connection, params};
    use serde_json::json;
    use tempfile::NamedTempFile;

    #[test]
    fn resolves_relative_tool_paths_against_project_root() {
        assert_eq!(
            normalize_tool_path("tests/pages/user-support-po.ts", Some("/tmp/repo")).as_deref(),
            Some("/tmp/repo/tests/pages/user-support-po.ts")
        );
    }

    #[test]
    fn avoids_double_joining_overlapping_relative_tool_paths() {
        assert_eq!(
            normalize_tool_path(
                "tests/pages/user-support-po.ts",
                Some("/tmp/repo/tests/pages"),
            )
            .as_deref(),
            Some("/tmp/repo/tests/pages/user-support-po.ts")
        );
    }

    #[test]
    fn parses_edit_file_patch_lines() {
        let (added, removed) = extract_patch_lines(
            "@@\n import { A } from './a';\n-import { B } from './b';\n+import { C } from './c';\n",
        );
        assert_eq!(added, vec!["import { C } from './c';"]);
        assert_eq!(removed, vec!["import { B } from './b';"]);
    }

    #[test]
    fn resolve_tool_call_edits_uses_first_edit_bubble_as_path_bridge() {
        let graph = CursorSessionGraph {
            composer_id: "c1".to_string(),
            source_file: "/tmp/state.vscdb".to_string(),
            created_at_ms: None,
            last_updated_at_ms: None,
            started_at: None,
            ended_at: Some("2026-04-18T11:07:54Z".to_string()),
            project_path: Some("/tmp/repo".to_string()),
            model_name: None,
            subtitle: None,
            files_changed_count: Some(1),
            total_lines_added: Some(1),
            total_lines_removed: Some(1),
            conversation_messages: Vec::new(),
            bubble_events: Vec::new(),
            tool_calls: vec![CursorToolCall {
                bubble_id: "bubble-1".to_string(),
                name: "edit_file_v2".to_string(),
                call_id: "call-1".to_string(),
                status: Some("completed".to_string()),
                timestamp: None,
                path_hints: Vec::new(),
                patch_texts: vec!["@@\n-old\n+new\n".to_string()],
                before_content_id: None,
                after_content_id: None,
            }],
            checkpoint_paths: HashSet::new(),
            strong_path_hints: HashSet::new(),
            weak_path_hints: HashSet::new(),
            original_file_states: HashMap::from([(
                "/tmp/repo/src/app.ts".to_string(),
                CursorOriginalFileState {
                    content: Some("old\n".to_string()),
                    first_edit_bubble_id: Some("bubble-1".to_string()),
                },
            )]),
            partial_targets: Vec::new(),
            legacy_targets: Vec::new(),
            inline_hints: Vec::new(),
            inline_undo_rows: Vec::new(),
            partial_fates: HashMap::new(),
            legacy_diff_payloads: HashMap::new(),
            content_blobs: HashMap::new(),
        };

        let edits = resolve_tool_call_edits(&graph);
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].abs_path, "/tmp/repo/src/app.ts");
        assert_eq!(edits[0].added_lines, 1);
        assert_eq!(edits[0].removed_lines, 1);
    }

    #[test]
    fn resolve_tool_call_edits_diffs_referenced_content_blobs() {
        let before_id = "composer.content.before".to_string();
        let after_id = "composer.content.after".to_string();
        let graph = CursorSessionGraph {
            composer_id: "c1".to_string(),
            source_file: "/tmp/state.vscdb".to_string(),
            created_at_ms: None,
            last_updated_at_ms: None,
            started_at: None,
            ended_at: Some("2026-04-18T11:07:54Z".to_string()),
            project_path: Some("/tmp/repo".to_string()),
            model_name: None,
            subtitle: None,
            files_changed_count: Some(1),
            total_lines_added: Some(1),
            total_lines_removed: Some(1),
            conversation_messages: Vec::new(),
            bubble_events: Vec::new(),
            tool_calls: vec![CursorToolCall {
                bubble_id: "bubble-1".to_string(),
                name: "edit_file_v2".to_string(),
                call_id: "call-1".to_string(),
                status: Some("completed".to_string()),
                timestamp: None,
                // No inline patch: this edit is referenced purely by content id,
                // mirroring the newer Cursor agent-edit schema (CRLF before, LF
                // after, to exercise line-ending normalization).
                path_hints: vec!["/tmp/repo/lib/home.dart".to_string()],
                patch_texts: Vec::new(),
                before_content_id: Some(before_id.clone()),
                after_content_id: Some(after_id.clone()),
            }],
            checkpoint_paths: HashSet::new(),
            strong_path_hints: HashSet::new(),
            weak_path_hints: HashSet::new(),
            original_file_states: HashMap::new(),
            partial_targets: Vec::new(),
            legacy_targets: Vec::new(),
            inline_hints: Vec::new(),
            inline_undo_rows: Vec::new(),
            partial_fates: HashMap::new(),
            legacy_diff_payloads: HashMap::new(),
            content_blobs: HashMap::from([
                (before_id, "import 'a';\r\nclass Home {}\r\n".to_string()),
                (
                    after_id,
                    "import 'a';\nimport 'b';\nclass Home {}\n".to_string(),
                ),
            ]),
        };

        let edits = resolve_tool_call_edits(&graph);
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].abs_path, "/tmp/repo/lib/home.dart");
        // The only real change between before/after is the added `import 'b';`.
        assert_eq!(edits[0].added_lines, 1);
        assert_eq!(edits[0].removed_lines, 0);
        assert_eq!(edits[0].parser_name, "cursor_tool_edit_file_v2_content_v1");
        assert!(edits[0].before_known);
    }

    #[test]
    fn resolve_tool_call_edits_treats_missing_before_content_as_new_file() {
        let after_id = "composer.content.after".to_string();
        let graph = CursorSessionGraph {
            composer_id: "c1".to_string(),
            source_file: "/tmp/state.vscdb".to_string(),
            created_at_ms: None,
            last_updated_at_ms: None,
            started_at: None,
            ended_at: Some("2026-04-18T11:07:54Z".to_string()),
            project_path: Some("/tmp/repo".to_string()),
            model_name: None,
            subtitle: None,
            files_changed_count: Some(1),
            total_lines_added: Some(2),
            total_lines_removed: Some(0),
            conversation_messages: Vec::new(),
            bubble_events: Vec::new(),
            tool_calls: vec![CursorToolCall {
                bubble_id: "bubble-1".to_string(),
                name: "edit_file_v2".to_string(),
                call_id: "call-1".to_string(),
                status: Some("completed".to_string()),
                timestamp: None,
                path_hints: vec!["/tmp/repo/lib/new.dart".to_string()],
                patch_texts: Vec::new(),
                before_content_id: None,
                after_content_id: Some(after_id.clone()),
            }],
            checkpoint_paths: HashSet::new(),
            strong_path_hints: HashSet::new(),
            weak_path_hints: HashSet::new(),
            original_file_states: HashMap::new(),
            partial_targets: Vec::new(),
            legacy_targets: Vec::new(),
            inline_hints: Vec::new(),
            inline_undo_rows: Vec::new(),
            partial_fates: HashMap::new(),
            legacy_diff_payloads: HashMap::new(),
            content_blobs: HashMap::from([(after_id, "line one\nline two\n".to_string())]),
        };

        let edits = resolve_tool_call_edits(&graph);
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].added_lines, 2);
        assert_eq!(edits[0].removed_lines, 0);
        assert!(!edits[0].before_known);
    }

    #[test]
    fn normalize_bubble_timestamp_handles_string_and_millis() {
        assert_eq!(
            normalize_bubble_timestamp(Some(&json!("2026-06-01T07:19:41.178Z"))).as_deref(),
            Some("2026-06-01T07:19:41.178Z")
        );
        // Epoch millis (1780298369463 == 2026-06-01T07:19:29.463Z) get converted.
        assert_eq!(
            normalize_bubble_timestamp(Some(&json!(1780298369463i64))).as_deref(),
            Some("2026-06-01T07:19:29.463+00:00")
        );
        assert_eq!(normalize_bubble_timestamp(Some(&json!("  "))), None);
        assert_eq!(normalize_bubble_timestamp(Some(&json!(null))), None);
        assert_eq!(normalize_bubble_timestamp(None), None);
    }

    #[test]
    fn populate_bubbles_captures_per_message_timestamps() {
        let file = NamedTempFile::new().expect("temp db should be created");
        let conn = Connection::open(file.path()).expect("temp db should open");
        conn.execute_batch(
            "CREATE TABLE cursorDiskKV (
                key   TEXT PRIMARY KEY,
                value TEXT
            );",
        )
        .expect("schema should be created");

        // Composer-level created/updated span a full day; without per-bubble
        // timestamps every message would collapse onto `createdAt`.
        conn.execute(
            "INSERT INTO cursorDiskKV (key, value) VALUES (?1, ?2)",
            params![
                "composerData:s1",
                json!({
                    "composerId": "s1",
                    "createdAt": 1_780_298_369_463i64,
                    "lastUpdatedAt": 1_780_382_474_682i64,
                })
                .to_string()
            ],
        )
        .expect("composer row should insert");
        conn.execute(
            "INSERT INTO cursorDiskKV (key, value) VALUES (?1, ?2)",
            params![
                "bubbleId:s1:b1",
                json!({
                    "type": 1,
                    "text": "first user turn",
                    "createdAt": "2026-06-01T07:19:41.178Z",
                })
                .to_string()
            ],
        )
        .expect("user bubble should insert");
        conn.execute(
            "INSERT INTO cursorDiskKV (key, value) VALUES (?1, ?2)",
            params![
                "bubbleId:s1:b2",
                json!({
                    "type": 2,
                    "text": "assistant reply",
                    "createdAt": "2026-06-02T06:40:58.614Z",
                })
                .to_string()
            ],
        )
        .expect("assistant bubble should insert");

        let graphs =
            load_cursor_session_graphs(&conn, "/tmp/state.vscdb").expect("graph load should work");
        assert_eq!(graphs.len(), 1);
        let messages = graphs[0].messages();
        let timestamps: Vec<Option<&str>> =
            messages.iter().map(|m| m.timestamp.as_deref()).collect();
        assert!(
            timestamps.contains(&Some("2026-06-01T07:19:41.178Z")),
            "expected first bubble's own createdAt, got {timestamps:?}"
        );
        assert!(
            timestamps.contains(&Some("2026-06-02T06:40:58.614Z")),
            "expected second bubble's own createdAt, got {timestamps:?}"
        );
    }

    #[test]
    fn load_cursor_session_graphs_skips_null_composer_rows() {
        let file = NamedTempFile::new().expect("temp db should be created");
        let conn = Connection::open(file.path()).expect("temp db should open");
        conn.execute_batch(
            "CREATE TABLE cursorDiskKV (
                key   TEXT PRIMARY KEY,
                value TEXT
            );",
        )
        .expect("schema should be created");

        conn.execute(
            "INSERT INTO cursorDiskKV (key, value) VALUES (?1, NULL)",
            params!["composerData:null-session"],
        )
        .expect("null composer row should insert");
        conn.execute(
            "INSERT INTO cursorDiskKV (key, value) VALUES (?1, ?2)",
            params![
                "composerData:real-session",
                json!({
                    "composerId": "real-session",
                    "conversation": [{"type": 1, "text": "hello"}],
                    "createdAt": 1,
                    "lastUpdatedAt": 2,
                })
                .to_string()
            ],
        )
        .expect("real composer row should insert");

        let graphs =
            load_cursor_session_graphs(&conn, "/tmp/state.vscdb").expect("graph load should work");
        assert_eq!(graphs.len(), 1);
        assert_eq!(graphs[0].composer_id, "real-session");
    }
}