khive-pack-session 0.11.0

Session verb pack - store/list/resume/export over the notes substrate
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
//! Parsers for CLI transcripts and provider conversation exports.
//!
//! Every function here is deterministic and side-effect-free so the unit tests
//! can run without any runtime or DB setup.

use std::collections::{HashMap, HashSet};

use chrono::DateTime;
use khive_runtime::secret_gate;
use serde_json::{Map, Value};

fn mask_session_mirror(text: &str) -> std::borrow::Cow<'_, str> {
    secret_gate::mask_for_redaction_surface(secret_gate::RedactionSurface::SessionMirror, text)
}

/// Bound the masker's own input window (see `secret_gate::mask_bounded`)
/// before capping display text to `output_cap_chars`, rather than masking
/// the full, unbounded text: cost stays proportional to the shared window
/// regardless of input length, and a token straddling the window is dropped
/// whole rather than echoed unmasked.
fn mask_session_mirror_bounded(text: &str, output_cap_chars: usize) -> String {
    secret_gate::mask_bounded(
        secret_gate::RedactionSurface::SessionMirror,
        text,
        secret_gate::MASK_WINDOW_CHARS,
        output_cap_chars,
    )
    .text
}

/// A single parsed event, source-agnostic.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedEvent {
    /// Event UUID — the primary key for idempotency.
    ///
    /// For Claude Code events this is the top-level `uuid` field.
    /// For Codex events (which carry no per-message uuid) this is synthesised
    /// as `"{session_id}:{abs_byte_offset}"`.
    /// For ChatGPT export events this is the mapping node's `message.id`.
    /// For Claude.ai export events this is `chat_messages[].uuid`.
    pub uuid: String,
    /// Session UUID.
    pub session_id: String,
    /// Parent event UUID if present.
    pub parent_uuid: Option<String>,
    /// Whether this event is on a sidechain.
    pub is_sidechain: bool,
    /// Normalized provider role when present.
    pub role: Option<String>,
    /// Source event or content type.
    pub msg_type: String,
    /// Extracted display text, secrets masked; `None` for non-message events.
    pub text: Option<String>,
    /// Original line or serialized export message/node with secrets masked.
    pub raw: String,
    /// Source timestamp as microseconds since the Unix epoch; 0 if absent or unparseable.
    pub created_at_micros: i64,
    /// `cwd` if present, secrets masked.
    pub cwd: Option<String>,
    /// `gitBranch` (CC) or `payload.git.branch` (Codex) if present, secrets masked.
    pub git_branch: Option<String>,
    /// `slug` if present (CC: project slug; ChatGPT/Claude.ai export:
    /// conversation title; Codex files carry no slug concept).
    pub slug: Option<String>,
}

/// Session metadata parsed independently of retained message events.
///
/// Whole-file exports can contain valid conversations with no displayable
/// messages. Keeping this record separate from [`ParsedEvent`] lets the
/// ingester create the required `sessions` row without inventing a synthetic
/// `session_messages` row.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ParsedSession {
    /// Provider conversation/session identifier.
    pub(crate) session_id: String,
    /// Source timestamp as microseconds since the Unix epoch; 0 if absent or unparseable.
    pub(crate) created_at_micros: i64,
    /// `cwd` if present.
    pub(crate) cwd: Option<String>,
    /// Source git branch if present.
    pub(crate) git_branch: Option<String>,
    /// Provider conversation title or project slug if present.
    pub(crate) slug: Option<String>,
}

/// Parsed whole-file export payload used by the ingest layer.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ParsedExport {
    pub(crate) sessions: Vec<ParsedSession>,
    pub(crate) events: Vec<ParsedEvent>,
}

/// Parse one Claude Code JSONL line.
///
/// Returns `None` for:
/// - blank or whitespace-only lines
/// - lines that are not valid JSON objects
/// - lines that lack a top-level `uuid` field
/// - lines that lack a top-level `sessionId` field
///
/// The returned `raw` and `text` fields have secrets masked.
pub fn parse_cc_line(line: &str) -> Option<ParsedEvent> {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return None;
    }

    let obj: Value = serde_json::from_str(trimmed).ok()?;
    let map = obj.as_object()?;

    // Both uuid and sessionId are required for idempotency and routing.
    let uuid = map.get("uuid")?.as_str()?.to_string();
    if uuid.is_empty() {
        return None;
    }
    let session_id = map.get("sessionId")?.as_str()?.to_string();
    if session_id.is_empty() {
        return None;
    }

    let parent_uuid = map
        .get("parentUuid")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(str::to_string);

    let is_sidechain = map
        .get("isSidechain")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    let msg_type = map
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    let cwd = map
        .get("cwd")
        .and_then(|v| v.as_str())
        .map(|s| mask_session_mirror(s).into_owned());

    let git_branch = map
        .get("gitBranch")
        .and_then(|v| v.as_str())
        .map(|s| mask_session_mirror(s).into_owned());

    let slug = map
        .get("slug")
        .and_then(|v| v.as_str())
        .map(|s| mask_session_mirror(s).into_owned());

    let created_at_micros = map
        .get("timestamp")
        .and_then(|v| v.as_str())
        .and_then(|ts| DateTime::parse_from_rfc3339(ts).ok())
        .map(|dt| dt.timestamp_micros())
        .unwrap_or(0);

    // Extract role and text from message when present.
    let (role, text) = match map.get("message").and_then(|m| m.as_object()) {
        None => (None, None),
        Some(msg) => {
            let role = msg.get("role").and_then(|v| v.as_str()).map(str::to_string);
            let text = extract_text(msg.get("content"));
            (role, text)
        }
    };

    // Apply masking to the raw line and the extracted text, reusing the
    // canonical write-time secret detector (khive-runtime) — never a second,
    // weaker masker.
    let raw = mask_session_mirror(trimmed).into_owned();
    let text = text.map(|t| mask_session_mirror(&t).into_owned());

    Some(ParsedEvent {
        uuid,
        session_id,
        parent_uuid,
        is_sidechain,
        role,
        msg_type,
        text,
        raw,
        created_at_micros,
        cwd,
        git_branch,
        slug,
    })
}

/// Parse one Codex CLI JSONL line.
///
/// `session_id` must be derived from the filename before calling this function
/// (e.g. from `rollout-<timestamp>-<uuid>.jsonl`).  `abs_byte_offset` is the
/// file byte offset of the **start** of this line; it is embedded in the
/// synthesised event UUID so that `INSERT OR IGNORE` on `session_messages.id`
/// is idempotent across re-tails of an append-only file.
///
/// Returns `None` for:
/// - blank or whitespace-only lines
/// - lines that are not valid JSON objects
/// - lines whose top-level `type` is `"event_msg"` — these are duplicate
///   event-stream representations of messages and must not be double-stored
/// - any other line type that carries no useful message content
///
/// The returned `raw` and `text` fields have secrets masked.
pub fn parse_codex_line(line: &str, session_id: &str, abs_byte_offset: u64) -> Option<ParsedEvent> {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return None;
    }

    let obj: Value = serde_json::from_str(trimmed).ok()?;
    let map = obj.as_object()?;

    let line_type = map.get("type")?.as_str()?;

    // event_msg lines are duplicate event-stream representations — skip them.
    if line_type == "event_msg" {
        return None;
    }

    let created_at_micros = map
        .get("timestamp")
        .and_then(|v| v.as_str())
        .and_then(|ts| DateTime::parse_from_rfc3339(ts).ok())
        .map(|dt| dt.timestamp_micros())
        .unwrap_or(0);

    match line_type {
        "session_meta" => {
            // session_meta carries cwd and git metadata; the session UUID in
            // payload.id should match the filename-derived session_id, but we
            // do NOT use it as the event id — use the synthesised offset key so
            // the message row is unique and idempotent.
            let payload = map.get("payload").and_then(|v| v.as_object());

            let cwd = payload
                .and_then(|p| p.get("cwd"))
                .and_then(|v| v.as_str())
                .map(|s| mask_session_mirror(s).into_owned());

            let git_branch = payload
                .and_then(|p| p.get("git"))
                .and_then(|g| g.as_object())
                .and_then(|g| g.get("branch"))
                .and_then(|v| v.as_str())
                .map(|s| mask_session_mirror(s).into_owned());

            let uuid = format!("{session_id}:{abs_byte_offset}");
            let raw = mask_session_mirror(trimmed).into_owned();

            Some(ParsedEvent {
                uuid,
                session_id: session_id.to_string(),
                parent_uuid: None,
                is_sidechain: false,
                role: None,
                msg_type: "session_meta".to_string(),
                text: None,
                raw,
                created_at_micros,
                cwd,
                git_branch,
                slug: None,
            })
        }
        "response_item" => {
            let payload = map.get("payload").and_then(|v| v.as_object())?;

            // Only ingest message items; skip tool_call, completion, etc.
            if payload.get("type").and_then(|v| v.as_str()) != Some("message") {
                return None;
            }

            let role = payload
                .get("role")
                .and_then(|v| v.as_str())
                .map(str::to_string);

            let text = extract_text(payload.get("content"));
            let text = text.map(|t| mask_session_mirror_bounded(&t, 500));

            let uuid = format!("{session_id}:{abs_byte_offset}");
            let raw = mask_session_mirror(trimmed).into_owned();

            Some(ParsedEvent {
                uuid,
                session_id: session_id.to_string(),
                parent_uuid: None,
                is_sidechain: false,
                role,
                msg_type: "response_item".to_string(),
                text,
                raw,
                created_at_micros,
                cwd: None,
                git_branch: None,
                slug: None,
            })
        }
        // Unknown line types are silently skipped.
        _ => None,
    }
}

