codenexus 0.3.11

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! CSV batch loading (ADR-014).
//!
//! Generates RFC 4180-compliant CSV for node and edge tables using the [`csv`]
//! crate, then loads them into LadybugDB via `COPY FROM`. This is the
//! recommended bulk-load path for large indexing runs (ADR-014).
//!
//! # Node → column mapping
//!
//! Each [`NodeLabel`] has a distinct column layout (see [`node_table_columns`]).
//! The [`node_to_row`] helper extracts values from a [`Node`], pulling
//! table-specific fields (e.g. `hash`, `content`, `parameterCount`) from the
//! node's `properties` JSON when they don't have a dedicated struct field.

use std::io::Write;
use std::path::Path;

use csv::WriterBuilder;

use super::connection::StorageConnection;
use super::error::{Result, StorageError};
use super::schema::{escape_identifier, node_table_columns, relation_table_columns};
use crate::model::{Edge, Node, NodeLabel};

/// Tab character used as the CSV delimiter.
///
/// LadybugDB's COPY parser does not correctly handle RFC 4180 quoted fields
/// containing commas (e.g. `FallbackChain<T, U>` — the comma inside the
/// angle brackets splits the field even though it's quoted). Switching to
/// tab-delimited format avoids this entirely because tab characters never
/// appear in code identifiers or file paths.
const CSV_DELIMITER: u8 = b'\t';

/// CSV batch loader for node and edge tables (ADR-014).
///
/// Stateless — the struct exists primarily for API symmetry with
/// [`crate::storage::Repository`] and to group the CSV-related functions.
#[derive(Debug, Clone, Default)]
pub struct CsvLoader;

impl CsvLoader {
    /// Creates a new [`CsvLoader`].
    #[must_use]
    pub const fn new() -> Self {
        Self
    }

    /// Streams a node table CSV directly to `path` on disk (L4 of the
    /// memory-overflow fix: no intermediate `String` allocation).
    ///
    /// Delegates to [`write_nodes_csv_stream`]. The file is created (or
    /// truncated) at `path` and the CSV is written row-by-row through a
    /// `csv::Writer` buffer.
    ///
    /// # L6-3 memory-overflow fix
    ///
    /// Accepts `impl IntoIterator<Item = &Node>` instead of `&[Node]` for API
    /// symmetry with [`write_nodes_csv_stream`]. Dedup stats are consumed
    /// internally: a warning is printed to stderr when any duplicates are
    /// skipped (fail-loud principle, mirroring [`Repository::save_nodes`]'s
    /// behavior).
    pub fn write_nodes_file<'a, I>(&self, nodes: I, label: NodeLabel, path: &Path) -> Result<()>
    where
        I: IntoIterator<Item = &'a Node>,
    {
        let file = std::fs::File::create(path)?;
        let stats = write_nodes_csv_stream(nodes, label, file)?;
        if stats.skipped_duplicates > 0 {
            eprintln!(
                "warning: skipped {} duplicate node(s) during CSV generation (unique: {})",
                stats.skipped_duplicates, stats.written
            );
        }
        Ok(())
    }

    /// Streams the `CodeRelation` CSV directly to `path` on disk (L4 of the
    /// memory-overflow fix).
    ///
    /// Delegates to [`write_edges_csv_stream`].
    pub fn write_edges_file(&self, edges: &[Edge], path: &Path) -> Result<()> {
        let file = std::fs::File::create(path)?;
        write_edges_csv_stream(edges, file).map(|_| ())
    }
}

/// Sanitizes a string field for LadybugDB COPY compatibility (B6 workaround).
///
/// LadybugDB's COPY parser does not correctly handle RFC 4180 quoted fields:
/// - Backslashes are treated as C-style escape chars (breaks C macro line
///   continuations in the redis sample).
/// - Doubled quotes (`""`) are not always parsed as a literal `"` (breaks
///   Python method signatures in the subno.ts sample).
/// - Multi-line quoted fields (newlines inside a quoted field) cause the
///   parser to report "expected N values per row, but got M" because it
///   cannot reconcile a quoted field spanning multiple physical lines with
///   its row-splitting logic (breaks any sample whose `content` or
///   `signature` field contains embedded newlines — e.g. subno.ts Python
///   methods, redis C function bodies).
/// - Tab characters inside a field collide with the tab delimiter and force
///   quoting, re-triggering the multi-line issue.
///
/// To prevent parser corruption, we replace these characters with visually
/// similar but parser-safe alternatives:
/// - `\` → `/` (consistent with [`load_from_csv`]'s path normalization)
/// - `"` → `'` (preserves readability of quoted strings in signatures)
/// - `\n` / `\r` → ` ` (space; collapses multi-line content to one line)
/// - `\t` → ` ` (space; prevents delimiter collision and forced quoting)
///
/// The data-fidelity impact is minimal: backslashes in indexed code are rare
/// (mostly C macros and Windows paths, both already normalized elsewhere),
/// double-quotes in signatures are typically decorative rather than
/// semantically significant, and newlines/tabs in indexed metadata fields
/// (signatures, docstrings, content snapshots) are not semantically loaded —
/// the structural line range is preserved in the dedicated `startLine` and
/// `endLine` columns. See `tools/verification/results/triage.md` §B6.
fn sanitize_for_ladybugdb(s: String) -> String {
    if !s.contains('\\')
        && !s.contains('"')
        && !s.contains('\n')
        && !s.contains('\r')
        && !s.contains('\t')
    {
        return s;
    }
    s.replace('\\', "/")
        .replace('"', "'")
        .replace(['\n', '\r', '\t'], " ")
}

/// Streams a node table CSV (header + one row per node) directly to `writer`,
/// avoiding the intermediate `String` allocation of the pre-L4 API (L4 of the
/// memory-overflow fix).
///
/// The header row contains the column names from [`node_table_columns`] for the
/// given `label`. Each subsequent row contains the field values extracted by
/// [`node_to_row`], sanitized via [`sanitize_for_ladybugdb`] to avoid the
/// LadybugDB COPY parser bug (B6). Uses tab-delimited format (see
/// [`CSV_DELIMITER`] for rationale).
///
/// The caller owns `writer`; this function flushes the `csv::Writer` buffer
/// before returning, so the underlying writer receives all bytes. Callers that
/// pass a `std::fs::File` should `drop`/`flush` it as needed.
///
/// # L6 memory-overflow fix
///
/// Accepts `impl IntoIterator<Item = &Node>` instead of `&[Node]` so callers
/// can stream from [`Graph::nodes_view`] without first collecting into a
/// `Vec<Node>`. For large repos (100k+ nodes), eliminating the intermediate
/// Vec avoids ~10 MB of peak RSS.
///
/// Deduplicates nodes by their `id` field (primary key in every node table) to
/// prevent primary-key conflicts during `COPY FROM`. Returns
/// [`NodeCsvStats`] so callers can log dedup counts (fail-loud principle,
/// mirroring [`write_edges_csv_stream`]'s behavior). Dedup is "first-wins"
/// (consistent with [`write_edges_csv_stream`]): the first node with a given
/// id is written, subsequent nodes with the same id are skipped.
///
/// [`Graph::nodes_view`]: crate::model::Graph::nodes_view
/// [`write_edges_csv_stream`]: self::write_edges_csv_stream
pub fn write_nodes_csv_stream<'a, W: Write, I>(
    nodes: I,
    label: NodeLabel,
    writer: W,
) -> Result<NodeCsvStats>
where
    I: IntoIterator<Item = &'a Node>,
{
    let columns = node_table_columns(label);
    let mut csv_writer = WriterBuilder::new()
        .delimiter(CSV_DELIMITER)
        .from_writer(writer);
    csv_writer.write_record(columns)?;
    // L6-3 perf fix: borrow node ids as `&'a str` instead of cloning each id
    // into a `HashSet<String>`. For 100k+ nodes this avoids ~5 MB of String
    // allocations. The `'a` lifetime is bound to the input iterator's `Node`
    // refs, so the borrows are valid for the entire dedup pass.
    let mut seen: std::collections::HashSet<&'a str> = std::collections::HashSet::new();
    let mut skipped = 0usize;
    let mut written = 0usize;
    let mut total = 0usize;
    for node in nodes {
        total += 1;
        if !seen.insert(node.id.as_str()) {
            skipped += 1;
            continue;
        }
        let row: Vec<String> = node_to_row(node, label)
            .into_iter()
            .map(sanitize_for_ladybugdb)
            .collect();
        csv_writer.write_record(&row)?;
        written += 1;
    }
    csv_writer.flush()?;
    Ok(NodeCsvStats {
        written,
        skipped_duplicates: skipped,
        total,
    })
}

