splice 2.6.3

Span-safe refactoring kernel for 7 languages with Magellan code graph integration
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
//! CLI output format and exit code tests.

use std::path::PathBuf;

#[test]
fn test_output_format_enum_exists() {
    // Verify OutputFormat enum variants exist
    // This is a compile-time check - if it compiles, the types exist
    use splice::cli::OutputFormat;

    let _human = OutputFormat::Human;
    let _json = OutputFormat::Json;
    let _pretty = OutputFormat::Pretty;

    // Verify is_json() method
    assert!(!OutputFormat::Human.is_json());
    assert!(OutputFormat::Json.is_json());
    assert!(OutputFormat::Pretty.is_json());
}

#[test]
fn test_call_direction_enum_exists() {
    use splice::cli::CallDirection;

    let _in = CallDirection::In;
    let _out = CallDirection::Out;
    let _both = CallDirection::Both;
}

#[test]
fn test_splice_exit_code_values() {
    // Verify exit code values match Magellan conventions
    // Note: SpliceExitCode is defined in main.rs, not re-exported
    // We verify the values match Magellan conventions (0-5)
    let success: u8 = 0;
    let error: u8 = 1;
    let usage: u8 = 2;
    let database: u8 = 3;
    let file_not_found: u8 = 4;
    let validation: u8 = 5;

    // These are the expected Magellan exit codes
    assert_eq!(success, 0);
    assert_eq!(error, 1);
    assert_eq!(usage, 2);
    assert_eq!(database, 3);
    assert_eq!(file_not_found, 4);
    assert_eq!(validation, 5);
}