/// Parse a ChatGPT data-export `conversations.json` file: parses the whole
/// file at once (unlike the line-at-a-time `parse_cc_line`/`parse_codex_line`)
/// and returns every message-bearing event across every conversation, in
/// deterministic DFS preorder per conversation.
///
/// Returns `None` when `content` is not valid JSON or the top level is not a
/// JSON array — the caller treats that as a per-file error so the mirror
/// cursor does not advance. A malformed *conversation* inside an otherwise-
/// valid array is skipped individually, not the whole file. The returned
/// `raw` and `text` fields have secrets masked, exactly like
/// `parse_cc_line`/`parse_codex_line`. See
/// `crates/khive-pack-session/docs/api/mirror-parse.md` for the DFS/sidechain
/// algorithm detail.
pub fn parse_chatgpt_export(content: &str) -> Option<Vec<ParsedEvent>> {
    let value: Value = serde_json::from_str(content).ok()?;
    let conversations = value.as_array()?;

    // Both providers use the filename `conversations.json`. If operators point
    // both roots at the same directory, rejecting an unmistakable Claude.ai
    // file here prevents the ChatGPT ingester from consuming its cursor first.
    if conversations.iter().any(is_claude_ai_conversation) {
        return None;
    }

    let mut events = Vec::new();
    for conv in conversations {
        parse_conversation(conv, &mut events);
    }
    Some(events)
}

/// Parse a claude.ai data-export `conversations.json` file.
///
/// Claude.ai exports are a top-level JSON array whose conversation objects
/// carry `uuid`, `name`, and `chat_messages`. Message UUIDs and conversation
/// UUIDs are preserved as the idempotency and provider-session anchors. When
/// `current_leaf_message_uuid` is present, messages outside its parent chain
/// are retained with `is_sidechain = true`; older flat exports without that
/// field keep every message on the main path.
///
/// Returns `None` when `content` is not valid JSON or the top level is not an
/// array. Malformed conversation objects inside a valid array are skipped.
pub fn parse_claude_ai_export(content: &str) -> Option<Vec<ParsedEvent>> {
    parse_claude_ai_export_with_sessions(content).map(|parsed| parsed.events)
}

/// Parse a claude.ai export while retaining conversation metadata even when a
/// conversation has no displayable messages.
pub(crate) fn parse_claude_ai_export_with_sessions(content: &str) -> Option<ParsedExport> {
    let value: Value = serde_json::from_str(content).ok()?;
    let conversations = value.as_array()?;

    // Symmetric source-shape check for accidentally overlapping export roots.
    // Empty and wholly malformed arrays remain valid so per-conversation
    // isolation keeps its existing semantics.
    if conversations.iter().any(is_chatgpt_conversation) {
        return None;
    }

    let mut sessions = Vec::new();
    let mut events = Vec::new();
    for conversation in conversations {
        if let Some(session) = parse_claude_ai_conversation(conversation, &mut events) {
            sessions.push(session);
        }
    }
    Some(ParsedExport { sessions, events })
}

fn is_chatgpt_conversation(conversation: &Value) -> bool {
    conversation.as_object().is_some_and(|conversation| {
        conversation
            .get("id")
            .and_then(Value::as_str)
            .is_some_and(|id| !id.is_empty())
            && conversation.get("mapping").is_some_and(Value::is_object)
    })
}

fn is_claude_ai_conversation(conversation: &Value) -> bool {
    conversation.as_object().is_some_and(|conversation| {
        conversation
            .get("uuid")
            .and_then(Value::as_str)
            .is_some_and(|id| !id.is_empty())
            && conversation
                .get("chat_messages")
                .is_some_and(Value::is_array)
    })
}

fn parse_claude_ai_conversation(
    conversation: &Value,
    out: &mut Vec<ParsedEvent>,
) -> Option<ParsedSession> {
    let conversation = conversation.as_object()?;
    let session_id = conversation
        .get("uuid")
        .and_then(Value::as_str)
        .filter(|id| !id.is_empty())?;
    let messages = conversation
        .get("chat_messages")
        .and_then(Value::as_array)?;

    let slug = conversation
        .get("name")
        .and_then(Value::as_str)
        .filter(|name| !name.is_empty())
        .or_else(|| {
            conversation
                .get("summary")
                .and_then(Value::as_str)
                .filter(|summary| !summary.is_empty())
        })
        .map(|title| mask_session_mirror(title).into_owned());
    let conversation_created_at_micros = conversation
        .get("created_at")
        .and_then(parse_rfc3339_micros)
        .or_else(|| {
            conversation
                .get("updated_at")
                .and_then(parse_rfc3339_micros)
        })
        .unwrap_or(0);

    let mut parent_by_id: HashMap<String, Option<String>> = HashMap::new();
    for message in messages {
        let Some(message) = message.as_object() else {
            continue;
        };
        let Some(uuid) = message
            .get("uuid")
            .and_then(Value::as_str)
            .filter(|id| !id.is_empty())
        else {
            continue;
        };
        parent_by_id
            .entry(uuid.to_string())
            .or_insert_with(|| claude_ai_parent_uuid(message));
    }

    let current_path = claude_ai_current_path(conversation, &parent_by_id);
    let mut order: Vec<usize> = (0..messages.len()).collect();
    order.sort_by_key(|&position| {
        let source_index = messages[position]
            .as_object()
            .and_then(|message| message.get("index"))
            .and_then(Value::as_i64)
            .unwrap_or(position as i64);
        (source_index, position)
    });

    let mut emitted = HashSet::new();
    let start = out.len();
    for position in order {
        let Some(message) = messages[position].as_object() else {
            continue;
        };
        let Some(uuid) = message
            .get("uuid")
            .and_then(Value::as_str)
            .filter(|id| !id.is_empty())
        else {
            continue;
        };
        if !emitted.insert(uuid.to_string()) {
            continue;
        }
        if let Some(event) = build_claude_ai_event(
            message,
            session_id,
            slug.as_deref(),
            conversation_created_at_micros,
            &current_path,
        ) {
            out.push(event);
        }
    }

    let stored_ids: HashSet<String> = out[start..]
        .iter()
        .map(|event| event.uuid.clone())
        .collect();
    for event in &mut out[start..] {
        if event
            .parent_uuid
            .as_ref()
            .is_some_and(|parent| !stored_ids.contains(parent))
        {
            event.parent_uuid = None;
        }
    }

    Some(ParsedSession {
        session_id: session_id.to_string(),
        created_at_micros: conversation_created_at_micros,
        cwd: None,
        git_branch: None,
        slug,
    })
}