/// Statistics from streaming a nodes CSV (L6-3 of the memory-overflow fix).
///
/// Returned by [`write_nodes_csv_stream`] so callers can log dedup metrics
/// (fail-loud principle) without inspecting the CSV content. Mirrors
/// [`EdgeCsvStats`] for symmetric API design.
///
/// # L6-3 architecture fix
///
/// Includes `total` field (mirrors [`EdgeCsvStats`]) so callers can compute
/// dedup rate in warnings.
///
/// [`EdgeCsvStats`]: self::EdgeCsvStats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct NodeCsvStats {
    /// Number of nodes written to the CSV (after dedup).
    pub written: usize,
    /// Number of duplicate nodes skipped during dedup.
    pub skipped_duplicates: usize,
    /// Total number of nodes seen by the streamer (written + skipped).
    pub total: usize,
}

/// Statistics from streaming an edges CSV (L4 of the memory-overflow fix).
///
/// Returned by [`write_edges_csv_stream`] so callers can log dedup metrics
/// (BR-INDEX-005, fail-loud principle) without inspecting the CSV content.
///
/// # L6-3 architecture fix
///
/// Added `total` field so callers can compute dedup rate (`skipped / total`)
/// in warnings. Restores the observability lost when `save_edges` switched
/// from `&[Edge]` (where `edges.len()` was available) to `impl IntoIterator`
/// (where the count must be accumulated during streaming).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct EdgeCsvStats {
    /// Number of edges written to the CSV (after dedup).
    pub written: usize,
    /// Number of duplicate edges skipped during dedup.
    pub skipped_duplicates: usize,
    /// Total number of edges seen by the streamer (written + skipped).
    pub total: usize,
}

/// Streams the `CodeRelation` CSV (header + one row per edge) directly to
/// `writer`, avoiding the intermediate `String` allocation of the pre-L4 API
/// (L4 of the memory-overflow fix).
///
/// Deduplicates edges by their primary-key id ([`edge_id`]) to prevent
/// primary-key conflicts during `COPY FROM`. Duplicate edges arise when
/// distinct call sites resolve to the same `{source, target, type, line}`
/// tuple (e.g. chained `.project(project)` calls in different files sharing
/// the same start line). Returns [`EdgeCsvStats`] so callers can log dedup
/// counts.
///
/// # L6 memory-overflow fix
///
/// Accepts `impl IntoIterator<Item = &Edge>` instead of `&[Edge]` so callers
/// can stream from [`Graph::edges_view`] without first collecting into a
/// `Vec<Edge>`. For large repos (100k+ edges), eliminating the intermediate
/// Vec avoids ~10 MB of peak RSS.
///
/// [`Graph::edges_view`]: crate::model::Graph::edges_view
pub fn write_edges_csv_stream<'a, W: Write, I>(edges: I, writer: W) -> Result<EdgeCsvStats>
where
    I: IntoIterator<Item = &'a Edge>,
{
    let columns = relation_table_columns();
    let mut csv_writer = WriterBuilder::new()
        .delimiter(CSV_DELIMITER)
        .from_writer(writer);
    csv_writer.write_record(columns)?;
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut skipped = 0usize;
    let mut written = 0usize;
    let mut total = 0usize;
    for edge in edges {
        total += 1;
        let id = edge_id(edge);
        if !seen.insert(id) {
            skipped += 1;
            continue;
        }
        let row: Vec<String> = edge_to_row(edge)
            .into_iter()
            .map(sanitize_for_ladybugdb)
            .collect();
        csv_writer.write_record(&row)?;
        written += 1;
    }
    csv_writer.flush()?;
    Ok(EdgeCsvStats {
        written,
        skipped_duplicates: skipped,
        total,
    })
}

/// Loads a CSV file into a table via LadybugDB's `COPY FROM` command.
///
/// The CSV file must have a header row whose column names match the target
/// table's columns. The `table` name is escaped via [`escape_identifier`] to
/// handle reserved keywords like `Macro`.
///
/// `PARALLEL=FALSE` is specified because LadybugDB's parallel CSV reader does
/// not support quoted fields containing embedded newlines (e.g. multi-line
/// function signatures produced by the Fortran extractor). The serial reader
/// handles RFC 4180-compliant quoted fields correctly.
///
/// `HEADER` is specified so LadybugDB skips the CSV header row. Without it,
/// the header row (e.g. `id,project,name,...`) is inserted as a data row,
/// producing phantom nodes whose fields are the column names (DQ-005).
///
/// `DELIM '\t'` specifies tab-delimited format. LadybugDB's COPY parser does
/// not correctly handle RFC 4180 quoted fields containing commas (e.g. Rust
/// generic types like `FallbackChain<T, U>`), so we use tab delimiters
/// instead (see [`CSV_DELIMITER`]).
pub fn load_from_csv(conn: &StorageConnection, table: &str, csv_path: &Path) -> Result<()> {
    let path_str = csv_path
        .to_str()
        .ok_or_else(|| StorageError::InvalidData(format!("non-utf8 csv path: {csv_path:?}")))?
        .replace('\\', "/");
    // Escape single quotes for safe interpolation into a Cypher string literal.
    // Paths are internally generated (not user-controlled), but this guards
    // against pathological paths containing quotes.
    let escaped_path = path_str.replace('\'', "''");
    let escaped_table = escape_identifier(table);
    let cypher = format!(
        "COPY {escaped_table} FROM '{escaped_path}' (HEADER, DELIM '\\t', PARALLEL=FALSE);"
    );
    conn.execute(&cypher)?;
    Ok(())
}

/// Extracts a string property from a node's `properties` JSON, returning an
/// empty string if absent.
fn prop_str(node: &Node, key: &str) -> String {
    node.properties
        .get(key)
        .and_then(|v| v.as_str())
        .map(String::from)
        .unwrap_or_default()
}

/// Extracts an integer property from a node's `properties` JSON, returning an
/// empty string if absent (LadybugDB COPY treats empty as NULL for INT types
/// when the column is nullable; for non-null INT columns the caller should
/// ensure a value is present).
fn prop_int(node: &Node, key: &str) -> String {
    node.properties
        .get(key)
        .and_then(|v| v.as_i64())
        .map(|i| i.to_string())
        .unwrap_or_default()
}

/// Converts an `Option<u32>` to a string (empty if `None`).
fn opt_line(n: Option<u32>) -> String {
    n.map(|v| v.to_string()).unwrap_or_default()
}

/// Converts an `Option<String>` to a string (empty if `None`).
fn opt_str(s: &Option<String>) -> String {
    s.clone().unwrap_or_default()
}

/// Converts an `Option<Language>` to its string representation.
fn opt_lang(lang: &Option<crate::model::Language>) -> String {
    lang.map(|l| l.to_string()).unwrap_or_default()
}