#[test]
fn test_response_types_serialize() {
    use splice::output::{
        FilesResponse, FindResponse, MagellanSymbol, RefsResponse, StatusResponse,
    };

    // Test StatusResponse
    let status = StatusResponse {
        files: 10,
        symbols: 100,
        references: 50,
        calls: 25,
        code_chunks: 75,
        db_path: "/path/to/db".to_string(),
    };
    let json = serde_json::to_string(&status).unwrap();
    assert!(json.contains(r#""files":10"#));
    assert!(json.contains(r#""symbols":100"#));

    // Test FindResponse
    let find = FindResponse {
        symbols: vec![MagellanSymbol {
            symbol_id: Some("abc123".to_string()),
            id_format: Some("v1".to_string()),
            name: "test_fn".to_string(),
            kind: "fn".to_string(),
            file_path: "/path/to/file.rs".to_string(),
            byte_start: 0,
            byte_end: 100,
            start_line: 1,
            end_line: 5,
            start_col: 0,
            end_col: 4,
        }],
        count: 1,
    };
    let json = serde_json::to_string(&find).unwrap();
    assert!(json.contains(r#""start_line":1"#)); // Magellan field name
    assert!(json.contains(r#""end_line":5"#));

    // Test RefsResponse
    // Note: callers and callees use skip_serializing_if, so empty vectors are omitted
    let refs = RefsResponse {
        symbol: MagellanSymbol {
            symbol_id: None,
            id_format: None,
            name: "main".to_string(),
            kind: "fn".to_string(),
            file_path: "/path/to/main.rs".to_string(),
            byte_start: 0,
            byte_end: 50,
            start_line: 1,
            end_line: 3,
            start_col: 0,
            end_col: 2,
        },
        callers: vec![],
        callees: vec![],
    };
    let json = serde_json::to_string(&refs).unwrap();
    assert!(json.contains(r#""symbol":"#));
    // Empty vectors are skipped due to skip_serializing_if attribute
    assert!(!json.contains(r#""callers""#));

    // Test FilesResponse
    let files = FilesResponse {
        files: vec![],
        count: 0,
    };
    let json = serde_json::to_string(&files).unwrap();
    assert!(json.contains(r#""count":0"#));
}

#[test]
fn test_magellan_symbol_field_names() {
    use serde_json::Value;
    use splice::output::MagellanSymbol;

    let symbol = MagellanSymbol {
        symbol_id: Some("test_id".to_string()),
        id_format: Some("v2".to_string()),
        name: "test".to_string(),
        kind: "fn".to_string(),
        file_path: "/path/to/test.rs".to_string(),
        byte_start: 0,
        byte_end: 100,
        start_line: 5,
        end_line: 10,
        start_col: 2,
        end_col: 6,
    };

    let json = serde_json::to_string(&symbol).unwrap();
    let value: Value = serde_json::from_str(&json).unwrap();

    // Verify Magellan field names (NOT Splice names)
    assert!(value.get("start_line").is_some());
    assert!(value.get("end_line").is_some());
    assert!(value.get("start_col").is_some());
    assert!(value.get("end_col").is_some());

    // Verify Splice field names are NOT present
    assert!(value.get("line_start").is_none());
    assert!(value.get("line_end").is_none());
    assert!(value.get("col_start").is_none());
    assert!(value.get("col_end").is_none());
}

#[test]
fn test_response_types_reexported() {
    // Verify response types are accessible via splice::cli::
    // This is a compile-time check
    use splice::cli::{FindResponse, StatusResponse};

    // Just verify types exist
    let _status: StatusResponse = StatusResponse {
        files: 0,
        symbols: 0,
        references: 0,
        calls: 0,
        code_chunks: 0,
        db_path: String::new(),
    };

    let _find: FindResponse = FindResponse {
        symbols: vec![],
        count: 0,
    };

    // Types compile successfully
    assert_eq!(_status.files, 0);
    assert_eq!(_find.count, 0);
}

#[test]
fn test_help_text_includes_categories() {
    // Note: This test checks that the help text categories are defined
    // in the source code, not by running the binary (which would require subprocess)
    // The categories are verified at compile time by the long_about attribute

    // Verify OutputFormat parsing works
    use splice::cli::OutputFormat;

    // Human format should not be JSON
    assert!(!OutputFormat::Human.is_json());

    // Json and Pretty should both be JSON formats
    assert!(OutputFormat::Json.is_json());
    assert!(OutputFormat::Pretty.is_json());

    // Verify we can format JSON with each format
    let test_data = serde_json::json!({"test": "data"});

    assert!(OutputFormat::Json.format_json(&test_data).is_ok());
    assert!(OutputFormat::Pretty.format_json(&test_data).is_ok());
    assert!(OutputFormat::Human.format_json(&test_data).is_err());
}

#[test]
fn test_status_command_requires_db_flag() {
    // Test that the Status command struct requires db field
    // This is a compile-time check - if it compiles, the field exists
    use splice::cli::Commands;

    // We can't run the CLI without a database, but we can verify
    // the struct requires the db field by construction
    let _status_variant = Commands::Status {
        db: PathBuf::from("/tmp/test.db"),
        detect_backend: false,
    };

    // If we reached here, the Status command has the required db field
    assert!(true);
}

#[test]
fn test_find_command_requires_name_or_symbol_id() {
    // Test Find command has name and symbol_id fields with conflicts_with
    use splice::cli::Commands;

    // Valid Find with name
    let _find_with_name = Commands::Find {
        db: PathBuf::from("/tmp/test.db"),
        name: Some("test".to_string()),
        symbol_id: None,
        ambiguous: false,
        output: splice::cli::OutputFormat::Human,
    };

    // Valid Find with symbol_id
    let _find_with_id = Commands::Find {
        db: PathBuf::from("/tmp/test.db"),
        name: None,
        symbol_id: Some("abc123".to_string()),
        ambiguous: false,
        output: splice::cli::OutputFormat::Human,
    };

    // Both are valid at the struct level (clap handles conflicts_with at parse time)
    assert!(true);
}

#[test]
fn test_files_command_requires_db_flag() {
    // Test that the Files command struct requires db field
    use splice::cli::Commands;

    let _files_variant = Commands::Files {
        db: PathBuf::from("/tmp/test.db"),
        symbols: false,
        output: splice::cli::OutputFormat::Human,
    };

    // If we reached here, the Files command has the required db field
    assert!(true);
}

#[test]
fn test_output_format_flag_accepted() {
    // Test that OutputFormat enum has all three variants
    use splice::cli::OutputFormat;

    // Verify all three format variants exist and can be constructed
    let _human = OutputFormat::Human;
    let _json = OutputFormat::Json;
    let _pretty = OutputFormat::Pretty;

    // Verify we can convert to string if needed for clap parsing
    // (clap derives ValueEnum which provides to_possible_value())
    assert!(true);
}

#[test]
fn test_call_direction_enum_parsing() {
    use splice::cli::CallDirection;

    // Verify we can construct all direction variants
    let in_dir = CallDirection::In;
    let _out_dir = CallDirection::Out;
    let _both_dir = CallDirection::Both;

    // Verify PartialEq works
    assert_eq!(CallDirection::In, CallDirection::In);
    assert_ne!(CallDirection::In, CallDirection::Out);

    // Verify Copy trait works
    let in_copy = in_dir;
    assert_eq!(in_dir, in_copy);
}

#[test]
fn test_refs_command_has_direction_field() {
    // Test Refs command has direction field
    use splice::cli::{CallDirection, Commands, OutputFormat};

    let _refs_variant = Commands::Refs {
        db: PathBuf::from("/tmp/test.db"),
        name: "test".to_string(),
        path: PathBuf::from("/tmp/test.rs"),
        direction: CallDirection::Both,
        output: OutputFormat::Human,
        impact_graph: false,
    };

    // If we reached here, the Refs command has all required fields
    assert!(true);
}

#[test]
fn test_magellan_span_field_names() {
    use serde_json::Value;
    use splice::output::MagellanSpan;

    let span = MagellanSpan {
        file_path: "/path/to/file.rs".to_string(),
        byte_start: 0,
        byte_end: 100,
        start_line: 5,
        start_col: 2,
        end_line: 10,
        end_col: 6,
    };

    let json = serde_json::to_string(&span).unwrap();
    let value: Value = serde_json::from_str(&json).unwrap();

    // Verify Magellan field names (NOT Splice names)
    assert!(value.get("start_line").is_some());
    assert!(value.get("end_line").is_some());
    assert!(value.get("start_col").is_some());
    assert!(value.get("end_col").is_some());
}

#[test]
fn test_magellan_call_reference_serialization() {
    use splice::output::{MagellanCallReference, MagellanSpan, MagellanSymbol};

    let call_ref = MagellanCallReference {
        symbol: MagellanSymbol {
            symbol_id: Some("abc123".to_string()),
            id_format: Some("v1".to_string()),
            name: "callee".to_string(),
            kind: "fn".to_string(),
            file_path: "/path/to/callee.rs".to_string(),
            byte_start: 0,
            byte_end: 50,
            start_line: 1,
            end_line: 5,
            start_col: 0,
            end_col: 2,
        },
        call_site: MagellanSpan {
            file_path: "/path/to/caller.rs".to_string(),
            byte_start: 100,
            byte_end: 105,
            start_line: 10,
            start_col: 5,
            end_line: 10,
            end_col: 10,
        },
    };

    let json = serde_json::to_string(&call_ref).unwrap();
    let value: serde_json::Value = serde_json::from_str(&json).unwrap();

    // Verify structure
    assert!(value.get("symbol").is_some());
    assert!(value.get("call_site").is_some());

    // Verify Magellan field names in nested structures
    let call_site = value.get("call_site").unwrap();
    assert!(call_site.get("start_line").is_some());
    assert!(call_site.get("end_line").is_some());
}

#[test]
fn test_magellan_file_metadata_serialization() {
    use splice::output::MagellanFileMetadata;

    let metadata = MagellanFileMetadata {
        path: "/path/to/file.rs".to_string(),
        hash: "abc123".to_string(),
        last_indexed_at: 1234567890,
        last_modified: 1234567890,
        symbol_count: Some(42),
    };

    let json = serde_json::to_string(&metadata).unwrap();
    let value: serde_json::Value = serde_json::from_str(&json).unwrap();

    // Verify all fields serialize correctly
    assert_eq!(
        value.get("path").unwrap().as_str(),
        Some("/path/to/file.rs")
    );
    assert_eq!(value.get("hash").unwrap().as_str(), Some("abc123"));
    assert_eq!(value.get("symbol_count").unwrap().as_u64(), Some(42));
}

#[test]
fn test_status_response_serialization() {
    use splice::output::StatusResponse;

    let status = StatusResponse {
        files: 100,
        symbols: 1000,
        references: 500,
        calls: 250,
        code_chunks: 750,
        db_path: "/tmp/magellan.db".to_string(),
    };

    let json = serde_json::to_string(&status).unwrap();
    let value: serde_json::Value = serde_json::from_str(&json).unwrap();

    // Verify all fields serialize correctly
    assert_eq!(value.get("files").unwrap().as_u64(), Some(100));
    assert_eq!(value.get("symbols").unwrap().as_u64(), Some(1000));
    assert_eq!(value.get("references").unwrap().as_u64(), Some(500));
    assert_eq!(value.get("calls").unwrap().as_u64(), Some(250));
    assert_eq!(value.get("code_chunks").unwrap().as_u64(), Some(750));
    assert_eq!(
        value.get("db_path").unwrap().as_str(),
        Some("/tmp/magellan.db")
    );
}

// ============================================================================
// Export command tests (Phase 25-04)
// ============================================================================

#[cfg(test)]
mod export_tests {
    use serde_json::Value;
    use splice::graph::magellan_integration::MagellanIntegration;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;
    use std::process::Command;
    use tempfile::TempDir;

    /// Get the path to the splice binary.
    fn get_splice_binary() -> PathBuf {
        if let Ok(path) = std::env::var("SPLICE_TEST_BIN") {
            return PathBuf::from(path);
        }

        if let Ok(path) = std::env::var("CARGO_BIN_EXE_splice") {
            return PathBuf::from(path);
        }

        let mut path = std::env::current_exe().unwrap();
        path.pop(); // deps
        let deps_dir = path.clone();
        path.pop(); // debug
        let bin_path = path.join("splice");

        if bin_path.exists() {
            return bin_path;
        }

        if let Ok(entries) = std::fs::read_dir(deps_dir) {
            let mut candidates: Vec<(std::time::SystemTime, PathBuf)> = Vec::new();

            for entry in entries.flatten() {
                let path = entry.path();
                let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");

                if !name.starts_with("splice-") || !path.is_file() {
                    continue;
                }

                if let Ok(metadata) = entry.metadata() {
                    #[cfg(unix)]
                    let is_executable = metadata.permissions().mode() & 0o111 != 0;
                    #[cfg(not(unix))]
                    let is_executable = true;

                    if !is_executable {
                        continue;
                    }

                    if let Ok(modified) = metadata.modified() {
                        let len = metadata.len();
                        if len > 50_000_000 {
                            candidates.push((modified, path));
                        }
                    }
                }
            }

            if let Some((_, path)) = candidates.into_iter().max_by_key(|(time, _)| *time) {
                return path;
            }
        }

        bin_path
    }

    /// Extract JSON from stdout that may contain debug output lines.
    fn extract_json_from_stdout(stdout: &str) -> String {
        let start = stdout.find('{');
        let end = stdout.rfind('}');

        match (start, end) {
            (Some(start), Some(end)) if end >= start => stdout[start..=end].to_string(),
            _ => String::new(),
        }
    }

    #[test]
    fn test_export_json_format() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export.json");

        // Create a test file and index it
        let test_file = temp_dir.path().join("test.rs");
        std::fs::write(&test_file, "fn test() { println!(\"hello\"); }").unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&test_file).unwrap();

        // Run export command
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("json")
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok(), "export command should succeed");
        let output = result.unwrap();
        if !output.status.success() {
            eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        }
        assert!(output.status.success(), "export should return success");

        // Verify output file exists and contains valid JSON
        let json_content = std::fs::read_to_string(&output_path).unwrap();
        let value: Value =
            serde_json::from_str(&json_content).expect("export should produce valid JSON");

        // Check required fields
        assert!(
            value.get("schema_version").is_some(),
            "should have schema_version"
        );
        assert!(value.get("timestamp").is_some(), "should have timestamp");
        assert!(value.get("db_path").is_some(), "should have db_path");
        assert!(value.get("data").is_some(), "should have data");

        // Check data structure
        let data = &value["data"];
        assert!(data.get("files").is_some(), "data should have files array");
        assert!(
            data.get("symbols").is_some(),
            "data should have symbols array"
        );
        assert!(
            data.get("references").is_some(),
            "data should have references array"
        );
        assert!(data.get("calls").is_some(), "data should have calls array");
    }

    #[test]
    fn test_export_jsonl_format() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export.jsonl");

        // Create a test file and index it
        let test_file = temp_dir.path().join("test.rs");
        std::fs::write(&test_file, "fn test() {}").unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&test_file).unwrap();

        // Run export command
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("jsonl")
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.status.success());

        // Verify JSONL format (one JSON object per line)
        let jsonl_content = std::fs::read_to_string(&output_path).unwrap();
        for line in jsonl_content.lines() {
            let value: Value = serde_json::from_str(line).expect("each line should be valid JSON");
            // Check for type tag in data records
            if let Some(obj) = value.as_object() {
                if obj.get("type").is_some() {
                    let record_type = obj["type"].as_str().unwrap();
                    assert!(
                        record_type == "header" || record_type == "file" || record_type == "symbol",
                        "type should be header, file, or symbol"
                    );
                }
            }
        }
    }

    #[test]
    fn test_export_csv_format() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export.csv");

        // Create a test file and index it
        let test_file = temp_dir.path().join("test.rs");
        std::fs::write(&test_file, "fn test() {}").unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&test_file).unwrap();

        // Run export command
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("csv")
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.status.success());

        // Verify CSV format
        let csv_content = std::fs::read_to_string(&output_path).unwrap();
        // CSV should have section headers
        assert!(
            csv_content.contains("# Files"),
            "CSV should have Files section"
        );
        assert!(
            csv_content.contains("# Symbols"),
            "CSV should have Symbols section"
        );
        // CSV should have column headers
        assert!(csv_content.contains("path"), "CSV should have path column");
        assert!(csv_content.contains("hash"), "CSV should have hash column");
    }

    #[test]
    fn test_export_defaults_to_json() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export_default.json");

        // Create and index a test file
        let test_file = temp_dir.path().join("test.rs");
        std::fs::write(&test_file, "fn test() {}").unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&test_file).unwrap();

        // Run export without --format flag (should default to json)
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.status.success());

        // Verify output is valid JSON
        let json_content = std::fs::read_to_string(&output_path).unwrap();
        let _value: Value =
            serde_json::from_str(&json_content).expect("default format should produce valid JSON");
    }

    #[test]
    fn test_export_stdout_output() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");

        // Create and index a test file
        let test_file = temp_dir.path().join("test.rs");
        std::fs::write(&test_file, "fn test() {}").unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&test_file).unwrap();

        // Run export without --file (should write to stdout)
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("json")
            .output();

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.status.success());

        // Verify stdout contains expected export data fields
        let stdout = String::from_utf8_lossy(&output.stdout);
        // When exporting to stdout, the export JSON is written directly
        // followed by the success payload JSON. Verify both are present.
        assert!(
            stdout.contains("schema_version"),
            "stdout should contain schema_version"
        );
        assert!(
            stdout.contains("files"),
            "stdout should contain files array"
        );
        assert!(
            stdout.contains("symbols"),
            "stdout should contain symbols array"
        );
        assert!(
            stdout.contains("\"status\""),
            "stdout should contain success payload status"
        );
    }

    // ============================================================================
    // Extended export format validation tests (Phase 26-02)
    // ============================================================================

    #[test]
    fn test_export_json_schema_validation() {
        use splice::output::EXPORT_SCHEMA_VERSION;

        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export.json");

        // Create multiple test files (Rust and Python)
        let rust_file = temp_dir.path().join("lib.rs");
        std::fs::write(
            &rust_file,
            r#"
pub fn helper() -> i32 { 42 }
pub fn main() { let _ = helper(); }
"#,
        )
        .unwrap();

        let python_file = temp_dir.path().join("module.py");
        std::fs::write(
            &python_file,
            r#"
def helper():
    return 42

def main():
    helper()
"#,
        )
        .unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&rust_file).unwrap();
        integration.index_file(&python_file).unwrap();

        // Run export command
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("json")
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok(), "export command should execute");
        let output = result.unwrap();
        if !output.status.success() {
            eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        }
        assert!(output.status.success(), "export should return success");

        // Read and validate export.json
        let json_content = std::fs::read_to_string(&output_path).unwrap();
        let value: Value =
            serde_json::from_str(&json_content).expect("export should produce valid JSON");

        // 1. Validate schema_version
        assert_eq!(
            value.get("schema_version").and_then(|v| v.as_str()),
            Some(EXPORT_SCHEMA_VERSION),
            "schema_version should equal EXPORT_SCHEMA_VERSION constant"
        );
        assert_eq!(
            value["schema_version"], "1.0.0",
            "schema_version should be 1.0.0"
        );

        // 2. Validate timestamp is valid ISO 8601
        let timestamp = value
            .get("timestamp")
            .and_then(|v| v.as_str())
            .expect("should have timestamp string");
        assert!(!timestamp.is_empty(), "timestamp should not be empty");
        // Verify it's parseable as ISO 8601 (contains T and : chars)
        assert!(
            timestamp.contains('T'),
            "timestamp should be ISO 8601 format"
        );
        assert!(
            timestamp.contains(':'),
            "timestamp should have time component"
        );

        // 3. Validate db_path matches test database
        let db_path_str = value
            .get("db_path")
            .and_then(|v| v.as_str())
            .expect("should have db_path");
        assert!(
            db_path_str.contains("test.db")
                || db_path_str.contains(&format!("{}", db_path.display())),
            "db_path should reference test database"
        );

        // 4. Validate data structure has required arrays
        let data = value.get("data").expect("should have data object");
        assert!(
            data.get("files").and_then(|v| v.as_array()).is_some(),
            "data should have files array"
        );
        assert!(
            data.get("symbols").and_then(|v| v.as_array()).is_some(),
            "data should have symbols array"
        );
        assert!(
            data.get("references").and_then(|v| v.as_array()).is_some(),
            "data should have references array"
        );
        assert!(
            data.get("calls").and_then(|v| v.as_array()).is_some(),
            "data should have calls array"
        );

        // 5. Validate arrays have expected counts
        let files = data["files"].as_array().unwrap();
        let symbols = data["symbols"].as_array().unwrap();
        assert!(
            files.len() >= 2,
            "should have at least 2 files (Rust and Python)"
        );
        assert!(symbols.len() >= 2, "should have at least 2 symbols");

        // 6. Validate each symbol has required fields with correct types
        for symbol in symbols {
            // symbol_id is optional (can be null for some symbols)
            // Accept both 16-char SHA-256 (v1) and 32-char BLAKE3 (v2) formats
            if let Some(sid) = symbol.get("symbol_id") {
                if let Some(sid_str) = sid.as_str() {
                    assert!(
                        (sid_str.len() == 16 || sid_str.len() == 32)
                            && sid_str.chars().all(|c| c.is_ascii_hexdigit()),
                        "symbol_id should be 16-char or 32-char hex when present, got: {} ({})",
                        sid_str.len(),
                        sid_str
                    );
                }
            }

            // name must be non-empty string
            let name = symbol
                .get("name")
                .and_then(|v| v.as_str())
                .expect("symbol should have name");
            assert!(!name.is_empty(), "symbol name should not be empty");

            // kind must be valid symbol kind
            let kind = symbol
                .get("kind")
                .and_then(|v| v.as_str())
                .expect("symbol should have kind");
            let valid_kinds = [
                "fn",
                "method",
                "struct",
                "class",
                "enum",
                "interface",
                "module",
                "trait",
                "impl",
                "variable",
                "constructor",
                "type_alias",
                "function",
                "type",
            ]; // Additional kinds from different parsers
            assert!(
                valid_kinds.contains(&kind) || !kind.is_empty(),
                "symbol kind should be valid"
            );

            // file_path must be absolute path
            let file_path = symbol
                .get("file_path")
                .and_then(|v| v.as_str())
                .expect("symbol should have file_path");
            assert!(!file_path.is_empty(), "file_path should not be empty");

            // byte offsets
            let byte_start = symbol
                .get("byte_start")
                .and_then(|v| v.as_u64())
                .expect("symbol should have byte_start") as usize;
            let byte_end = symbol
                .get("byte_end")
                .and_then(|v| v.as_u64())
                .expect("symbol should have byte_end") as usize;
            assert!(
                byte_start < byte_end,
                "byte_start ({}) should be less than byte_end ({})",
                byte_start,
                byte_end
            );

            // Line numbers (may be 0 if not populated)
            let start_line = symbol
                .get("start_line")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;
            let end_line = symbol.get("end_line").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
            if start_line > 0 {
                assert!(
                    end_line >= start_line,
                    "end_line should be >= start_line when populated"
                );
            }

            // 7. Validate Magellan field naming (start_line not line_start)
            assert!(
                symbol.get("start_line").is_some(),
                "symbol should use Magellan field name start_line"
            );
            assert!(
                symbol.get("end_line").is_some(),
                "symbol should use Magellan field name end_line"
            );
        }
    }

    #[test]
    fn test_export_jsonl_record_types() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export.jsonl");

        // Create test files with different symbol types
        let rust_file = temp_dir.path().join("lib.rs");
        std::fs::write(
            &rust_file,
            r#"
pub fn helper() -> i32 { 42 }
pub struct Counter;
impl Counter {
    pub fn new() -> Self { Counter }
}
pub fn main() { let _ = helper(); }
"#,
        )
        .unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&rust_file).unwrap();

        // Run export command with jsonl format
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("jsonl")
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok(), "export command should execute");
        let output = result.unwrap();
        if !output.status.success() {
            eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        }
        assert!(output.status.success(), "export should return success");

        // Read and validate JSONL format
        let jsonl_content = std::fs::read_to_string(&output_path).unwrap();
        let lines: Vec<&str> = jsonl_content.lines().collect();

        // Should have at least header + file record + some symbols
        assert!(
            lines.len() >= 3,
            "should have header, file, and at least one symbol"
        );

        let mut found_header = false;
        let mut found_file = false;
        let mut found_symbol = false;

        // Track all record types found
        let mut record_types = std::collections::HashSet::new();

        for (line_num, line) in lines.iter().enumerate() {
            // Verify every line is valid JSON
            let value: Value = serde_json::from_str(line).unwrap_or_else(|e| {
                panic!(
                    "Line {} should be valid JSON: {}\nContent: {}",
                    line_num + 1,
                    e,
                    line
                );
            });

            // Check for type field
            if let Some(obj) = value.as_object() {
                if let Some(record_type) = obj.get("type") {
                    let type_str = record_type.as_str().unwrap_or_else(|| {
                        panic!("Line {} type field should be string", line_num + 1)
                    });
                    record_types.insert(type_str.to_string());

                    match type_str {
                        "header" => {
                            found_header = true;
                            // Header should have schema_version
                            assert!(
                                obj.get("schema_version").is_some(),
                                "header record should have schema_version"
                            );
                        }
                        "file" => {
                            found_file = true;
                            // File records have "data" wrapper with path and hash
                            if let Some(data) = obj.get("data") {
                                let data_obj =
                                    data.as_object().expect("file data should be object");
                                assert!(
                                    data_obj.get("path").is_some(),
                                    "file data should have path"
                                );
                                assert!(
                                    data_obj.get("hash").is_some(),
                                    "file data should have hash"
                                );
                            } else {
                                panic!("Line {} file record should have data field", line_num + 1);
                            }
                        }
                        "symbol" => {
                            found_symbol = true;
                            // Symbol records have "data" wrapper
                            if let Some(data) = obj.get("data") {
                                let data_obj =
                                    data.as_object().expect("symbol data should be object");
                                assert!(
                                    data_obj.get("name").is_some(),
                                    "symbol data should have name"
                                );
                                assert!(
                                    data_obj.get("kind").is_some(),
                                    "symbol data should have kind"
                                );
                                assert!(
                                    data_obj.get("file_path").is_some(),
                                    "symbol data should have file_path"
                                );
                            } else {
                                panic!(
                                    "Line {} symbol record should have data field",
                                    line_num + 1
                                );
                            }
                        }
                        "reference" => {
                            // Reference records with from_symbol and to_symbol
                            if let Some(data) = obj.get("data") {
                                let data_obj =
                                    data.as_object().expect("reference data should be object");
                                assert!(
                                    data_obj.get("from_symbol_id").is_some()
                                        || data_obj.get("from_symbol").is_some(),
                                    "reference data should have from_symbol field"
                                );
                                assert!(
                                    data_obj.get("to_symbol_id").is_some()
                                        || data_obj.get("to_symbol").is_some(),
                                    "reference data should have to_symbol field"
                                );
                            }
                        }
                        "call" => {
                            // Call records with caller and callee
                            if let Some(data) = obj.get("data") {
                                let data_obj =
                                    data.as_object().expect("call data should be object");
                                assert!(
                                    data_obj.get("caller_symbol_id").is_some()
                                        || data_obj.get("caller").is_some(),
                                    "call data should have caller field"
                                );
                                assert!(
                                    data_obj.get("callee_symbol_id").is_some()
                                        || data_obj.get("callee").is_some(),
                                    "call data should have callee field"
                                );
                                assert!(
                                    data_obj.get("call_site").is_some()
                                        || data_obj.get("call_site_file").is_some()
                                        || data_obj.get("call_site_line").is_some(),
                                    "call data should have call_site field"
                                );
                            }
                        }
                        other => {
                            panic!("Line {} unexpected record type: {}", line_num + 1, other);
                        }
                    }
                }
            }
        }

        // Verify we found the expected record types
        assert!(found_header, "should find header record type");
        assert!(found_file, "should find at least one file record type");
        assert!(found_symbol, "should find at least one symbol record type");

        // Verify all record types are valid
        for record_type in &record_types {
            assert!(
                matches!(
                    record_type.as_str(),
                    "header" | "file" | "symbol" | "reference" | "call"
                ),
                "record type '{}' should be valid",
                record_type
            );
        }
    }

    #[test]
    fn test_export_csv_section_structure() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let output_path = temp_dir.path().join("export.csv");

        // Create multiple test files
        let rust_file = temp_dir.path().join("lib.rs");
        std::fs::write(
            &rust_file,
            r#"
pub fn helper() -> i32 { 42 }
pub struct Counter;
pub fn main() { let _ = helper(); }
"#,
        )
        .unwrap();

        let python_file = temp_dir.path().join("module.py");
        std::fs::write(
            &python_file,
            r#"
def helper():
    return 42
"#,
        )
        .unwrap();

        let mut integration = MagellanIntegration::open(&db_path).unwrap();
        integration.index_file(&rust_file).unwrap();
        integration.index_file(&python_file).unwrap();

        // Run export command with csv format
        let splice_binary = get_splice_binary();
        let result = Command::new(&splice_binary)
            .arg("export")
            .arg("--db")
            .arg(&db_path)
            .arg("--format")
            .arg("csv")
            .arg("--file")
            .arg(&output_path)
            .output();

        assert!(result.is_ok(), "export command should execute");
        let output = result.unwrap();
        if !output.status.success() {
            eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        }
        assert!(output.status.success(), "export should return success");

        // Read and validate CSV format
        let csv_content = std::fs::read_to_string(&output_path).unwrap();

        // 1. Validate section headers
        assert!(
            csv_content.contains("# Files"),
            "CSV should have Files section header"
        );
        assert!(
            csv_content.contains("# Symbols"),
            "CSV should have Symbols section header"
        );

        // 2. Parse into sections
        let lines: Vec<&str> = csv_content.lines().collect();

        // Find section boundaries
        let mut files_section_start = None;
        let mut symbols_section_start = None;
        let mut references_section_start = None;
        let mut calls_section_start = None;

        for (i, line) in lines.iter().enumerate() {
            if *line == "# Files" {
                files_section_start = Some(i);
            } else if *line == "# Symbols" {
                symbols_section_start = Some(i);
            } else if *line == "# References" {
                references_section_start = Some(i);
            } else if *line == "# Calls" {
                calls_section_start = Some(i);
            }
        }

        assert!(files_section_start.is_some(), "should find # Files section");
        assert!(
            symbols_section_start.is_some(),
            "should find # Symbols section"
        );

        // 3. Validate Files section has proper headers
        if let Some(files_start) = files_section_start {
            // Files section header is followed by column header row
            if files_start + 1 < lines.len() {
                let header_line = lines[files_start + 1];
                assert!(
                    header_line.contains("path"),
                    "Files section should have path column header"
                );
                assert!(
                    header_line.contains("hash"),
                    "Files section should have hash column header"
                );
            }
        }

        // 4. Validate Symbols section has proper headers
        if let Some(symbols_start) = symbols_section_start {
            // Symbols section header is followed by column header row
            if symbols_start + 1 < lines.len() {
                let header_line = lines[symbols_start + 1];
                assert!(
                    header_line.contains("symbol_id"),
                    "Symbols section should have symbol_id column header"
                );
                assert!(
                    header_line.contains("name"),
                    "Symbols section should have name column header"
                );
                assert!(
                    header_line.contains("kind"),
                    "Symbols section should have kind column header"
                );
                assert!(
                    header_line.contains("file_path"),
                    "Symbols section should have file_path column header"
                );
                assert!(
                    header_line.contains("byte_start"),
                    "Symbols section should have byte_start column header"
                );
                assert!(
                    header_line.contains("byte_end"),
                    "Symbols section should have byte_end column header"
                );
            }
        }

        // 5. Validate data rows match column counts
        // Count columns in header row vs data rows for each section
        let mut prev_col_count = None;

        for line in &lines {
            // Skip empty lines and section headers
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            let col_count = line.split(',').count();

            if let Some(prev) = prev_col_count {
                // Within a section, column counts should be consistent
                // (New sections reset the count, which is fine)
                if col_count != prev {
                    // Column count changed - this is OK at section boundaries
                }
            }
            prev_col_count = Some(col_count);
        }

        // 6. Validate no empty rows between sections
        for (i, line) in lines.iter().enumerate() {
            // Empty lines are allowed, but consecutive empty lines are not
            if line.is_empty() {
                if i > 0 && lines[i - 1].is_empty() {
                    panic!("Line {}: consecutive empty lines not allowed", i + 1);
                }
            }
        }

        // 7. Verify we have actual data (at least 2 files and symbols)
        let data_lines: Vec<&str> = lines
            .iter()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .copied()
            .collect();

        assert!(
            data_lines.len() >= 2,
            "should have at least 2 data rows (files + symbols)"
        );
    }

    #[test]
    fn test_export_error_handling() {
        // Test 1: Invalid format option (if CLI validates it)
        {
            let temp_dir = TempDir::new().unwrap();
            let db_path = temp_dir.path().join("test.db");

            // Create a test file and index it
            let test_file = temp_dir.path().join("test.rs");
            std::fs::write(&test_file, "fn test() {}").unwrap();

            let mut integration = MagellanIntegration::open(&db_path).unwrap();
            integration.index_file(&test_file).unwrap();

            let splice_binary = get_splice_binary();
            let output = Command::new(&splice_binary)
                .arg("export")
                .arg("--db")
                .arg(&db_path)
                .arg("--format")
                .arg("invalid_format")
                .output();

            assert!(output.is_ok(), "command should execute");
            let output = output.unwrap();

            // Should fail - clap validates the format enum
            assert!(
                !output.status.success(),
                "export should fail with invalid format"
            );

            // Exit code should be 2 (usage error) from clap
            let exit_code = output.status.code();
            assert!(
                exit_code == Some(2),
                "Expected exit code 2 for invalid argument, got {:?}",
                exit_code
            );

            // stderr should mention the invalid value
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                stderr.contains("invalid_format")
                    || stderr.contains("invalid")
                    || stderr.contains("possible values")
                    || stderr.contains("one of"),
                "stderr should mention invalid value or show possible values"
            );
        }

        // Test 2: Valid export with empty database (edge case - Magellan creates db if nonexistent)
        {
            let temp_dir = TempDir::new().unwrap();
            let db_path = temp_dir.path().join("empty.db");
            let output_path = temp_dir.path().join("export.json");

            // Create empty database
            let _integration = MagellanIntegration::open(&db_path).unwrap();

            let splice_binary = get_splice_binary();
            let output = Command::new(&splice_binary)
                .arg("export")
                .arg("--db")
                .arg(&db_path)
                .arg("--format")
                .arg("json")
                .arg("--file")
                .arg(&output_path)
                .output();

            assert!(output.is_ok(), "command should execute");
            let output = output.unwrap();

            // Should succeed with empty data
            assert!(
                output.status.success(),
                "export should succeed with empty database"
            );

            // Output should be valid JSON with empty arrays
            let json_content = std::fs::read_to_string(&output_path).unwrap();
            let value: Value =
                serde_json::from_str(&json_content).expect("export should produce valid JSON");

            assert!(
                value.get("schema_version").is_some(),
                "should have schema_version"
            );
            assert!(
                value["data"]["files"].as_array().unwrap().is_empty(),
                "files array should be empty"
            );
            assert!(
                value["data"]["symbols"].as_array().unwrap().is_empty(),
                "symbols array should be empty"
            );
        }

        // Test 3: File write permission error (read-only directory) - Unix only
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            let temp_dir = TempDir::new().unwrap();
            let db_path = temp_dir.path().join("test.db");
            let readonly_dir = temp_dir.path().join("readonly");

            // Create a test file and index it
            let test_file = temp_dir.path().join("test.rs");
            std::fs::write(&test_file, "fn test() {}").unwrap();

            let mut integration = MagellanIntegration::open(&db_path).unwrap();
            integration.index_file(&test_file).unwrap();

            // Create read-only directory
            std::fs::create_dir(&readonly_dir).unwrap();
            let mut perms = std::fs::metadata(&readonly_dir).unwrap().permissions();
            perms.set_mode(0o444); // read-only
            std::fs::set_permissions(&readonly_dir, perms).unwrap();

            let readonly_file = readonly_dir.join("export.json");

            let splice_binary = get_splice_binary();
            let output = Command::new(&splice_binary)
                .arg("export")
                .arg("--db")
                .arg(&db_path)
                .arg("--format")
                .arg("json")
                .arg("--file")
                .arg(&readonly_file)
                .output();

            assert!(output.is_ok(), "command should execute");
            let output = output.unwrap();

            // Should fail due to permission error
            assert!(
                !output.status.success(),
                "export should fail with read-only directory"
            );

            // Exit code should be 1 (error)
            let exit_code = output.status.code();
            assert!(
                exit_code == Some(1),
                "Expected exit code 1 for permission error, got {:?}",
                exit_code
            );

            // stderr should contain error message
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                !stderr.is_empty() || !output.stdout.is_empty(),
                "should have some error output"
            );
        }

        // Test 4: Export to stdout succeeds
        {
            let temp_dir = TempDir::new().unwrap();
            let db_path = temp_dir.path().join("test.db");

            // Create a test file and index it
            let test_file = temp_dir.path().join("test.rs");
            std::fs::write(&test_file, "fn test() {}").unwrap();

            let mut integration = MagellanIntegration::open(&db_path).unwrap();
            integration.index_file(&test_file).unwrap();

            let splice_binary = get_splice_binary();
            let output = Command::new(&splice_binary)
                .arg("export")
                .arg("--db")
                .arg(&db_path)
                .arg("--format")
                .arg("json")
                .output();

            assert!(output.is_ok(), "command should execute");
            let output = output.unwrap();

            // Should succeed (writing to stdout is valid)
            assert!(output.status.success(), "export to stdout should succeed");

            // stdout should contain export data
            let stdout = String::from_utf8_lossy(&output.stdout);
            assert!(
                stdout.contains("schema_version"),
                "stdout should contain schema_version"
            );
            assert!(
                stdout.contains("\"status\""),
                "stdout should contain success status"
            );
        }
    }
}