fn claude_ai_current_path(
    conversation: &Map<String, Value>,
    parent_by_id: &HashMap<String, Option<String>>,
) -> HashSet<String> {
    let Some(current_leaf) = conversation
        .get("current_leaf_message_uuid")
        .and_then(Value::as_str)
        .filter(|id| parent_by_id.contains_key(*id))
    else {
        return parent_by_id.keys().cloned().collect();
    };

    let mut path = HashSet::new();
    let mut cursor = Some(current_leaf.to_string());
    while let Some(message_id) = cursor {
        if !path.insert(message_id.clone()) {
            break;
        }
        cursor = parent_by_id.get(&message_id).cloned().flatten();
    }
    path
}

fn build_claude_ai_event(
    message: &Map<String, Value>,
    session_id: &str,
    slug: Option<&str>,
    conversation_created_at_micros: i64,
    current_path: &HashSet<String>,
) -> Option<ParsedEvent> {
    let uuid = message
        .get("uuid")
        .and_then(Value::as_str)
        .filter(|id| !id.is_empty())?
        .to_string();

    let role = message
        .get("sender")
        .or_else(|| message.get("role"))
        .and_then(Value::as_str)
        .filter(|sender| !sender.is_empty())
        .map(|sender| match sender {
            "human" | "user" => "user".to_string(),
            other => other.to_string(),
        });
    let text = extract_claude_ai_text(message)?;
    if text.trim().is_empty() {
        return None;
    }

    let created_at_micros = message
        .get("created_at")
        .and_then(parse_rfc3339_micros)
        .or_else(|| message.get("updated_at").and_then(parse_rfc3339_micros))
        .unwrap_or(conversation_created_at_micros);
    let parent_uuid = claude_ai_parent_uuid(message);
    let raw_json = serde_json::to_string(message).unwrap_or_default();

    Some(ParsedEvent {
        uuid: uuid.clone(),
        session_id: session_id.to_string(),
        parent_uuid,
        is_sidechain: !current_path.contains(&uuid),
        role,
        msg_type: "message".to_string(),
        text: Some(mask_session_mirror(&text).into_owned()),
        raw: mask_session_mirror(&raw_json).into_owned(),
        created_at_micros,
        cwd: None,
        git_branch: None,
        slug: slug.map(str::to_string),
    })
}

fn claude_ai_parent_uuid(message: &Map<String, Value>) -> Option<String> {
    message
        .get("parent_message_uuid")
        .and_then(Value::as_str)
        .filter(|parent| !parent.is_empty() && *parent != "00000000-0000-4000-8000-000000000000")
        .map(str::to_string)
}

fn extract_claude_ai_text(message: &Map<String, Value>) -> Option<String> {
    let top_level_text = message
        .get("text")
        .and_then(Value::as_str)
        .filter(|text| !text.trim().is_empty());
    let mut parts = Vec::new();

    match message.get("content") {
        Some(Value::Array(blocks)) => {
            for part in blocks
                .iter()
                .filter_map(extract_block)
                .filter(|part| !part.trim().is_empty())
            {
                parts.push(part);
            }
        }
        Some(Value::String(text)) if !text.trim().is_empty() => parts.push(text.clone()),
        Some(_) | None => {}
    }

    if let Some(text) = top_level_text {
        if !parts.iter().any(|part| part == text) {
            parts.push(text.to_string());
        }
    }

    (!parts.is_empty()).then(|| parts.join("\n"))
}

fn parse_rfc3339_micros(value: &Value) -> Option<i64> {
    value
        .as_str()
        .and_then(|timestamp| DateTime::parse_from_rfc3339(timestamp).ok())
        .map(|timestamp| timestamp.timestamp_micros())
}

/// Extract a display-friendly text string from a message `content` value
/// (string form or structured-block array form).
fn extract_text(content: Option<&Value>) -> Option<String> {
    match content? {
        Value::String(s) => Some(s.clone()),
        Value::Array(blocks) => {
            let parts: Vec<String> = blocks.iter().filter_map(extract_block).collect();
            if parts.is_empty() {
                None
            } else {
                Some(parts.join("\n"))
            }
        }
        _ => None,
    }
}

/// Extract a display string from a single content block (`"text"` /
/// `"input_text"` / `"output_text"` / `"voice_note"` / `"tool_use"` /
/// `"tool_result"`). See
/// `crates/khive-pack-session/docs/api/mirror-parse.md#extract_text--extract_block-claude-code-codex-and-claudeai-blocks`.
fn extract_block(block: &Value) -> Option<String> {
    let map = block.as_object()?;
    match map.get("type")?.as_str()? {
        // Claude Code text block and Codex user/assistant text blocks all carry
        // their display text in a "text" field — same extraction logic.
        "text" | "input_text" | "output_text" | "voice_note" => {
            map.get("text").and_then(|v| v.as_str()).map(str::to_string)
        }
        "tool_use" => {
            let name = map
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            let input = map.get("input").cloned().unwrap_or(Value::Null);
            let input_json = serde_json::to_string(&input).unwrap_or_default();
            let input_str = mask_session_mirror_bounded(&input_json, 500);
            Some(format!("[tool_use: {name}] {input_str}"))
        }
        "tool_result" => {
            let content_val = map.get("content").cloned().unwrap_or(Value::Null);
            let content_str = match &content_val {
                Value::String(s) => s.clone(),
                other => serde_json::to_string(other).unwrap_or_default(),
            };
            Some(format!(
                "[tool_result] {}",
                mask_session_mirror_bounded(&content_str, 500)
            ))
        }
        _ => None,
    }
}

/// Context threaded through one conversation's DFS walk. See
/// `crates/khive-pack-session/docs/api/mirror-parse.md#convcontext`.
struct ConvContext<'a> {
    mapping: &'a Map<String, Value>,
    current_path: &'a HashSet<String>,
    session_id: &'a str,
    conv_created_at_micros: i64,
    slug: Option<&'a str>,
}