/// Builds the column-value vector for a node, in the order specified by
/// [`node_table_columns`].
#[must_use]
pub fn node_to_row(node: &Node, label: NodeLabel) -> Vec<String> {
    match label {
        NodeLabel::Project => vec![
            node.id.clone(),
            node.name.clone(),
            prop_str(node, "rootPath"),
            opt_lang(&node.language),
            prop_int(node, "fileCount"),
            prop_int(node, "indexedAt"),
            prop_str(node, "lastCommit"),
        ],
        NodeLabel::Folder => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            opt_str(&node.file_path),
        ],
        NodeLabel::File => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            opt_str(&node.file_path),
            opt_lang(&node.language),
            prop_str(node, "hash"),
            prop_int(node, "lineCount"),
        ],
        NodeLabel::Module | NodeLabel::Namespace => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Class
        | NodeLabel::Struct
        | NodeLabel::Enum
        | NodeLabel::Trait
        | NodeLabel::Interface => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            node.is_exported.to_string(),
            opt_str(&node.docstring),
            prop_str(node, "content"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Impl => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            prop_str(node, "implType"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Function => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            opt_str(&node.signature),
            opt_str(&node.return_type),
            node.is_exported.to_string(),
            opt_str(&node.docstring),
            prop_str(node, "content"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Method => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            opt_str(&node.signature),
            opt_str(&node.return_type),
            node.is_exported.to_string(),
            opt_str(&node.docstring),
            prop_str(node, "content"),
            prop_int(node, "parameterCount"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Variable => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            node.is_global.to_string(),
            opt_str(&node.return_type),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::GlobalVar => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_str(&node.return_type),
            node.is_exported.to_string(),
        ],
        NodeLabel::Parameter => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            prop_str(node, "paramType"),
            prop_int(node, "paramIndex"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Const => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            prop_str(node, "constType"),
            prop_str(node, "constValue"),
            node.is_exported.to_string(),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Static => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_str(&node.return_type),
            node.is_exported.to_string(),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Macro => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            opt_str(&node.signature),
            prop_str(node, "content"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::TypeAlias => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            prop_str(node, "aliasType"),
            node.is_exported.to_string(),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Typedef => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            prop_str(node, "typedefType"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Constructor | NodeLabel::Handler | NodeLabel::Middleware | NodeLabel::Test => {
            vec![
                node.id.clone(),
                node.project.clone(),
                node.name.clone(),
                node.qualified_name.clone(),
                opt_str(&node.file_path),
                opt_line(node.start_line),
                opt_line(node.end_line),
                opt_str(&node.signature),
                opt_str(&node.return_type),
                node.is_exported.to_string(),
                opt_str(&node.docstring),
                prop_str(node, "content"),
                opt_str(&node.parent_qn),
            ]
        }
        NodeLabel::Record | NodeLabel::Delegate | NodeLabel::Union | NodeLabel::Service => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            node.is_exported.to_string(),
            opt_str(&node.docstring),
            prop_str(node, "content"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Property | NodeLabel::Field => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            opt_str(&node.return_type),
            node.is_exported.to_string(),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Annotation | NodeLabel::Variant | NodeLabel::Event | NodeLabel::Section => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            opt_str(&node.docstring),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Template => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            prop_str(node, "templateParams"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Endpoint | NodeLabel::Route => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            opt_line(node.start_line),
            opt_line(node.end_line),
            prop_str(node, "httpMethod"),
            prop_str(node, "path"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Process | NodeLabel::Community => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.docstring),
        ],
        NodeLabel::Database => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            prop_str(node, "dbType"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Config => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            prop_str(node, "configType"),
            opt_str(&node.parent_qn),
        ],
        NodeLabel::Tool => vec![
            node.id.clone(),
            node.project.clone(),
            node.name.clone(),
            node.qualified_name.clone(),
            opt_str(&node.file_path),
            prop_str(node, "toolType"),
            opt_str(&node.parent_qn),
        ],
        // Embedding rows use the vector-store schema (id, nodeId, project,
        // chunkIndex, startLine, endLine, embedding, contentHash) per DDD §5.9.
        // In practice Embedding rows are inserted via the embed module's
        // dedicated path, not CSV batch load; this arm exists for exhaustiveness.
        NodeLabel::Embedding => vec![
            node.id.clone(),
            prop_str(node, "nodeId"),
            node.project.clone(),
            prop_int(node, "chunkIndex"),
            opt_line(node.start_line),
            opt_line(node.end_line),
            prop_str(node, "embedding"),
            prop_str(node, "contentHash"),
        ],
    }
}

/// Generates the primary-key id for an edge.
///
/// The id is `{source}_{target}_{type}_{start_line}`, with `start_line`
/// defaulting to 0 when `None`. Callers that batch-insert edges must dedup
/// by this id to avoid primary-key conflicts (ADR-014).
#[must_use]
pub fn edge_id(edge: &Edge) -> String {
    format!(
        "{}_{}_{}_{}",
        edge.source,
        edge.target,
        edge.edge_type.as_db_type(),
        edge.start_line.unwrap_or(0)
    )
}

/// Builds the column-value vector for an edge, in the order specified by
/// [`relation_table_columns`].
#[must_use]
pub fn edge_to_row(edge: &Edge) -> Vec<String> {
    let id = edge_id(edge);
    vec![
        id,
        edge.source.clone(),
        edge.target.clone(),
        edge.edge_type.as_db_type().to_string(),
        format!("{:.6}", edge.confidence),
        edge.confidence_tier.as_db_type().to_string(),
        opt_str(&edge.reason),
        opt_line(edge.start_line),
        edge.project.clone(),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{EdgeType, Language};

    fn sample_function_node() -> Node {
        Node::builder(NodeLabel::Function, "main", "proj.src.main")
            .id("func_001")
            .project("demo")
            .file_path("/src/main.rs")
            .start_line(10)
            .end_line(20)
            .language(Language::Rust)
            .signature("fn main() -> i32")
            .return_type("i32")
            .docstring("Entry point")
            .is_exported(true)
            .parent_qn("proj.src")
            .properties(serde_json::json!({"content": "fn main() { }"}))
            .build()
    }

    /// Test helper: streams nodes to an in-memory buffer and returns the CSV
    /// as a `String`. Replaces the pre-L4 `write_nodes_csv` in tests so they
    /// can assert on the produced CSV content without changing the production
    /// streaming API.
    fn write_nodes_csv_to_string(nodes: &[Node], label: NodeLabel) -> String {
        let mut buf = Vec::new();
        write_nodes_csv_stream(nodes, label, &mut buf).expect("stream write");
        String::from_utf8(buf).expect("csv utf8")
    }

    /// Test helper: streams edges to an in-memory buffer and returns the CSV
    /// as a `String`. Replaces the pre-L4 `write_edges_csv` in tests.
    fn write_edges_csv_to_string(edges: &[Edge]) -> String {
        let mut buf = Vec::new();
        write_edges_csv_stream(edges, &mut buf).expect("stream write");
        String::from_utf8(buf).expect("csv utf8")
    }

    /// Test helper: streams nodes to a temp file and returns the path. The
    /// caller owns the temp dir (leaked on purpose for the same process model
    /// as the pre-L4 `write_csv_temp`).
    fn write_nodes_csv_to_temp(
        nodes: &[Node],
        label: NodeLabel,
        file_name: &str,
    ) -> std::path::PathBuf {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(file_name);
        let file = std::fs::File::create(&path).expect("create temp file");
        write_nodes_csv_stream(nodes, label, file).expect("stream write");
        // Leak the tempdir so the file survives for the caller (matches the
        // lifetime model used in load_from_csv tests).
        std::mem::forget(dir);
        path
    }

    /// Test helper: streams edges to a temp file and returns the path.
    fn write_edges_csv_to_temp(edges: &[Edge], file_name: &str) -> std::path::PathBuf {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join(file_name);
        let file = std::fs::File::create(&path).expect("create temp file");
        write_edges_csv_stream(edges, file).expect("stream write");
        std::mem::forget(dir);
        path
    }

    #[test]
    fn write_nodes_csv_has_header_row() {
        let csv = write_nodes_csv_to_string(&[], NodeLabel::Function);
        let lines: Vec<&str> = csv.lines().collect();
        // CSV_DELIMITER is tab (LadybugDB COPY compatibility); header uses tabs.
        assert_eq!(
            lines[0],
            "id\tproject\tname\tqualifiedName\tfilePath\tstartLine\tendLine\tsignature\treturnType\tisExported\tdocstring\tcontent\tparentQn"
        );
    }

    #[test]
    fn write_nodes_csv_has_one_row_per_node() {
        let nodes = vec![sample_function_node()];
        let csv = write_nodes_csv_to_string(&nodes, NodeLabel::Function);
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 2, "expected header + 1 row");
    }

    #[test]
    fn write_nodes_csv_contains_correct_values() {
        let nodes = vec![sample_function_node()];
        let csv = write_nodes_csv_to_string(&nodes, NodeLabel::Function);
        let lines: Vec<&str> = csv.lines().collect();
        let row = lines[1];
        assert!(row.contains("func_001"));
        assert!(row.contains("demo"));
        assert!(row.contains("main"));
        assert!(row.contains("proj.src.main"));
        assert!(row.contains("/src/main.rs"));
        assert!(row.contains("fn main() -> i32"));
        assert!(row.contains("i32"));
        assert!(row.contains("Entry point"));
        assert!(row.contains("fn main() { }"));
    }

    #[test]
    fn write_nodes_csv_sanitizes_tabs_in_fields() {
        // B6 workaround: tabs are replaced with spaces by sanitize_for_ladybugdb
        // to prevent delimiter collision and forced quoting (LadybugDB COPY
        // cannot parse multi-line quoted fields that result from tab-quoted fields).
        let node = Node::builder(NodeLabel::Function, "foo\tbar", "qn")
            .id("id1")
            .project("p")
            .docstring("has\t tab")
            .build();
        let csv = write_nodes_csv_to_string(&[node], NodeLabel::Function);
        let lines: Vec<&str> = csv.lines().collect();
        // Tab replaced with space; field is NOT quoted.
        assert!(lines[1].contains("foo bar"));
        assert!(lines[1].contains("has  tab"));
        // No literal tab should remain in the data row (only as delimiter).
        // The data row has exactly 13 tab delimiters (14 columns) — verify no
        // extra tabs from field content by checking the quoted form is absent.
        assert!(!lines[1].contains("\"foo"));
    }

    #[test]
    fn write_nodes_csv_sanitizes_quotes_in_fields() {
        // B6 workaround: double-quotes are replaced with single-quotes before
        // CSV writing to avoid LadybugDB COPY parser corruption on Python
        // method signatures (subno.ts sample).
        let node = Node::builder(NodeLabel::Function, "foo\"bar", "qn")
            .id("id1")
            .project("p")
            .docstring("say \"hi\"")
            .build();
        let csv = write_nodes_csv_to_string(&[node], NodeLabel::Function);
        let lines: Vec<&str> = csv.lines().collect();
        // Quotes are sanitized to single-quotes (no RFC 4180 doubling needed)
        assert!(lines[1].contains("foo'bar"));
        assert!(lines[1].contains("say 'hi'"));
        // Ensure no doubled quotes remain (would indicate sanitize was bypassed)
        assert!(!lines[1].contains("\"\""));
    }

    #[test]
    fn write_nodes_csv_sanitizes_backslashes_for_ladybugdb() {
        // B6 workaround: backslashes are replaced with forward slashes before
        // CSV writing to avoid LadybugDB COPY parser treating them as C-style
        // escape chars (breaks C macro line continuations in redis sample).
        let node = Node::builder(NodeLabel::Macro, "MY_MACRO", "proj.MY_MACRO")
            .id("macro_1")
            .project("demo")
            .file_path("/src/macro.h")
            .start_line(1)
            .end_line(3)
            .signature("#define MY_MACRO(x) \\ continuation")
            .properties(serde_json::json!({"content": "#define MY_MACRO(x) \\ continuation"}))
            .build();
        let csv = write_nodes_csv_to_string(&[node], NodeLabel::Macro);
        // Backslash in signature/content replaced with forward slash
        assert!(csv.contains("MY_MACRO(x) / continuation"));
        // Ensure no raw backslash remains in the CSV data (sanitize was applied)
        assert!(!csv.contains('\\'));
    }

    #[test]
    fn write_nodes_csv_sanitizes_newlines_in_fields() {
        // B6 workaround: newlines are replaced with spaces by sanitize_for_ladybugdb
        // to prevent multi-line quoted fields (which LadybugDB COPY cannot parse).
        let node = Node::builder(NodeLabel::Function, "foo", "qn")
            .id("id1")
            .project("p")
            .docstring("line1\nline2")
            .build();
        let csv = write_nodes_csv_to_string(&[node], NodeLabel::Function);
        let lines: Vec<&str> = csv.lines().collect();
        // Newline replaced with space; field is NOT quoted (no quoting needed).
        assert!(lines[1].contains("line1 line2"));
        assert!(!lines[1].contains("\"line1"));
    }

    #[test]
    fn write_nodes_csv_for_project_label() {
        let node = Node::builder(NodeLabel::Project, "demo", "demo")
            .id("proj_001")
            .properties(serde_json::json!({
                "rootPath": "/repo/demo",
                "fileCount": 42,
                "indexedAt": 1700000000,
                "lastCommit": "abc123"
            }))
            .build();
        let csv = write_nodes_csv_to_string(&[node], NodeLabel::Project);
        let lines: Vec<&str> = csv.lines().collect();
        // CSV_DELIMITER is tab; Project header uses tabs.
        assert_eq!(
            lines[0],
            "id\tname\trootPath\tlanguage\tfileCount\tindexedAt\tlastCommit"
        );
        assert!(lines[1].contains("proj_001"));
        assert!(lines[1].contains("demo"));
        assert!(lines[1].contains("/repo/demo"));
        assert!(lines[1].contains("42"));
        assert!(lines[1].contains("1700000000"));
        assert!(lines[1].contains("abc123"));
    }

    #[test]
    fn write_nodes_csv_for_file_label() {
        let node = Node::builder(NodeLabel::File, "main.rs", "demo.src.main")
            .id("file_001")
            .project("demo")
            .file_path("/src/main.rs")
            .language(Language::Rust)
            .properties(serde_json::json!({"hash": "abc123", "lineCount": 100}))
            .build();
        let csv = write_nodes_csv_to_string(&[node], NodeLabel::File);
        let lines: Vec<&str> = csv.lines().collect();
        assert!(lines[1].contains("abc123"));
        assert!(lines[1].contains("100"));
        assert!(lines[1].contains("rust"));
    }

    #[test]
    fn write_nodes_csv_empty_input_returns_header_only() {
        let csv = write_nodes_csv_to_string(&[], NodeLabel::Class);
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 1);
        // CSV_DELIMITER is tab; header starts with "id\t".
        assert!(lines[0].starts_with("id\t"));
    }

    #[test]
    fn write_edges_csv_has_header_row() {
        let csv = write_edges_csv_to_string(&[]);
        let lines: Vec<&str> = csv.lines().collect();
        // CSV_DELIMITER is tab (LadybugDB COPY compatibility); header uses tabs.
        assert_eq!(
            lines[0],
            "id\tsource\ttarget\ttype\tconfidence\tconfidenceTier\treason\tstartLine\tproject"
        );
    }

    #[test]
    fn write_edges_csv_contains_correct_values() {
        let edge = Edge::builder("func_a", "func_b", EdgeType::Calls, "demo")
            .confidence(0.95)
            .reason("direct call")
            .start_line(15)
            .build();
        let csv = write_edges_csv_to_string(&[edge]);
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 2);
        assert!(lines[1].contains("func_a"));
        assert!(lines[1].contains("func_b"));
        assert!(lines[1].contains("CALLS"));
        assert!(lines[1].contains("0.950000"));
        assert!(lines[1].contains("direct call"));
        assert!(lines[1].contains("15"));
        assert!(lines[1].contains("demo"));
    }

    #[test]
    fn write_edges_csv_sanitizes_special_chars_in_reason() {
        // B6 workaround: newlines in edge reason fields are replaced with spaces
        // to prevent multi-line quoted fields (LadybugDB COPY cannot parse them).
        let edge = Edge::builder("s", "t", EdgeType::Calls, "p")
            .reason("arg, index=0\nnext line")
            .build();
        let csv = write_edges_csv_to_string(&[edge]);
        // Newline replaced with space; no quoting needed.
        assert!(csv.contains("arg, index=0 next line"));
        assert!(!csv.contains("\"arg"));
    }

    #[test]
    fn node_to_row_function_has_thirteen_columns() {
        let node = sample_function_node();
        let row = node_to_row(&node, NodeLabel::Function);
        assert_eq!(row.len(), 13);
        assert_eq!(row[0], "func_001");
        assert_eq!(row[1], "demo");
        assert_eq!(row[2], "main");
    }

    #[test]
    fn node_to_row_project_has_seven_columns() {
        let node = Node::builder(NodeLabel::Project, "p", "p")
            .id("p1")
            .properties(serde_json::json!({"rootPath": "/", "fileCount": 1, "indexedAt": 2, "lastCommit": "abc"}))
            .build();
        let row = node_to_row(&node, NodeLabel::Project);
        assert_eq!(row.len(), 7);
        assert_eq!(row[2], "/");
        assert_eq!(row[4], "1");
        assert_eq!(row[5], "2");
        assert_eq!(row[6], "abc");
    }

    #[test]
    fn node_to_row_method_has_fourteen_columns() {
        let node = Node::builder(NodeLabel::Method, "m", "qn")
            .id("m1")
            .project("p")
            .properties(serde_json::json!({"content": "x", "parameterCount": 3}))
            .build();
        let row = node_to_row(&node, NodeLabel::Method);
        assert_eq!(row.len(), 14);
        assert_eq!(row[12], "3");
    }

    #[test]
    fn edge_to_row_has_nine_columns() {
        let edge = Edge::new("s", "t", EdgeType::Calls, "p");
        let row = edge_to_row(&edge);
        assert_eq!(row.len(), 9);
        assert_eq!(row[1], "s");
        assert_eq!(row[2], "t");
        assert_eq!(row[3], "CALLS");
        assert_eq!(row[5], "GLOBAL");
    }

    #[test]
    fn load_from_csv_loads_nodes_into_table() {
        let dir = tempfile::tempdir().unwrap();
        let conn = StorageConnection::open(dir.path().join("testdb")).unwrap();
        std::mem::forget(dir);
        conn.init_schema().unwrap();

        let node = sample_function_node();
        let csv_path = write_nodes_csv_to_temp(&[node], NodeLabel::Function, "functions.csv");
        load_from_csv(&conn, "Function", &csv_path).expect("COPY failed");

        let rows = conn
            .query("MATCH (f:Function) RETURN f.name AS name;")
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0][0], serde_json::json!("main"));
    }

    #[test]
    fn load_from_csv_loads_edges_into_table() {
        let dir = tempfile::tempdir().unwrap();
        let conn = StorageConnection::open(dir.path().join("testdb")).unwrap();
        std::mem::forget(dir);
        conn.init_schema().unwrap();

        let edge = Edge::builder("s", "t", EdgeType::Calls, "demo")
            .confidence(0.9)
            .start_line(5)
            .build();
        let csv_path = write_edges_csv_to_temp(&[edge], "edges.csv");
        load_from_csv(&conn, "CodeRelation", &csv_path).expect("COPY failed");

        let rows = conn
            .query("MATCH (r:CodeRelation) RETURN r.type AS type;")
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0][0], serde_json::json!("CALLS"));
    }

    #[test]
    fn load_from_csv_handles_macro_table() {
        let dir = tempfile::tempdir().unwrap();
        let conn = StorageConnection::open(dir.path().join("testdb")).unwrap();
        std::mem::forget(dir);
        conn.init_schema().unwrap();

        let node = Node::builder(NodeLabel::Macro, "MY_MACRO", "demo.MY_MACRO")
            .id("macro_1")
            .project("demo")
            .start_line(1)
            .end_line(3)
            .signature("#define MY_MACRO(x) x+1")
            .properties(serde_json::json!({"content": "#define MY_MACRO(x) x+1"}))
            .build();
        let csv_path = write_nodes_csv_to_temp(&[node], NodeLabel::Macro, "macros.csv");
        load_from_csv(&conn, "Macro", &csv_path).expect("COPY Macro failed");

        let rows = conn
            .query("MATCH (m:`Macro`) RETURN m.name AS name;")
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0][0], serde_json::json!("MY_MACRO"));
    }

    #[test]
    fn csv_loader_new_returns_default() {
        let loader = CsvLoader::new();
        let _ = format!("{loader:?}");
    }

    #[test]
    fn edge_id_generates_correct_format() {
        let edge = Edge::builder("src", "tgt", EdgeType::Calls, "p")
            .start_line(42)
            .build();
        assert_eq!(edge_id(&edge), "src_tgt_CALLS_42");
    }

    #[test]
    fn edge_id_defaults_line_to_zero_when_none() {
        let edge = Edge::new("s", "t", EdgeType::Reads, "p");
        assert_eq!(edge_id(&edge), "s_t_READS_0");
    }

    #[test]
    fn write_edges_csv_deduplicates_by_edge_id() {
        // Two edges with the same {source, target, type, start_line} produce
        // the same primary-key id. Only the first should appear in the CSV.
        let edge1 = Edge::builder("a", "b", EdgeType::Calls, "p")
            .confidence(0.9)
            .start_line(10)
            .build();
        let edge2 = Edge::builder("a", "b", EdgeType::Calls, "p")
            .confidence(0.5) // different confidence, same id
            .start_line(10)
            .build();
        let edge3 = Edge::builder("a", "b", EdgeType::Calls, "p")
            .start_line(20) // different line -> different id
            .build();
        let csv = write_edges_csv_to_string(&[edge1, edge2, edge3]);
        let lines: Vec<&str> = csv.lines().collect();
        // 1 header + 2 unique data rows (edge1 and edge3; edge2 is dup of edge1)
        assert_eq!(lines.len(), 3);
        assert!(lines[1].contains("0.900000"));
        assert!(lines[2].contains("20"));
    }

    #[test]
    fn write_edges_csv_preserves_all_unique_edges() {
        let edges = vec![
            Edge::new("a", "b", EdgeType::Calls, "p"),
            Edge::new("b", "c", EdgeType::Calls, "p"),
            Edge::new("c", "d", EdgeType::Reads, "p"),
        ];
        let csv = write_edges_csv_to_string(&edges);
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 4); // header + 3 edges
    }

    #[test]
    fn node_to_row_folder_has_four_columns() {
        let node = Node::builder(NodeLabel::Folder, "src", "proj.src")
            .id("folder_1")
            .project("demo")
            .file_path("/src")
            .build();
        let row = node_to_row(&node, NodeLabel::Folder);
        assert_eq!(row.len(), 4);
        assert_eq!(row[0], "folder_1");
        assert_eq!(row[1], "demo");
        assert_eq!(row[2], "src");
        assert_eq!(row[3], "/src");
    }

    #[test]
    fn node_to_row_module_has_six_columns() {
        let node = Node::builder(NodeLabel::Module, "mymod", "proj.mymod")
            .id("mod_1")
            .project("demo")
            .file_path("/src/mod.rs")
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Module);
        assert_eq!(row.len(), 6);
        assert_eq!(row[3], "proj.mymod");
        assert_eq!(row[5], "proj");
    }

    #[test]
    fn node_to_row_namespace_has_six_columns() {
        let node = Node::builder(NodeLabel::Namespace, "ns", "proj.ns")
            .id("ns_1")
            .project("demo")
            .build();
        let row = node_to_row(&node, NodeLabel::Namespace);
        assert_eq!(row.len(), 6);
    }

    #[test]
    fn node_to_row_class_has_twelve_columns() {
        let node = Node::builder(NodeLabel::Class, "MyClass", "proj.MyClass")
            .id("cls_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(10)
            .is_exported(true)
            .docstring("A class")
            .properties(serde_json::json!({"content": "class body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Class);
        assert_eq!(row.len(), 11);
        assert_eq!(row[7], "true");
        assert_eq!(row[8], "A class");
        assert_eq!(row[9], "class body");
    }

    #[test]
    fn node_to_row_struct_has_twelve_columns() {
        let node = Node::builder(NodeLabel::Struct, "Point", "proj.Point")
            .id("struct_1")
            .project("demo")
            .start_line(1)
            .end_line(5)
            .build();
        let row = node_to_row(&node, NodeLabel::Struct);
        assert_eq!(row.len(), 11);
    }

    #[test]
    fn node_to_row_enum_has_twelve_columns() {
        let node = Node::builder(NodeLabel::Enum, "Color", "proj.Color")
            .id("enum_1")
            .project("demo")
            .build();
        let row = node_to_row(&node, NodeLabel::Enum);
        assert_eq!(row.len(), 11);
    }

    #[test]
    fn node_to_row_trait_has_twelve_columns() {
        let node = Node::builder(NodeLabel::Trait, "Drawable", "proj.Drawable")
            .id("trait_1")
            .project("demo")
            .build();
        let row = node_to_row(&node, NodeLabel::Trait);
        assert_eq!(row.len(), 11);
    }

    #[test]
    fn node_to_row_impl_has_nine_columns() {
        let node = Node::builder(NodeLabel::Impl, "impl Point", "proj.Point.impl")
            .id("impl_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(10)
            .properties(serde_json::json!({"implType": "inherent"}))
            .parent_qn("proj.Point")
            .build();
        let row = node_to_row(&node, NodeLabel::Impl);
        assert_eq!(row.len(), 9);
        assert_eq!(row[7], "inherent");
        assert_eq!(row[8], "proj.Point");
    }

    #[test]
    fn node_to_row_variable_has_nine_columns() {
        let node = Node::builder(NodeLabel::Variable, "x", "proj.x")
            .id("var_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(5)
            .is_global(false)
            .return_type("i32")
            .parent_qn("proj.main")
            .build();
        let row = node_to_row(&node, NodeLabel::Variable);
        assert_eq!(row.len(), 9);
        assert_eq!(row[6], "false");
        assert_eq!(row[7], "i32");
        assert_eq!(row[8], "proj.main");
    }

    #[test]
    fn node_to_row_globalvar_has_eight_columns() {
        let node = Node::builder(NodeLabel::GlobalVar, "PI", "proj.PI")
            .id("gvar_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .return_type("f64")
            .is_exported(true)
            .build();
        let row = node_to_row(&node, NodeLabel::GlobalVar);
        assert_eq!(row.len(), 8);
        assert_eq!(row[6], "f64");
        assert_eq!(row[7], "true");
    }

    #[test]
    fn node_to_row_parameter_has_nine_columns() {
        let node = Node::builder(NodeLabel::Parameter, "param0", "proj.foo.param0")
            .id("param_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(3)
            .properties(serde_json::json!({"paramType": "i32", "paramIndex": 0}))
            .parent_qn("proj.foo")
            .build();
        let row = node_to_row(&node, NodeLabel::Parameter);
        assert_eq!(row.len(), 9);
        assert_eq!(row[6], "i32");
        assert_eq!(row[7], "0");
    }

    #[test]
    fn node_to_row_const_has_nine_columns() {
        let node = Node::builder(NodeLabel::Const, "MAX", "proj.MAX")
            .id("const_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .properties(serde_json::json!({"constType": "i32", "constValue": "42"}))
            .is_exported(true)
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Const);
        assert_eq!(row.len(), 10);
        assert_eq!(row[6], "i32");
        assert_eq!(row[7], "42");
        assert_eq!(row[8], "true");
    }

    #[test]
    fn node_to_row_static_has_eight_columns() {
        let node = Node::builder(NodeLabel::Static, "COUNTER", "proj.COUNTER")
            .id("static_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .return_type("u32")
            .is_exported(false)
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Static);
        assert_eq!(row.len(), 9);
        assert_eq!(row[6], "u32");
        assert_eq!(row[7], "false");
    }

    #[test]
    fn node_to_row_typealias_has_eight_columns() {
        let node = Node::builder(NodeLabel::TypeAlias, "Id", "proj.Id")
            .id("alias_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .properties(serde_json::json!({"aliasType": "u32"}))
            .is_exported(true)
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::TypeAlias);
        assert_eq!(row.len(), 9);
        assert_eq!(row[6], "u32");
        assert_eq!(row[7], "true");
    }

    #[test]
    fn node_to_row_typedef_has_seven_columns() {
        let node = Node::builder(NodeLabel::Typedef, "MyType", "proj.MyType")
            .id("typedef_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .properties(serde_json::json!({"typedefType": "int"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Typedef);
        assert_eq!(row.len(), 8);
        assert_eq!(row[6], "int");
    }

    #[test]
    fn write_nodes_file_writes_csv_to_disk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nodes.csv");
        let node = sample_function_node();
        CsvLoader::new()
            .write_nodes_file(&[node], NodeLabel::Function, &path)
            .expect("write_nodes_file");
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("func_001"));
        assert!(content.contains("main"));
    }

    #[test]
    fn write_edges_file_writes_csv_to_disk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("edges.csv");
        let edge = Edge::builder("s", "t", EdgeType::Calls, "demo")
            .start_line(1)
            .build();
        CsvLoader::new()
            .write_edges_file(&[edge], &path)
            .expect("write_edges_file");
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("CALLS"));
        assert!(content.contains("demo"));
    }

    // --- node_to_row coverage for remaining NodeLabel variants ---

    #[test]
    fn node_to_row_constructor_has_thirteen_columns() {
        let node = Node::builder(NodeLabel::Constructor, "ctor", "proj.ctor")
            .id("ctor_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(5)
            .signature("fn ctor()")
            .return_type("Self")
            .is_exported(true)
            .docstring("ctor")
            .properties(serde_json::json!({"content": "body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Constructor);
        assert_eq!(row.len(), 13);
        assert_eq!(row[0], "ctor_1");
        assert_eq!(row[5], "1");
        assert_eq!(row[6], "5");
        assert_eq!(row[7], "fn ctor()");
        assert_eq!(row[8], "Self");
        assert_eq!(row[9], "true");
        assert_eq!(row[10], "ctor");
        assert_eq!(row[11], "body");
        assert_eq!(row[12], "proj");
    }

    #[test]
    fn node_to_row_handler_has_thirteen_columns() {
        let node = Node::builder(NodeLabel::Handler, "on_click", "proj.on_click")
            .id("h_1")
            .project("demo")
            .file_path("/src/ui.rs")
            .start_line(10)
            .end_line(20)
            .signature("fn on_click()")
            .return_type("void")
            .is_exported(false)
            .docstring("click handler")
            .properties(serde_json::json!({"content": "handler body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Handler);
        assert_eq!(row.len(), 13);
        assert_eq!(row[9], "false");
        assert_eq!(row[11], "handler body");
    }

    #[test]
    fn node_to_row_middleware_has_thirteen_columns() {
        let node = Node::builder(NodeLabel::Middleware, "auth", "proj.auth")
            .id("mw_1")
            .project("demo")
            .file_path("/src/mw.rs")
            .start_line(1)
            .end_line(10)
            .signature("fn auth()")
            .return_type("Response")
            .is_exported(true)
            .docstring("auth mw")
            .properties(serde_json::json!({"content": "mw body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Middleware);
        assert_eq!(row.len(), 13);
        assert_eq!(row[7], "fn auth()");
    }

    #[test]
    fn node_to_row_test_has_thirteen_columns() {
        let node = Node::builder(NodeLabel::Test, "test_foo", "proj.test_foo")
            .id("test_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(5)
            .signature("fn test_foo()")
            .return_type("()")
            .is_exported(false)
            .docstring("tests foo")
            .properties(serde_json::json!({"content": "assert!()"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Test);
        assert_eq!(row.len(), 13);
        assert_eq!(row[2], "test_foo");
    }

    #[test]
    fn node_to_row_record_has_ten_columns() {
        let node = Node::builder(NodeLabel::Record, "Rec", "proj.Rec")
            .id("rec_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(5)
            .is_exported(true)
            .docstring("a record")
            .properties(serde_json::json!({"content": "record body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Record);
        assert_eq!(row.len(), 11);
        assert_eq!(row[5], "1");
        assert_eq!(row[6], "5");
        assert_eq!(row[7], "true");
        assert_eq!(row[8], "a record");
        assert_eq!(row[9], "record body");
        assert_eq!(row[10], "proj");
    }

    #[test]
    fn node_to_row_delegate_has_ten_columns() {
        let node = Node::builder(NodeLabel::Delegate, "Action", "proj.Action")
            .id("del_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(3)
            .is_exported(false)
            .docstring("delegate")
            .properties(serde_json::json!({"content": "delegate body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Delegate);
        assert_eq!(row.len(), 11);
        assert_eq!(row[7], "false");
    }

    #[test]
    fn node_to_row_union_has_ten_columns() {
        let node = Node::builder(NodeLabel::Union, "U", "proj.U")
            .id("union_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(3)
            .is_exported(true)
            .docstring("a union")
            .properties(serde_json::json!({"content": "union body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Union);
        assert_eq!(row.len(), 11);
        assert_eq!(row[8], "a union");
    }

    #[test]
    fn node_to_row_service_has_ten_columns() {
        let node = Node::builder(NodeLabel::Service, "AuthService", "proj.AuthService")
            .id("svc_1")
            .project("demo")
            .file_path("/src/svc.rs")
            .start_line(1)
            .end_line(20)
            .is_exported(true)
            .docstring("auth service")
            .properties(serde_json::json!({"content": "service body"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Service);
        assert_eq!(row.len(), 11);
        assert_eq!(row[2], "AuthService");
    }

    #[test]
    fn node_to_row_property_has_nine_columns() {
        let node = Node::builder(NodeLabel::Property, "name", "proj.name")
            .id("prop_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(2)
            .return_type("String")
            .is_exported(true)
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Property);
        assert_eq!(row.len(), 10);
        assert_eq!(row[5], "1");
        assert_eq!(row[6], "2");
        assert_eq!(row[7], "String");
        assert_eq!(row[8], "true");
        assert_eq!(row[9], "proj");
    }

    #[test]
    fn node_to_row_field_has_nine_columns() {
        let node = Node::builder(NodeLabel::Field, "x", "proj.x")
            .id("field_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(1)
            .return_type("i32")
            .is_exported(false)
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Field);
        assert_eq!(row.len(), 10);
        assert_eq!(row[7], "i32");
        assert_eq!(row[8], "false");
    }

    #[test]
    fn node_to_row_annotation_has_eight_columns() {
        let node = Node::builder(NodeLabel::Annotation, "Deprecated", "proj.Deprecated")
            .id("ann_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(1)
            .docstring("deprecated")
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Annotation);
        assert_eq!(row.len(), 9);
        assert_eq!(row[5], "1");
        assert_eq!(row[6], "1");
        assert_eq!(row[7], "deprecated");
        assert_eq!(row[8], "proj");
    }

    #[test]
    fn node_to_row_variant_has_eight_columns() {
        let node = Node::builder(NodeLabel::Variant, "A", "proj.A")
            .id("var_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(1)
            .docstring("variant A")
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Variant);
        assert_eq!(row.len(), 9);
        assert_eq!(row[7], "variant A");
    }

    #[test]
    fn node_to_row_event_has_eight_columns() {
        let node = Node::builder(NodeLabel::Event, "OnClick", "proj.OnClick")
            .id("evt_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(1)
            .docstring("click event")
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Event);
        assert_eq!(row.len(), 9);
        assert_eq!(row[2], "OnClick");
    }

    #[test]
    fn node_to_row_section_has_eight_columns() {
        let node = Node::builder(NodeLabel::Section, "intro", "proj.intro")
            .id("sec_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(10)
            .docstring("intro section")
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Section);
        assert_eq!(row.len(), 9);
        assert_eq!(row[7], "intro section");
    }

    #[test]
    fn node_to_row_template_has_eight_columns() {
        let node = Node::builder(NodeLabel::Template, "T", "proj.T")
            .id("tpl_1")
            .project("demo")
            .file_path("/src/lib.rs")
            .start_line(1)
            .end_line(1)
            .properties(serde_json::json!({"templateParams": "<T: Clone>"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Template);
        assert_eq!(row.len(), 9);
        assert_eq!(row[5], "1");
        assert_eq!(row[6], "1");
        assert_eq!(row[7], "<T: Clone>");
        assert_eq!(row[8], "proj");
    }

    #[test]
    fn node_to_row_endpoint_has_nine_columns() {
        let node = Node::builder(NodeLabel::Endpoint, "create_user", "proj.create_user")
            .id("ep_1")
            .project("demo")
            .file_path("/src/api.rs")
            .start_line(1)
            .end_line(10)
            .properties(serde_json::json!({"httpMethod": "POST", "path": "/users"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Endpoint);
        assert_eq!(row.len(), 10);
        assert_eq!(row[5], "1");
        assert_eq!(row[6], "10");
        assert_eq!(row[7], "POST");
        assert_eq!(row[8], "/users");
        assert_eq!(row[9], "proj");
    }

    #[test]
    fn node_to_row_route_has_nine_columns() {
        let node = Node::builder(NodeLabel::Route, "list_users", "proj.list_users")
            .id("rt_1")
            .project("demo")
            .file_path("/src/api.rs")
            .start_line(1)
            .end_line(5)
            .properties(serde_json::json!({"httpMethod": "GET", "path": "/users"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Route);
        assert_eq!(row.len(), 10);
        assert_eq!(row[7], "GET");
        assert_eq!(row[8], "/users");
    }

    #[test]
    fn node_to_row_process_has_four_columns() {
        let node = Node::builder(NodeLabel::Process, "worker", "proj.worker")
            .id("proc_1")
            .project("demo")
            .docstring("background worker")
            .build();
        let row = node_to_row(&node, NodeLabel::Process);
        assert_eq!(row.len(), 5);
        assert_eq!(row[0], "proc_1");
        assert_eq!(row[1], "demo");
        assert_eq!(row[2], "worker");
        assert_eq!(row[3], "proj.worker");
        assert_eq!(row[4], "background worker");
    }

    #[test]
    fn node_to_row_community_has_four_columns() {
        let node = Node::builder(NodeLabel::Community, "cluster_a", "proj.cluster_a")
            .id("comm_1")
            .project("demo")
            .docstring("a community")
            .build();
        let row = node_to_row(&node, NodeLabel::Community);
        assert_eq!(row.len(), 5);
        assert_eq!(row[4], "a community");
    }

    #[test]
    fn node_to_row_database_has_six_columns() {
        let node = Node::builder(NodeLabel::Database, "main_db", "proj.main_db")
            .id("db_1")
            .project("demo")
            .file_path("/db/main")
            .properties(serde_json::json!({"dbType": "postgres"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Database);
        assert_eq!(row.len(), 7);
        assert_eq!(row[0], "db_1");
        assert_eq!(row[1], "demo");
        assert_eq!(row[2], "main_db");
        assert_eq!(row[3], "proj.main_db");
        assert_eq!(row[4], "/db/main");
        assert_eq!(row[5], "postgres");
        assert_eq!(row[6], "proj");
    }

    #[test]
    fn node_to_row_config_has_six_columns() {
        let node = Node::builder(NodeLabel::Config, "app_config", "proj.app_config")
            .id("cfg_1")
            .project("demo")
            .file_path("/config/app.toml")
            .properties(serde_json::json!({"configType": "toml"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Config);
        assert_eq!(row.len(), 7);
        assert_eq!(row[5], "toml");
        assert_eq!(row[6], "proj");
    }

    #[test]
    fn node_to_row_tool_has_six_columns() {
        let node = Node::builder(NodeLabel::Tool, "lint", "proj.lint")
            .id("tool_1")
            .project("demo")
            .file_path("/tools/lint")
            .properties(serde_json::json!({"toolType": "linter"}))
            .parent_qn("proj")
            .build();
        let row = node_to_row(&node, NodeLabel::Tool);
        assert_eq!(row.len(), 7);
        assert_eq!(row[5], "linter");
        assert_eq!(row[6], "proj");
    }

    #[test]
    fn node_to_row_embedding_has_eight_columns() {
        let node = Node::builder(NodeLabel::Embedding, "emb", "proj.emb")
            .id("emb_1")
            .project("demo")
            .start_line(1)
            .end_line(10)
            .properties(serde_json::json!({
                "nodeId": "func_1",
                "chunkIndex": 0,
                "embedding": "[0.1,0.2]",
                "contentHash": "abc123"
            }))
            .build();
        let row = node_to_row(&node, NodeLabel::Embedding);
        assert_eq!(row.len(), 8);
        assert_eq!(row[0], "emb_1");
        assert_eq!(row[1], "func_1");
        assert_eq!(row[2], "demo");
        assert_eq!(row[3], "0");
        assert_eq!(row[4], "1");
        assert_eq!(row[5], "10");
        assert_eq!(row[6], "[0.1,0.2]");
        assert_eq!(row[7], "abc123");
    }

    // --- L4 streaming API tests ---

    #[test]
    fn write_nodes_csv_stream_writes_header_and_rows_to_vec() {
        let nodes = vec![sample_function_node()];
        let mut buf = Vec::new();
        write_nodes_csv_stream(&nodes, NodeLabel::Function, &mut buf).expect("stream");
        let csv = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 2, "header + 1 row");
        assert!(lines[1].contains("func_001"));
        assert!(lines[1].contains("demo"));
    }

    #[test]
    fn write_nodes_csv_stream_empty_input_writes_header_only() {
        let mut buf = Vec::new();
        write_nodes_csv_stream(&[], NodeLabel::Class, &mut buf).expect("stream");
        let csv = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 1, "header only");
        assert!(lines[0].starts_with("id\t"));
    }

    #[test]
    fn write_nodes_csv_stream_propagates_writer_error() {
        // A writer that always fails: write_record should return Err.
        use std::io::{self, Write};
        struct FailingWriter;
        impl Write for FailingWriter {
            fn write(&mut self, _: &[u8]) -> io::Result<usize> {
                Err(io::Error::other("write failed"))
            }
            fn flush(&mut self) -> io::Result<()> {
                Err(io::Error::other("flush failed"))
            }
        }
        let result = write_nodes_csv_stream(&[], NodeLabel::Function, FailingWriter);
        assert!(result.is_err(), "writer error must propagate");
    }

    #[test]
    fn write_edges_csv_stream_returns_stats_with_zero_skipped_when_no_dups() {
        let edges = vec![
            Edge::builder("a", "b", EdgeType::Calls, "p")
                .start_line(1)
                .build(),
            Edge::builder("b", "c", EdgeType::Calls, "p")
                .start_line(2)
                .build(),
        ];
        let mut buf = Vec::new();
        let stats = write_edges_csv_stream(&edges, &mut buf).expect("stream");
        assert_eq!(stats.written, 2);
        assert_eq!(stats.skipped_duplicates, 0);
        // L6-3: total mirrors written + skipped_duplicates.
        assert_eq!(stats.total, 2);
    }

    #[test]
    fn write_edges_csv_stream_returns_stats_with_correct_dedup_count() {
        let edge1 = Edge::builder("a", "b", EdgeType::Calls, "p")
            .confidence(0.9)
            .start_line(10)
            .build();
        let edge2 = Edge::builder("a", "b", EdgeType::Calls, "p")
            .confidence(0.5) // different confidence, same id
            .start_line(10)
            .build();
        let edge3 = Edge::builder("a", "b", EdgeType::Calls, "p")
            .start_line(20) // different line → different id
            .build();
        let mut buf = Vec::new();
        let stats = write_edges_csv_stream(&[edge1, edge2, edge3], &mut buf).expect("stream");
        assert_eq!(stats.written, 2, "edge1 + edge3");
        assert_eq!(stats.skipped_duplicates, 1, "edge2 is dup of edge1");
        // L6-3: total counts every edge seen (2 written + 1 dup).
        assert_eq!(stats.total, 3);
        // Verify the CSV content also matches the stats.
        let csv = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 3, "header + 2 unique rows");
    }

    #[test]
    fn edge_csv_stats_default_is_zero_zero_zero() {
        // L6-3: `total` field added — default must be 0 for all three counters.
        let stats = EdgeCsvStats::default();
        assert_eq!(stats.written, 0);
        assert_eq!(stats.skipped_duplicates, 0);
        assert_eq!(stats.total, 0);
    }

    #[test]
    fn edge_csv_stats_is_send_sync_copy() {
        fn _assert_send_sync<T: Send + Sync + Copy>() {}
        _assert_send_sync::<EdgeCsvStats>();
    }

    #[test]
    fn edge_csv_stats_equality_and_debug() {
        // L6-3: `total` mirrors `written + skipped_duplicates`. Construct with
        // all three fields and verify equality + Debug output includes `total`.
        let a = EdgeCsvStats {
            written: 5,
            skipped_duplicates: 2,
            total: 7,
        };
        let b = a;
        assert_eq!(a, b);
        let debug = format!("{a:?}");
        assert!(debug.contains("EdgeCsvStats"));
        assert!(debug.contains("written"));
        assert!(debug.contains("skipped_duplicates"));
        assert!(debug.contains("total"));
    }

    #[test]
    fn write_edges_csv_stream_empty_input_writes_header_only() {
        let mut buf = Vec::new();
        let stats = write_edges_csv_stream(&[], &mut buf).expect("stream");
        assert_eq!(stats.written, 0);
        assert_eq!(stats.skipped_duplicates, 0);
        // L6-3: `total` counts every edge seen by the streamer, even on empty
        // input (must be 0, not unset).
        assert_eq!(stats.total, 0);
        let csv = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 1, "header only");
    }

    // --- L6-3 memory-overflow fix: write_nodes_csv_stream iterator API ---

    #[test]
    fn write_nodes_csv_stream_accepts_iterator_of_node_refs() {
        // L6-3: write_nodes_csv_stream now accepts `impl IntoIterator<Item = &Node>`
        // so callers can stream from `Graph::nodes_view()` without first collecting
        // into a `Vec<Node>`. Verify by passing a direct iterator over node refs.
        let nodes = [
            sample_function_node(),
            Node::builder(NodeLabel::Function, "helper", "proj.helper")
                .id("func_002")
                .project("demo")
                .build(),
        ];
        let mut buf = Vec::new();
        let stats =
            write_nodes_csv_stream(nodes.iter(), NodeLabel::Function, &mut buf).expect("stream");
        assert_eq!(stats.written, 2);
        assert_eq!(stats.skipped_duplicates, 0);
        // L6-3: total mirrors written + skipped_duplicates.
        assert_eq!(stats.total, 2);
        let csv = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 3, "header + 2 rows");
        assert!(lines[1].contains("func_001"));
        assert!(lines[2].contains("func_002"));
    }

    #[test]
    fn write_nodes_csv_stream_deduplicates_by_node_id() {
        // L6-3: dedup is now performed inside write_nodes_csv_stream (HashSet by
        // node id), mirroring write_edges_csv_stream's behavior. Two nodes with
        // the same id produce only one CSV row; the duplicate is counted in
        // skipped_duplicates. This lets save_nodes_by_label skip the
        // `deduped: Vec<Node>` clone entirely.
        let n1 = Node::builder(NodeLabel::Function, "main", "proj.main")
            .id("dup_id")
            .project("demo")
            .signature("fn main() -> i32")
            .build();
        let n2 = Node::builder(NodeLabel::Function, "main", "proj.main")
            .id("dup_id") // same id, different signature (last-write-wins input)
            .project("demo")
            .signature("fn main() -> u64")
            .build();
        let n3 = Node::builder(NodeLabel::Function, "helper", "proj.helper")
            .id("unique_id")
            .project("demo")
            .build();
        let mut buf = Vec::new();
        let stats =
            write_nodes_csv_stream([&n1, &n2, &n3], NodeLabel::Function, &mut buf).expect("stream");
        assert_eq!(stats.written, 2, "n1 + n3; n2 is dup of n1");
        assert_eq!(stats.skipped_duplicates, 1);
        // L6-3: total counts every node seen by the streamer (2 written + 1 dup).
        assert_eq!(stats.total, 3);
        let csv = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 3, "header + 2 unique rows");
        // first-wins semantics (consistent with write_edges_csv_stream)
        assert!(lines[1].contains("fn main() -> i32"));
        assert!(!csv.contains("fn main() -> u64"));
    }

    #[test]
    fn node_csv_stats_default_is_zero_zero_zero() {
        // L6-3: `total` field added — default must be 0 for all three counters.
        let stats = NodeCsvStats::default();
        assert_eq!(stats.written, 0);
        assert_eq!(stats.skipped_duplicates, 0);
        assert_eq!(stats.total, 0);
    }

    #[test]
    fn node_csv_stats_is_send_sync_copy() {
        fn _assert_send_sync<T: Send + Sync + Copy>() {}
        _assert_send_sync::<NodeCsvStats>();
    }

    #[test]
    fn node_csv_stats_equality_and_debug() {
        // L6-3: `total` mirrors `written + skipped_duplicates`. Construct with
        // all three fields and verify equality + Debug output includes `total`.
        let a = NodeCsvStats {
            written: 5,
            skipped_duplicates: 2,
            total: 7,
        };
        let b = a;
        assert_eq!(a, b);
        let debug = format!("{a:?}");
        assert!(debug.contains("NodeCsvStats"));
        assert!(debug.contains("written"));
        assert!(debug.contains("skipped_duplicates"));
        assert!(debug.contains("total"));
    }
}