/// Parse one ChatGPT export conversation object (skips the whole
/// conversation on a missing/empty `id` or missing `mapping`), appending its
/// message-bearing nodes to `out` in deterministic DFS preorder. See
/// `crates/khive-pack-session/docs/api/mirror-parse.md#parse_conversation`.
fn parse_conversation(conv: &Value, out: &mut Vec<ParsedEvent>) {
    let Some(conv_obj) = conv.as_object() else {
        return;
    };
    let Some(session_id) = conv_obj
        .get("id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
    else {
        return;
    };
    let Some(mapping) = conv_obj.get("mapping").and_then(|v| v.as_object()) else {
        return;
    };

    let slug = conv_obj
        .get("title")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(|title| mask_session_mirror(title).into_owned());

    let conv_created_at_micros = conv_obj
        .get("create_time")
        .and_then(|v| v.as_f64())
        .map(|secs| (secs * 1_000_000.0) as i64)
        .unwrap_or(0);

    // current-path set: walk current_node -> parent -> ... -> root; off-path
    // nodes are flagged is_sidechain (see docs guide).
    let mut current_path: HashSet<String> = HashSet::new();
    if let Some(current_node) = conv_obj.get("current_node").and_then(|v| v.as_str()) {
        let mut cursor = Some(current_node.to_string());
        while let Some(node_id) = cursor {
            if !current_path.insert(node_id.clone()) {
                break; // cycle guard against malformed mapping data
            }
            cursor = mapping
                .get(&node_id)
                .and_then(|n| n.as_object())
                .and_then(|n| n.get("parent"))
                .and_then(|v| v.as_str())
                .map(str::to_string);
        }
    }

    let root_id = mapping.iter().find_map(|(id, node)| {
        let node_obj = node.as_object()?;
        let parent_is_null = node_obj.get("parent").map(|v| v.is_null()).unwrap_or(true);
        parent_is_null.then(|| id.clone())
    });
    let Some(root_id) = root_id else {
        return;
    };

    let ctx = ConvContext {
        mapping,
        current_path: &current_path,
        session_id,
        conv_created_at_micros,
        slug: slug.as_deref(),
    };

    // Deterministic DFS preorder, explicit stack (not recursion — see docs guide).
    let mut stack: Vec<String> = vec![root_id];
    let mut visited: HashSet<String> = HashSet::new();

    while let Some(node_id) = stack.pop() {
        if !visited.insert(node_id.clone()) {
            continue; // cycle guard
        }
        let Some(node) = mapping.get(&node_id).and_then(|n| n.as_object()) else {
            continue;
        };

        if let Some(message) = node.get("message").filter(|m| !m.is_null()) {
            if let Some(message_obj) = message.as_object() {
                if let Some(ev) = build_chatgpt_event(&node_id, node, message_obj, &ctx) {
                    out.push(ev);
                }
            }
        }

        if let Some(children) = node.get("children").and_then(|c| c.as_array()) {
            // Push in reverse so the first child in the array is popped (and
            // thus visited) first — preorder must follow children order.
            for child in children.iter().rev() {
                if let Some(child_id) = child.as_str() {
                    stack.push(child_id.to_string());
                }
            }
        }
    }
}

/// Build a `ParsedEvent` for a single message-bearing mapping node; `None`
/// on a missing `id` or empty/whitespace-only extracted text (ChatGPT
/// scaffolding nodes). See
/// `crates/khive-pack-session/docs/api/mirror-parse.md#build_chatgpt_event`.
fn build_chatgpt_event(
    node_id: &str,
    node: &Map<String, Value>,
    message: &Map<String, Value>,
    ctx: &ConvContext,
) -> Option<ParsedEvent> {
    let uuid = message
        .get("id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())?
        .to_string();

    let role = message
        .get("author")
        .and_then(|a| a.as_object())
        .and_then(|a| a.get("role"))
        .and_then(|v| v.as_str())
        .map(str::to_string);

    let content = message.get("content").and_then(|c| c.as_object());
    let content_type = content
        .and_then(|c| c.get("content_type"))
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    let text = extract_chatgpt_text(&content_type, content)?;
    if text.trim().is_empty() {
        return None;
    }

    let created_at_micros = message
        .get("create_time")
        .and_then(|v| v.as_f64())
        .map(|secs| (secs * 1_000_000.0) as i64)
        .unwrap_or(ctx.conv_created_at_micros);

    // parent_uuid is Some only when the parent node itself carries a message
    // (provenance linkage — see docs guide).
    let parent_uuid = node
        .get("parent")
        .and_then(|v| v.as_str())
        .filter(|pid| {
            ctx.mapping
                .get(*pid)
                .and_then(|p| p.as_object())
                .and_then(|p| p.get("message"))
                .map(|m| !m.is_null())
                .unwrap_or(false)
        })
        .map(str::to_string);

    let is_sidechain = !ctx.current_path.contains(node_id);

    let raw_json = serde_json::to_string(node).unwrap_or_default();
    let raw = mask_session_mirror(&raw_json).into_owned();
    let text = mask_session_mirror(&text).into_owned();

    Some(ParsedEvent {
        uuid,
        session_id: ctx.session_id.to_string(),
        parent_uuid,
        is_sidechain,
        role,
        msg_type: content_type,
        text: Some(text),
        raw,
        created_at_micros,
        cwd: None,
        git_branch: None,
        slug: ctx.slug.map(str::to_string),
    })
}

/// Extract display text from a ChatGPT message `content` object per its
/// `content_type`. See
/// `crates/khive-pack-session/docs/api/mirror-parse.md#extract_chatgpt_text`.
fn extract_chatgpt_text(
    content_type: &str,
    content: Option<&Map<String, Value>>,
) -> Option<String> {
    let content = content?;

    if content_type == "text" {
        let parts = content.get("parts")?.as_array()?;
        let joined: Vec<String> = parts
            .iter()
            .filter_map(|p| p.as_str().map(str::to_string))
            .collect();
        return if joined.is_empty() {
            None
        } else {
            Some(joined.join("\n"))
        };
    }

    if let Some(text) = content.get("text").and_then(|v| v.as_str()) {
        return Some(text.to_string());
    }

    let parts = content.get("parts")?.as_array()?;
    let joined: Vec<String> = parts
        .iter()
        .filter_map(|p| p.as_str().map(str::to_string))
        .collect();
    if joined.is_empty() {
        None
    } else {
        Some(joined.join("\n"))
    }
}

// ── unit tests ────────────────────────────────────────────────────────────────

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

    fn anthropic_api_key_fixture() -> String {
        format!("sk-ant-api03-{}AA", "A".repeat(93))
    }

    fn github_fine_grained_pat_fixture() -> String {
        format!("github_pat_{}", "A".repeat(82))
    }

    // Helper: build a minimal CC event JSON string.
    fn make_line(uuid: &str, session_id: &str, type_: &str, extra: &str) -> String {
        format!(
            r#"{{"uuid":"{uuid}","sessionId":"{session_id}","type":"{type_}","timestamp":"2026-06-29T10:00:00Z"{extra}}}"#,
        )
    }

    #[test]
    fn test_blank_line_returns_none() {
        assert!(parse_cc_line("").is_none());
        assert!(parse_cc_line("   ").is_none());
    }

    #[test]
    fn test_no_uuid_returns_none() {
        // pr-link style: no uuid
        let line = r#"{"type":"pr-link","sessionId":"sess-1","url":"https://github.com/foo"}"#;
        assert!(parse_cc_line(line).is_none());
    }

    #[test]
    fn test_no_session_id_returns_none() {
        let line = r#"{"uuid":"aaaa-bbbb","type":"user"}"#;
        assert!(parse_cc_line(line).is_none());
    }

    #[test]
    fn test_user_text_line() {
        let line = make_line(
            "aaaa-bbbb",
            "sess-1111",
            "user",
            r#","message":{"role":"user","content":"Hello world"},"cwd":"/proj","gitBranch":"main","slug":"my-proj""#,
        );
        let ev = parse_cc_line(&line).expect("should parse");
        assert_eq!(ev.uuid, "aaaa-bbbb");
        assert_eq!(ev.session_id, "sess-1111");
        assert_eq!(ev.role.as_deref(), Some("user"));
        assert_eq!(ev.msg_type, "user");
        assert_eq!(ev.text.as_deref(), Some("Hello world"));
        assert_eq!(ev.cwd.as_deref(), Some("/proj"));
        assert_eq!(ev.git_branch.as_deref(), Some("main"));
        assert_eq!(ev.slug.as_deref(), Some("my-proj"));
        assert!(ev.created_at_micros > 0);
        assert!(!ev.is_sidechain);
    }

    #[test]
    fn test_cc_line_masks_secret_bearing_slug() {
        let secret = format!("{}{}", "AKIA", "FAKEKEY1234567890");
        let line = make_line(
            "aaaa-bbbb",
            "sess-1111",
            "user",
            &format!(
                r#","message":{{"role":"user","content":"Hello world"}},"slug":"prod creds {secret}""#
            ),
        );
        let ev = parse_cc_line(&line).expect("should parse");
        let slug = ev.slug.as_deref().expect("slug");
        assert!(!slug.contains(&secret));
        assert!(slug.contains("***MASKED***"));
    }

    #[test]
    fn test_cc_line_masks_secret_bearing_cwd_and_git_branch() {
        let marker = "CwdCredMarkerXYZ789";
        let cwd = format!("/repo?token=postgres://svc:{marker}q@internal-host.example.test/db");
        let branch = format!("feature/postgres://svc:{marker}q@internal-host.example.test/db");
        let line = make_line(
            "aaaa-cwd1",
            "sess-1111",
            "user",
            &format!(
                r#","message":{{"role":"user","content":"Hello world"}},"cwd":"{cwd}","gitBranch":"{branch}""#
            ),
        );
        let ev = parse_cc_line(&line).expect("should parse");
        let stored_cwd = ev.cwd.as_deref().expect("cwd");
        let stored_branch = ev.git_branch.as_deref().expect("git_branch");
        assert!(!stored_cwd.contains(marker), "cwd: {stored_cwd}");
        assert!(stored_cwd.contains("***MASKED***"), "cwd: {stored_cwd}");
        assert!(
            !stored_branch.contains(marker),
            "git_branch: {stored_branch}"
        );
        assert!(
            stored_branch.contains("***MASKED***"),
            "git_branch: {stored_branch}"
        );
    }

    #[test]
    fn test_assistant_with_text_and_tool_use_blocks() {
        let line = r#"{"uuid":"cccc-dddd","sessionId":"sess-1111","type":"assistant","timestamp":"2026-06-29T10:01:00Z","message":{"role":"assistant","content":[{"type":"text","text":"I'll run a search."},{"type":"tool_use","name":"bash","input":{"command":"ls"}}]}}"#
            .to_string();
        let ev = parse_cc_line(&line).expect("should parse");
        assert_eq!(ev.role.as_deref(), Some("assistant"));
        let text = ev.text.expect("text should be present");
        assert!(text.contains("I'll run a search."), "text: {text}");
        assert!(text.contains("[tool_use: bash]"), "text: {text}");
        assert!(text.contains("command"), "text: {text}");
    }

    #[test]
    fn test_tool_use_input_credential_masked_before_truncation() {
        // The credential's terminating `@` lands past the 500-character
        // display cap applied to a tool_use input block. A masker that only
        // sees the already-truncated prefix can never recognize the span, so
        // the password marker survives untouched in the stored `text`.
        let marker = "ToolUseCredMarkerXYZ789";
        let padding = "z".repeat(600);
        let password = format!("{marker}{padding}");
        let url = format!("postgres://svc:{password}@internal-host.example.com/db");
        let input = serde_json::json!({ "url": url });
        let serialized_input = serde_json::to_string(&input).unwrap();
        let at_offset = serialized_input
            .find('@')
            .expect("fixture must contain '@'");
        assert!(at_offset > 500);

        let content = serde_json::json!([
            { "type": "tool_use", "name": "bash", "input": input }
        ]);
        let message = serde_json::json!({
            "uuid": "tool-use-cred",
            "sessionId": "sess-cred",
            "type": "assistant",
            "timestamp": "2026-06-29T10:01:00Z",
            "message": { "role": "assistant", "content": content }
        });
        let line = message.to_string();

        let ev = parse_cc_line(&line).expect("should parse");
        let text = ev.text.expect("text should be present");
        assert!(
            !text.contains(marker),
            "no fragment of the credential may survive masking: {text}"
        );
        assert!(
            text.contains("***MASKED***"),
            "MASKED marker must appear in text: {text}"
        );
    }

    #[test]
    fn test_tool_result_content_credential_masked_before_truncation() {
        // Same shape as the tool_use case above, but for a tool_result
        // content string whose credential terminator crosses the 500-char cut.
        let marker = "ToolResultCredMarkerXYZ789";
        let padding = "z".repeat(600);
        let password = format!("{marker}{padding}");
        let url = format!("postgres://svc:{password}@internal-host.example.com/db");
        let at_offset = url.find('@').expect("fixture must contain '@'");
        assert!(at_offset > 500);

        let content = serde_json::json!([
            { "type": "tool_result", "content": url }
        ]);
        let message = serde_json::json!({
            "uuid": "tool-result-cred",
            "sessionId": "sess-cred",
            "type": "user",
            "timestamp": "2026-06-29T10:02:00Z",
            "message": { "role": "user", "content": content }
        });
        let line = message.to_string();

        let ev = parse_cc_line(&line).expect("should parse");
        let text = ev.text.expect("text should be present");
        assert!(
            !text.contains(marker),
            "no fragment of the credential may survive masking: {text}"
        );
        assert!(
            text.contains("***MASKED***"),
            "MASKED marker must appear in text: {text}"
        );
    }

    #[test]
    fn test_tool_result_block() {
        let line = r#"{"uuid":"eeee-ffff","sessionId":"sess-1111","type":"user","timestamp":"2026-06-29T10:02:00Z","message":{"role":"user","content":[{"type":"tool_result","content":"file1.rs\nfile2.rs"}]}}"#
            .to_string();
        let ev = parse_cc_line(&line).expect("should parse");
        let text = ev.text.expect("text should be present");
        assert!(text.contains("[tool_result]"), "text: {text}");
        assert!(text.contains("file1.rs"), "text: {text}");
    }

    #[test]
    fn test_attachment_line_no_message() {
        // uuid present, sessionId present, but no message -> role/text None
        let line = r#"{"uuid":"gggg-hhhh","sessionId":"sess-1111","type":"attachment","timestamp":"2026-06-29T10:02:00Z","filename":"file.txt"}"#
            .to_string();
        let ev = parse_cc_line(&line).expect("should parse");
        assert_eq!(ev.msg_type, "attachment");
        assert!(ev.role.is_none());
        assert!(ev.text.is_none());
    }

    #[test]
    fn test_secret_masking_in_text_and_raw() {
        let secret = anthropic_api_key_fixture();
        let line = format!(
            r#"{{"uuid":"iiii-jjjj","sessionId":"sess-1111","type":"user","timestamp":"2026-06-29T10:03:00Z","message":{{"role":"user","content":"my key is {secret}"}}}}"#
        );
        let ev = parse_cc_line(&line).expect("should parse");

        let text = ev.text.expect("text should be present");
        assert!(
            !text.contains(secret.as_str()),
            "secret must not appear in text: {text}"
        );
        assert!(
            text.contains("***MASKED***"),
            "MASKED marker must appear in text: {text}"
        );

        assert!(
            !ev.raw.contains(secret.as_str()),
            "secret must not appear in raw: {}",
            ev.raw
        );
        assert!(
            ev.raw.contains("***MASKED***"),
            "MASKED marker must appear in raw: {}",
            ev.raw
        );
    }

    #[test]
    fn test_github_pat_masked() {
        let secret = github_fine_grained_pat_fixture();
        let line = format!(
            r#"{{"uuid":"kkkk-llll","sessionId":"sess-2","type":"user","timestamp":"2026-06-29T10:04:00Z","message":{{"role":"user","content":"token={secret}"}}}}"#
        );
        let ev = parse_cc_line(&line).unwrap();
        assert!(!ev.raw.contains(secret.as_str()));
        assert!(ev.raw.contains("***MASKED***"));
    }

    #[test]
    fn test_timestamp_to_micros() {
        let line = make_line(
            "ts-test",
            "sess-ts",
            "system",
            r#","timestamp":"2026-06-29T17:56:01.123Z""#,
        );
        let ev = parse_cc_line(&line).unwrap();
        // 2026-06-29T17:56:01.123Z in micros should be a large positive number
        assert!(ev.created_at_micros > 0, "created_at_micros should be > 0");
    }

    #[test]
    fn test_sidechain_flag() {
        let line = make_line("side-uuid", "sess-side", "user", r#","isSidechain":true"#);
        let ev = parse_cc_line(&line).unwrap();
        assert!(ev.is_sidechain);
    }

    // ── parse_codex_line tests ─────────────────────────────────────────────────

    const CDX_SID: &str = "cdx-session-0001-0001-0001-000000000001";

    /// Build a Codex user message line using the real `input_text` block shape.
    fn codex_user_msg(text: &str) -> String {
        format!(
            r#"{{"type":"response_item","timestamp":"2026-06-30T09:00:00Z","payload":{{"type":"message","role":"user","content":[{{"type":"input_text","text":"{text}"}}]}}}}"#
        )
    }

    /// Build a Codex assistant message line using the real `output_text` block shape.
    fn codex_asst_msg(text: &str) -> String {
        format!(
            r#"{{"type":"response_item","timestamp":"2026-06-30T09:00:00Z","payload":{{"type":"message","role":"assistant","content":[{{"type":"output_text","text":"{text}"}}]}}}}"#
        )
    }

    /// Build a Codex session_meta line.
    fn codex_meta(cwd: &str, branch: &str) -> String {
        format!(
            r#"{{"type":"session_meta","timestamp":"2026-06-30T09:00:00Z","payload":{{"id":"{CDX_SID}","cwd":"{cwd}","git":{{"branch":"{branch}","commit_hash":"abc123","repository_url":"https://github.com/example/repo"}}}}}}"#
        )
    }

    /// Build a Codex response_item with a tool_use block (no text block).
    fn codex_tool_use_msg() -> String {
        r#"{"type":"response_item","timestamp":"2026-06-30T09:01:00Z","payload":{"type":"message","role":"assistant","content":[{"type":"tool_use","name":"bash","input":{"command":"cargo test"}}]}}"#.to_string()
    }

    /// Build a Codex event_msg line (duplicate; must be skipped).
    fn codex_event_msg() -> String {
        r#"{"type":"event_msg","timestamp":"2026-06-30T09:00:00Z","payload":{"type":"user_message","content":"duplicate"}}"#.to_string()
    }

    #[test]
    fn test_codex_blank_returns_none() {
        assert!(parse_codex_line("", CDX_SID, 0).is_none());
        assert!(parse_codex_line("   ", CDX_SID, 0).is_none());
    }

    #[test]
    fn test_codex_event_msg_skipped() {
        let line = codex_event_msg();
        assert!(
            parse_codex_line(&line, CDX_SID, 42).is_none(),
            "event_msg must be skipped"
        );
    }

    #[test]
    fn test_codex_unknown_type_skipped() {
        let line = r#"{"type":"some_other_event","timestamp":"2026-06-30T09:00:00Z","payload":{}}"#;
        assert!(parse_codex_line(line, CDX_SID, 0).is_none());
    }

    #[test]
    fn test_codex_session_meta_produces_event() {
        let line = codex_meta("/workspace/proj", "main");
        let ev = parse_codex_line(&line, CDX_SID, 0).expect("session_meta should parse");
        assert_eq!(ev.session_id, CDX_SID);
        assert_eq!(ev.msg_type, "session_meta");
        assert_eq!(ev.cwd.as_deref(), Some("/workspace/proj"));
        assert_eq!(ev.git_branch.as_deref(), Some("main"));
        assert!(ev.role.is_none());
        assert!(ev.text.is_none());
        // Synthetic uuid: "{session_id}:{offset}".
        assert_eq!(ev.uuid, format!("{CDX_SID}:0"));
        assert!(ev.created_at_micros > 0);
    }

    #[test]
    fn test_codex_session_meta_masks_secret_bearing_cwd_and_branch() {
        let marker = "CodexCwdCredMarkerXYZ789";
        let cwd = format!("/repo?token=postgres://svc:{marker}q@internal-host.example.test/db");
        let branch = format!("feature/postgres://svc:{marker}q@internal-host.example.test/db");
        let line = codex_meta(&cwd, &branch);
        let ev = parse_codex_line(&line, CDX_SID, 0).expect("session_meta should parse");
        let stored_cwd = ev.cwd.as_deref().expect("cwd");
        let stored_branch = ev.git_branch.as_deref().expect("git_branch");
        assert!(!stored_cwd.contains(marker), "cwd: {stored_cwd}");
        assert!(stored_cwd.contains("***MASKED***"), "cwd: {stored_cwd}");
        assert!(
            !stored_branch.contains(marker),
            "git_branch: {stored_branch}"
        );
        assert!(
            stored_branch.contains("***MASKED***"),
            "git_branch: {stored_branch}"
        );
    }

    #[test]
    fn test_codex_user_message_input_text_block() {
        // Regression: real Codex user messages use `input_text` blocks.
        let line = codex_user_msg("Hello Codex");
        let ev = parse_codex_line(&line, CDX_SID, 128).expect("user message should parse");
        assert_eq!(ev.session_id, CDX_SID);
        assert_eq!(ev.msg_type, "response_item");
        assert_eq!(ev.role.as_deref(), Some("user"));
        // text must NOT be None — this was the NULL bug.
        let text = ev.text.expect("text must be non-NULL for input_text block");
        assert_eq!(text, "Hello Codex");
        assert_eq!(ev.uuid, format!("{CDX_SID}:128"));
    }

    #[test]
    fn test_codex_assistant_message_output_text_block() {
        // Regression: real Codex assistant messages use `output_text` blocks.
        let line = codex_asst_msg("Hello from assistant");
        let ev = parse_codex_line(&line, CDX_SID, 256).expect("assistant message should parse");
        assert_eq!(ev.role.as_deref(), Some("assistant"));
        // text must NOT be None.
        let text = ev
            .text
            .expect("text must be non-NULL for output_text block");
        assert_eq!(text, "Hello from assistant");
        assert_eq!(ev.uuid, format!("{CDX_SID}:256"));
    }

    #[test]
    fn test_codex_tool_use_block_extracted() {
        let line = codex_tool_use_msg();
        let ev = parse_codex_line(&line, CDX_SID, 512).expect("tool_use message should parse");
        assert_eq!(ev.role.as_deref(), Some("assistant"));
        let text = ev.text.expect("text must be present");
        assert!(text.contains("[tool_use: bash]"), "text: {text}");
        assert!(text.contains("cargo test"), "text: {text}");
    }

    #[test]
    fn test_codex_text_truncated_at_500_chars() {
        // input_text block with 600-char body — must be truncated.
        let long_text = "x".repeat(600);
        let line = codex_user_msg(&long_text);
        let ev = parse_codex_line(&line, CDX_SID, 0).expect("should parse");
        let text = ev.text.expect("text must be present");
        // char count must be ≤ 501 (500 + the '…' ellipsis char).
        assert!(
            text.chars().count() <= 501,
            "text must be truncated: len={}",
            text.chars().count()
        );
        assert!(text.ends_with('…'), "truncated text must end with ellipsis");
    }

    #[test]
    fn test_codex_secret_masked_in_text_and_raw() {
        // input_text block carrying a secret — masking must apply to both text and raw.
        let secret = anthropic_api_key_fixture();
        let line = codex_user_msg(&secret);
        let ev = parse_codex_line(&line, CDX_SID, 0).expect("should parse");
        let text = ev.text.expect("text present");
        assert!(
            !text.contains(secret.as_str()),
            "secret must not appear in text"
        );
        assert!(
            text.contains("***MASKED***"),
            "MASKED marker must appear in text"
        );
        assert!(
            !ev.raw.contains(secret.as_str()),
            "secret must not appear in raw"
        );
        assert!(
            ev.raw.contains("***MASKED***"),
            "MASKED marker must appear in raw"
        );
    }

    #[test]
    fn test_codex_synthetic_uuid_stable_across_calls() {
        // The same line at the same offset must produce the same uuid regardless
        // of how many times it is called (deterministic, no random component).
        let line = codex_user_msg("consistency");
        let ev1 = parse_codex_line(&line, CDX_SID, 999).unwrap();
        let ev2 = parse_codex_line(&line, CDX_SID, 999).unwrap();
        assert_eq!(ev1.uuid, ev2.uuid);
        assert_eq!(ev1.uuid, format!("{CDX_SID}:999"));
    }

    #[test]
    fn test_codex_response_item_non_message_payload_skipped() {
        // A response_item where payload.type != "message" must be skipped.
        let line = r#"{"type":"response_item","timestamp":"2026-06-30T09:00:00Z","payload":{"type":"tool_call","name":"some_tool"}}"#;
        assert!(parse_codex_line(line, CDX_SID, 0).is_none());
    }

    #[test]
    fn test_cc_text_block_still_works() {
        // Regression guard: adding input_text/output_text must not break the
        // existing CC "text" block handling.
        let line = r#"{"uuid":"cc-t1","sessionId":"cc-sess","type":"assistant","timestamp":"2026-06-30T09:00:00Z","message":{"role":"assistant","content":[{"type":"text","text":"CC still works"}]}}"#;
        let ev = parse_cc_line(line).expect("CC text block must parse");
        assert_eq!(ev.text.as_deref(), Some("CC still works"));
    }

    // ── parse_claude_ai_export: direct unit tests ───────────────────────────

    #[test]
    fn test_claude_ai_export_preserves_ids_order_roles_and_title() {
        let export = serde_json::json!([{
            "uuid": "claude-conv-1",
            "name": "Claude Web Conversation",
            "created_at": "2026-07-31T10:00:00Z",
            "current_leaf_message_uuid": "claude-msg-2",
            "chat_messages": [
                {
                    "uuid": "claude-msg-2",
                    "sender": "assistant",
                    "index": 1,
                    "parent_message_uuid": "claude-msg-1",
                    "created_at": "2026-07-31T10:00:02Z",
                    "content": [
                        {"type": "thinking", "thinking": "not display text"},
                        {"type": "text", "text": "Hello from Claude"}
                    ]
                },
                {
                    "uuid": "claude-msg-1",
                    "sender": "human",
                    "index": 0,
                    "parent_message_uuid": "00000000-0000-4000-8000-000000000000",
                    "created_at": "2026-07-31T10:00:01Z",
                    "content": [{"type": "text", "text": "Hello"}]
                }
            ]
        }]);

        let events = parse_claude_ai_export(&export.to_string()).expect("valid export");
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].uuid, "claude-msg-1");
        assert_eq!(events[0].session_id, "claude-conv-1");
        assert_eq!(events[0].role.as_deref(), Some("user"));
        assert_eq!(events[0].text.as_deref(), Some("Hello"));
        assert_eq!(events[0].parent_uuid, None);
        assert_eq!(events[0].slug.as_deref(), Some("Claude Web Conversation"));
        assert!(!events[0].is_sidechain);

        assert_eq!(events[1].uuid, "claude-msg-2");
        assert_eq!(events[1].role.as_deref(), Some("assistant"));
        assert_eq!(events[1].text.as_deref(), Some("Hello from Claude"));
        assert_eq!(events[1].parent_uuid.as_deref(), Some("claude-msg-1"));
        assert!(!events[1].is_sidechain);
        assert!(events[1].created_at_micros > events[0].created_at_micros);
    }

    #[test]
    fn test_claude_ai_export_preserves_branches_and_marks_inactive_path() {
        let export = serde_json::json!([{
            "uuid": "claude-conv-branch",
            "name": "Branching Claude Conversation",
            "current_leaf_message_uuid": "claude-main",
            "chat_messages": [
                {
                    "uuid": "claude-user",
                    "sender": "human",
                    "index": 0,
                    "parent_message_uuid": null,
                    "content": [{"type": "text", "text": "Question"}]
                },
                {
                    "uuid": "claude-main",
                    "sender": "assistant",
                    "index": 1,
                    "parent_message_uuid": "claude-user",
                    "content": [{"type": "text", "text": "Current answer"}]
                },
                {
                    "uuid": "claude-alt",
                    "sender": "assistant",
                    "index": 2,
                    "parent_message_uuid": "claude-user",
                    "content": [{"type": "text", "text": "Alternate answer"}]
                }
            ]
        }]);

        let events = parse_claude_ai_export(&export.to_string()).expect("valid branch export");
        assert_eq!(events.len(), 3, "alternate branches must be retained");
        assert!(!events[0].is_sidechain);
        assert!(!events[1].is_sidechain);
        assert!(events[2].is_sidechain);
        assert_eq!(events[2].uuid, "claude-alt");
        assert_eq!(events[2].parent_uuid.as_deref(), Some("claude-user"));
    }

    #[test]
    fn test_claude_ai_export_keeps_blocks_and_distinct_top_level_answer() {
        let export = serde_json::json!([{
            "uuid": "claude-conv-agent",
            "chat_messages": [
                {
                    "uuid": "claude-agent-turn",
                    "sender": "assistant",
                    "text": "Final answer",
                    "content": [
                        {"type": "tool_use", "name": "bash_tool", "input": {"command": "pwd"}},
                        {"type": "tool_result", "content": [{"type": "text", "text": "/tmp"}]}
                    ]
                },
                {
                    "uuid": "claude-deduplicated-text",
                    "sender": "assistant",
                    "text": "Already present",
                    "content": [{"type": "text", "text": "Already present"}]
                }
            ]
        }]);

        let events = parse_claude_ai_export(&export.to_string()).expect("valid agent export");
        assert_eq!(events.len(), 2);
        let agent_text = events[0].text.as_deref().expect("agent turn text");
        assert!(agent_text.contains("[tool_use: bash_tool]"));
        assert!(agent_text.contains("[tool_result]"));
        assert!(agent_text.ends_with("Final answer"));
        assert_eq!(events[1].text.as_deref(), Some("Already present"));
    }

    #[test]
    fn test_claude_ai_export_accepts_legacy_role_and_voice_note_text() {
        let export = serde_json::json!([{
            "uuid": "claude-conv-voice",
            "chat_messages": [{
                "uuid": "claude-voice-turn",
                "role": "human",
                "content": [{"type": "voice_note", "title": "Memo", "text": "Spoken prompt"}]
            }]
        }]);

        let events = parse_claude_ai_export(&export.to_string()).expect("valid legacy export");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].role.as_deref(), Some("user"));
        assert_eq!(events[0].text.as_deref(), Some("Spoken prompt"));
    }

    #[test]
    fn test_claude_ai_export_legacy_flat_text_is_masked() {
        let secret = format!("{}{}", "AKIA", "FAKEKEY1234567890");
        let export = serde_json::json!([{
            "uuid": "claude-conv-flat",
            "summary": "Legacy export",
            "chat_messages": [
                {
                    "uuid": "claude-flat-user",
                    "sender": "human",
                    "text": format!("key={secret}"),
                    "created_at": "2026-07-31T10:00:00Z"
                },
                {
                    "uuid": "claude-flat-assistant",
                    "sender": "assistant",
                    "text": "Legacy assistant text",
                    "content": [{"type": "thinking", "thinking": "not visible"}],
                    "created_at": "2026-07-31T10:00:01Z"
                }
            ]
        }]);

        let events = parse_claude_ai_export(&export.to_string()).expect("legacy export");
        assert_eq!(events.len(), 2);
        assert!(events.iter().all(|event| !event.is_sidechain));
        assert_eq!(events[0].slug.as_deref(), Some("Legacy export"));
        assert!(!events[0].text.as_deref().unwrap().contains(&secret));
        assert!(events[0].text.as_deref().unwrap().contains("***MASKED***"));
        assert!(!events[0].raw.contains(&secret));
        assert_eq!(events[1].text.as_deref(), Some("Legacy assistant text"));
    }

    #[test]
    fn test_claude_ai_export_masks_secret_bearing_title_and_summary() {
        let secret = format!("{}{}", "AKIA", "FAKEKEY1234567890");
        let export = serde_json::json!([
            {
                "uuid": "claude-conv-secret-name",
                "name": format!("prod creds {secret}"),
                "chat_messages": [{
                    "uuid": "claude-secret-name-user",
                    "sender": "human",
                    "text": "hello",
                    "created_at": "2026-07-31T10:00:00Z"
                }]
            },
            {
                "uuid": "claude-conv-secret-summary",
                "summary": format!("key={secret}"),
                "chat_messages": []
            }
        ]);

        let parsed =
            parse_claude_ai_export_with_sessions(&export.to_string()).expect("secret-title export");
        assert_eq!(parsed.sessions.len(), 2);
        for session in &parsed.sessions {
            let slug = session.slug.as_deref().expect("session slug");
            assert!(!slug.contains(&secret));
            assert!(slug.contains("***MASKED***"));
        }
        assert_eq!(parsed.events.len(), 1);
        let event_slug = parsed.events[0].slug.as_deref().expect("event slug");
        assert!(!event_slug.contains(&secret));
        assert!(event_slug.contains("***MASKED***"));
    }

    #[test]
    fn test_claude_ai_export_rejects_bad_top_level_and_skips_bad_conversations() {
        assert!(parse_claude_ai_export("not json").is_none());
        assert!(parse_claude_ai_export(r#"{"uuid":"not-an-array"}"#).is_none());

        let export = serde_json::json!([
            {"uuid": "missing-messages"},
            {
                "uuid": "claude-valid",
                "chat_messages": [{
                    "uuid": "claude-valid-message",
                    "sender": "human",
                    "text": "kept"
                }]
            }
        ]);
        let events = parse_claude_ai_export(&export.to_string()).expect("valid array");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].session_id, "claude-valid");
    }

    #[test]
    fn test_provider_export_parsers_reject_the_other_source_shape() {
        let claude_ai = serde_json::json!([{
            "uuid": "claude-conversation",
            "chat_messages": []
        }]);
        assert!(parse_chatgpt_export(&claude_ai.to_string()).is_none());

        let chatgpt = serde_json::json!([{
            "id": "chatgpt-conversation",
            "mapping": {}
        }]);
        assert!(parse_claude_ai_export(&chatgpt.to_string()).is_none());

        let mixed = serde_json::json!([
            {"uuid": "claude-conversation", "chat_messages": []},
            {"id": "chatgpt-conversation", "mapping": {}}
        ]);
        assert!(parse_chatgpt_export(&mixed.to_string()).is_none());
        assert!(parse_claude_ai_export(&mixed.to_string()).is_none());

        assert_eq!(parse_chatgpt_export("[]"), Some(Vec::new()));
        assert_eq!(parse_claude_ai_export("[]"), Some(Vec::new()));
    }

    // ── parse_chatgpt_export: direct unit tests ─────────────────────────────
    //
    // Unlike the end-to-end mirror_chatgpt_export_file tests in ingest.rs
    // (which go through file I/O + SQL), these exercise the pure JSON-tree
    // parsing seam directly with no runtime or DB setup.

    #[test]
    fn test_chatgpt_export_minimal_valid_export() {
        let export = serde_json::json!([{
            "id": "conv-min",
            "title": "Minimal Export",
            "current_node": "msg-assistant",
            "create_time": 1_700_000_000.0,
            "mapping": {
                "root": {
                    "id": "root",
                    "message": null,
                    "parent": null,
                    "children": ["msg-user"]
                },
                "msg-user": {
                    "id": "msg-user",
                    "parent": "root",
                    "children": ["msg-assistant"],
                    "message": {
                        "id": "msg-user",
                        "author": {"role": "user"},
                        "content": {"content_type": "text", "parts": ["Hello"]}
                    }
                },
                "msg-assistant": {
                    "id": "msg-assistant",
                    "parent": "msg-user",
                    "children": [],
                    "message": {
                        "id": "msg-assistant",
                        "author": {"role": "assistant"},
                        "content": {"content_type": "text", "parts": ["Hi there"]}
                    }
                }
            }
        }]);
        let content = serde_json::to_string(&export).unwrap();

        let events = parse_chatgpt_export(&content).expect("valid export must parse");
        assert_eq!(events.len(), 2, "root has no message, 2 nodes carry one");

        assert_eq!(events[0].uuid, "msg-user");
        assert_eq!(events[0].session_id, "conv-min");
        assert_eq!(events[0].role.as_deref(), Some("user"));
        assert_eq!(events[0].text.as_deref(), Some("Hello"));
        assert_eq!(events[0].parent_uuid, None, "root carries no message");
        assert!(!events[0].is_sidechain);
        assert_eq!(events[0].slug.as_deref(), Some("Minimal Export"));

        assert_eq!(events[1].uuid, "msg-assistant");
        assert_eq!(events[1].role.as_deref(), Some("assistant"));
        assert_eq!(events[1].text.as_deref(), Some("Hi there"));
        assert_eq!(events[1].parent_uuid.as_deref(), Some("msg-user"));
        assert!(!events[1].is_sidechain);
    }

    #[test]
    fn test_chatgpt_export_masks_secret_bearing_title() {
        let secret = format!("{}{}", "AKIA", "FAKEKEY1234567890");
        let export = serde_json::json!([{
            "id": "conv-secret-title",
            "title": format!("prod creds {secret}"),
            "current_node": "msg-user",
            "create_time": 1_700_000_000.0,
            "mapping": {
                "root": {
                    "id": "root",
                    "message": null,
                    "parent": null,
                    "children": ["msg-user"]
                },
                "msg-user": {
                    "id": "msg-user",
                    "parent": "root",
                    "children": [],
                    "message": {
                        "id": "msg-user",
                        "author": {"role": "user"},
                        "content": {"content_type": "text", "parts": ["Hello"]}
                    }
                }
            }
        }]);
        let content = serde_json::to_string(&export).unwrap();

        let events = parse_chatgpt_export(&content).expect("valid export must parse");
        assert_eq!(events.len(), 1);
        let slug = events[0].slug.as_deref().expect("event slug");
        assert!(!slug.contains(&secret));
        assert!(slug.contains("***MASKED***"));
    }

    #[test]
    fn test_chatgpt_export_multi_branch_tree_dfs_order_and_sidechain() {
        // root -> user -> {main (current path), alt (regenerated/abandoned)}
        let export = serde_json::json!([{
            "id": "conv-branch",
            "title": "Branching Conversation",
            "current_node": "msg-main",
            "mapping": {
                "root": {
                    "id": "root",
                    "message": null,
                    "parent": null,
                    "children": ["msg-user"]
                },
                "msg-user": {
                    "id": "msg-user",
                    "parent": "root",
                    "children": ["msg-main", "msg-alt"],
                    "message": {
                        "id": "msg-user",
                        "author": {"role": "user"},
                        "content": {"content_type": "text", "parts": ["Question"]}
                    }
                },
                "msg-main": {
                    "id": "msg-main",
                    "parent": "msg-user",
                    "children": [],
                    "message": {
                        "id": "msg-main",
                        "author": {"role": "assistant"},
                        "content": {"content_type": "text", "parts": ["Main answer"]}
                    }
                },
                "msg-alt": {
                    "id": "msg-alt",
                    "parent": "msg-user",
                    "children": [],
                    "message": {
                        "id": "msg-alt",
                        "author": {"role": "assistant"},
                        "content": {"content_type": "text", "parts": ["Alternate answer"]}
                    }
                }
            }
        }]);
        let content = serde_json::to_string(&export).unwrap();

        let events = parse_chatgpt_export(&content).expect("branch export must parse");
        assert_eq!(events.len(), 3);

        // DFS preorder must follow the mapping's `children` array order, not
        // JSON object key order: user, then main, then alt.
        let uuids: Vec<&str> = events.iter().map(|e| e.uuid.as_str()).collect();
        assert_eq!(uuids, vec!["msg-user", "msg-main", "msg-alt"]);

        let by_uuid = |id: &str| events.iter().find(|e| e.uuid == id).unwrap();
        assert!(!by_uuid("msg-user").is_sidechain);
        assert!(
            !by_uuid("msg-main").is_sidechain,
            "current_node's own path must not be flagged"
        );
        assert!(
            by_uuid("msg-alt").is_sidechain,
            "branch off current_node path must be flagged sidechain"
        );
        assert_eq!(by_uuid("msg-alt").text.as_deref(), Some("Alternate answer"));
    }

    #[test]
    fn test_chatgpt_export_malformed_inputs() {
        // Top level not valid JSON at all -> None (caller must not advance cursor).
        assert!(parse_chatgpt_export("not json").is_none());

        // Valid JSON but not an array -> None.
        assert!(parse_chatgpt_export(r#"{"oops": "not an array"}"#).is_none());

        // Valid array, but individual malformed conversations (missing
        // mapping, missing id, non-object entry) must be skipped
        // individually rather than sinking the whole file.
        let export = serde_json::json!([
            {"id": "no-mapping"},
            {"mapping": {}},
            "not-an-object",
            {
                "id": "conv-good",
                "current_node": "msg-good",
                "mapping": {
                    "root": {"id": "root", "message": null, "parent": null, "children": ["msg-good"]},
                    "msg-good": {
                        "id": "msg-good",
                        "parent": "root",
                        "children": [],
                        "message": {
                            "id": "msg-good",
                            "author": {"role": "user"},
                            "content": {"content_type": "text", "parts": ["Still works"]}
                        }
                    }
                }
            }
        ]);
        let content = serde_json::to_string(&export).unwrap();

        let events = parse_chatgpt_export(&content)
            .expect("array with some malformed conversations still parses");
        assert_eq!(
            events.len(),
            1,
            "malformed conversations skipped, valid one still yields its event"
        );
        assert_eq!(events[0].uuid, "msg-good");
        assert_eq!(events[0].session_id, "conv-good");
    }
}