codenexus 0.4.0-rc.1

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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! Import command: decompress a zstd team artifact into the database.
//!
//! See [`crate::service::export`] for the artifact format and zstd library
//! dependency rationale.

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

use serde::Serialize;

use crate::service::export::{ArtifactManifest, ARTIFACT_FORMAT_VERSION, ARTIFACT_MAGIC};
use crate::storage::StorageConfig;

#[cfg(any(feature = "cli", feature = "mcp", test))]
use crate::kit::{AsyncKit, AsyncReady};
#[cfg(any(feature = "cli", feature = "mcp", test))]
use crate::service::error::CodeNexusError;
#[cfg(any(feature = "cli", feature = "mcp"))]
use crate::service::error::{kit_not_initialized, to_api_error};
#[cfg(any(feature = "cli", feature = "mcp"))]
use crate::service::runtime::kit;

#[cfg(feature = "cli")]
use sdforge::forge;
#[cfg(any(feature = "cli", feature = "mcp"))]
use sdforge::prelude::ApiError;

/// JSON-serializable import-command output.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ImportOutput {
    pub artifact: String,
    pub db: String,
    pub db_size: u64,
    pub manifest: ArtifactManifest,
    pub reindexed: bool,
}

/// Hard cap on the decompressed DB payload accepted from an artifact.
///
/// `import` processes artifacts produced by *other people* (team sharing), so
/// the zstd step must be bomb-safe: a few MB of malicious compressed input can
/// otherwise expand to tens of GB and OOM the process before any DB write
/// happens. 4 GiB comfortably covers legitimate indexed repositories (a 10k-
/// file repo indexes to a few hundred MB) while bounding worst-case memory.
#[cfg(any(feature = "cli", feature = "mcp", test))]
const MAX_IMPORT_DB_BYTES: usize = 4 << 30;

/// Decompresses `input` (zstd-compressed bytes) via the `oxiarc-zstd` pure-Rust
/// library, refusing payloads that expand beyond [`MAX_IMPORT_DB_BYTES`].
#[cfg(any(feature = "cli", feature = "mcp", test))]
fn zstd_decompress(input: &[u8]) -> Result<Vec<u8>, CodeNexusError> {
    zstd_decompress_with_limit(input, MAX_IMPORT_DB_BYTES)
}

/// Bomb-safe zstd decompression with an explicit output cap.
///
/// The concrete error type (`oxiarc_core::error::OxiArcError`) lives in a
/// transitive dependency, so the budget-overrun variant is detected via its
/// stable Display prefix ("memory budget exceeded: …") and mapped to
/// `InvalidInput` — an oversized artifact is an input problem, not an
/// internal one.
#[cfg(any(feature = "cli", feature = "mcp", test))]
fn zstd_decompress_with_limit(input: &[u8], limit: usize) -> Result<Vec<u8>, CodeNexusError> {
    oxiarc_zstd::decompress_with_limit(input, limit).map_err(|e| {
        let msg = e.to_string();
        if msg.starts_with("memory budget exceeded") {
            CodeNexusError::InvalidInput(format!(
                "artifact decompressed size exceeds the {} GiB import limit (possible decompression bomb or corrupt artifact)",
                MAX_IMPORT_DB_BYTES >> 30
            ))
        } else {
            CodeNexusError::Internal(format!("zstd decompression failed: {e}"))
        }
    })
}

/// Parses and validates the artifact header (magic + manifest) without
/// touching the compressed payload.
///
/// Returns the parsed manifest and the total header size (`8`-byte prefix +
/// manifest). This is a pure function — no filesystem or database access —
/// so it is also exercised directly by the `cnxp_header` fuzz target.
///
/// # Errors
///
/// [`CodeNexusError::InvalidInput`] for truncation, magic mismatch or
/// unsupported `format_version`; serde errors for malformed manifest JSON.
#[cfg(any(feature = "cli", feature = "mcp", test))]
pub fn parse_artifact_header(bytes: &[u8]) -> Result<(ArtifactManifest, usize), CodeNexusError> {
    if bytes.len() < 8 {
        return Err(CodeNexusError::InvalidInput(format!(
            "artifact too small ({} bytes) — expected at least 8-byte header",
            bytes.len()
        )));
    }
    if bytes[0..4] != ARTIFACT_MAGIC {
        return Err(CodeNexusError::InvalidInput(format!(
            "artifact magic mismatch — expected {:?}, got {:?}",
            std::str::from_utf8(&ARTIFACT_MAGIC),
            std::str::from_utf8(&bytes[0..4])
        )));
    }
    let manifest_len = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;
    let header_total = 8 + manifest_len;
    if bytes.len() < header_total {
        return Err(CodeNexusError::InvalidInput(format!(
            "artifact truncated — header says manifest is {} bytes but file only has {} bytes total",
            manifest_len,
            bytes.len()
        )));
    }
    let manifest: ArtifactManifest = serde_json::from_slice(&bytes[8..header_total])?;
    if manifest.format_version != ARTIFACT_FORMAT_VERSION {
        return Err(CodeNexusError::InvalidInput(format!(
            "artifact format version mismatch — expected {}, got {}",
            ARTIFACT_FORMAT_VERSION, manifest.format_version
        )));
    }
    Ok((manifest, header_total))
}

/// Runs import against an injected Kit (testable core).
#[cfg(any(feature = "cli", feature = "mcp", test))]
pub fn run_import(
    kit: &AsyncKit<AsyncReady>,
    input: &str,
    reindex: bool,
    path: &str,
    name: &str,
) -> Result<ImportOutput, CodeNexusError> {
    let storage_config = kit.config::<StorageConfig>()?;
    let db_path = storage_config.db_path.clone();
    let db_path_str = db_path.to_string_lossy().into_owned();

    let input_path = Path::new(input);
    if !input_path.exists() {
        return Err(CodeNexusError::InvalidInput(format!(
            "artifact path does not exist: {input}"
        )));
    }

    let artifact_bytes = std::fs::read(input_path)?;
    let (manifest, header_total) = parse_artifact_header(&artifact_bytes)?;

    let compressed_payload = &artifact_bytes[header_total..];
    let db_bytes = zstd_decompress(compressed_payload)?;

    // Integrity gate: verify the payload digest recorded by `export` before
    // it overwrites the local database. Artifacts without a digest
    // (`payload_blake3 == None`, pre-0.3.x format) skip the check.
    if let Some(expected) = &manifest.payload_blake3 {
        let actual = blake3::hash(&db_bytes).to_string();
        if actual != *expected {
            return Err(CodeNexusError::InvalidInput(
                "artifact integrity check failed — payload digest does not match the                  manifest (corrupt or tampered artifact)"
                    .to_string(),
            ));
        }
    }
    if manifest.original_size != 0 && manifest.original_size != db_bytes.len() as u64 {
        return Err(CodeNexusError::InvalidInput(format!(
            "artifact size mismatch — manifest says {} bytes, payload is {} bytes",
            manifest.original_size,
            db_bytes.len()
        )));
    }

    // Remove stale WAL sidecar so LadybugDB doesn't reject the imported DB
    // (the WAL carries the old database ID; importing replaces the DB bytes).
    let wal_path = format!("{}.wal", db_path.display());
    let _ = std::fs::remove_file(&wal_path);

    {
        let mut out = File::create(&db_path)?;
        out.write_all(&db_bytes)?;
        out.flush()?;
    }

    let db_size = db_path.metadata()?.len();

    let mut reindexed = false;
    if reindex {
        if path.is_empty() {
            return Err(CodeNexusError::InvalidInput(
                "--reindex requires --path".to_string(),
            ));
        }
        if name.is_empty() {
            return Err(CodeNexusError::InvalidInput(
                "--reindex requires --name".to_string(),
            ));
        }
        let _output =
            crate::service::index::index_core(kit, &db_path, path, name, false, false, false)?;
        reindexed = true;
    }

    Ok(ImportOutput {
        artifact: input.to_string(),
        db: db_path_str,
        db_size,
        manifest,
        reindexed,
    })
}

/// CLI wrapper — prints result to stdout as JSON.
#[cfg(feature = "cli")]
#[forge(
    name = "import",
    version = "0.3.5",
    description = "Import a zstd team artifact into the graph database.",
    cli = true
)]
async fn import(input: String, reindex: bool, path: String, name: String) -> Result<(), ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    let result = run_import(&kit, &input, reindex, &path, &name)
        .map_err(|e| to_api_error(e, "import_error"))?;
    let json = serde_json::to_string(&result)
        .map_err(|e| to_api_error(CodeNexusError::from(e), "import_error"))?;
    println!("{json}");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kit::{build_kit, KitBootstrapConfig};
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn fresh_db_path() -> (TempDir, PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("svc_import_testdb");
        (dir, path)
    }

    fn build_kit_for_db(db: &std::path::Path) -> AsyncKit<AsyncReady> {
        let config = KitBootstrapConfig::new(db.to_path_buf());
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(build_kit(&config))
            .expect("build_kit")
    }

    #[test]
    fn import_output_serializes_to_json() {
        let manifest = ArtifactManifest {
            format_version: ARTIFACT_FORMAT_VERSION.to_string(),
            codenexus_version: "0.3.2".into(),
            exported_at: 1000,
            source_db_path: "/db".into(),
            project: Some("demo".into()),
            original_size: 4096,
            payload_blake3: None,
        };
        let output = ImportOutput {
            artifact: "/tmp/a.cnxp".into(),
            db: "/db/path".into(),
            db_size: 2048,
            manifest,
            reindexed: false,
        };
        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"artifact\":\"/tmp/a.cnxp\""));
        assert!(json.contains("\"db\":\"/db/path\""));
        assert!(json.contains("\"db_size\":2048"));
        assert!(json.contains("\"reindexed\":false"));
        assert!(json.contains("\"format_version\":\"1.0\""));
    }

    #[test]
    fn zstd_decompress_returns_error_for_invalid_input() {
        let garbage = b"this is not valid zstd data at all";
        let err = zstd_decompress(garbage).expect_err("decompressing garbage should fail");
        // zstd library returns io::Error for invalid data, converted to CodeNexusError::Io.
        let msg = err.to_string();
        assert!(!msg.is_empty(), "error should have a message");
    }

    #[test]
    fn zstd_decompress_succeeds_for_valid_compressed_data() {
        let original = b"Hello, zstd! This is a test for round-trip decompression.";
        let compressed = oxiarc_zstd::compress_with_level(&original[..], 19).expect("zstd encode");
        let decompressed = zstd_decompress(&compressed).expect("zstd_decompress should succeed");
        assert_eq!(decompressed, original, "decompressed should match original");
    }

    /// Decompression-bomb guard: a tiny compressed payload that expands beyond
    /// the configured limit must be rejected as InvalidInput (exit 2), not
    /// allocate the full output. Uses a small limit so the test stays cheap —
    /// production passes [`MAX_IMPORT_DB_BYTES`].
    #[test]
    fn zstd_decompress_rejects_payload_exceeding_limit() {
        let bomb_source = vec![b'A'; 1 << 20]; // 1 MiB compresses to ~1 KB
        let compressed =
            oxiarc_zstd::compress_with_level(&bomb_source[..], 19).expect("zstd encode");
        let err = zstd_decompress_with_limit(&compressed, 4096)
            .expect_err("payload beyond the limit must be rejected");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(msg.contains("import limit"), "unexpected message: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    /// The production limit itself admits legitimate payloads (round-trip at
    /// the real cap, keeping the guard from being accidentally tightened to
    /// something unusable).
    #[test]
    fn zstd_decompress_allows_payload_under_production_limit() {
        let original = b"legitimate artifact payload";
        let compressed = oxiarc_zstd::compress_with_level(&original[..], 19).expect("zstd encode");
        let decompressed = zstd_decompress(&compressed).expect("under the cap must succeed");
        assert_eq!(decompressed, original);
    }

    /// Integrity gate: a payload whose digest differs from the manifest's
    /// `payload_blake3` must be rejected (tamper/corruption detection).
    #[test]
    fn run_import_rejects_payload_digest_mismatch() {
        let (src_dir, src_db) = fresh_db_path();
        let src_kit = build_kit_for_db(&src_db);
        let artifact = src_dir.path().join("tamper.cnxp");

        crate::service::export::run_export(&src_kit, artifact.to_str().unwrap(), "demo")
            .expect("run_export should succeed");

        // Tamper: keep the valid header+manifest (recording the original
        // payload digest) but replace the payload with a *valid* zstd frame
        // of different content — the frame checksum passes, so only the
        // manifest digest gate can catch this.
        let bytes = std::fs::read(&artifact).unwrap();
        let manifest_len = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;
        let header = &bytes[..8 + manifest_len];
        let evil_payload = oxiarc_zstd::compress_with_level(&b"attacker-controlled bytes"[..], 19)
            .expect("zstd encode");
        let mut tampered_bytes = header.to_vec();
        tampered_bytes.extend_from_slice(&evil_payload);
        let tampered = src_dir.path().join("tampered.cnxp");
        std::fs::write(&tampered, &tampered_bytes).unwrap();

        let (_dst_dir, dst_db) = fresh_db_path();
        let dst_kit = build_kit_for_db(&dst_db);
        let err = run_import(&dst_kit, tampered.to_str().unwrap(), false, "", "")
            .expect_err("tampered artifact must be rejected");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("integrity check failed"),
                    "unexpected message: {msg}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn zstd_decompress_returns_error_for_empty_input() {
        let err = zstd_decompress(b"").expect_err("empty input should fail decompression");
        let msg = err.to_string();
        assert!(!msg.is_empty(), "error should have a message");
    }

    #[test]
    fn run_import_returns_error_for_nonexistent_artifact() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let err = run_import(&kit, "/nonexistent/path/artifact.cnxp", false, "", "")
            .expect_err("nonexistent artifact should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("artifact path does not exist"),
                    "unexpected message: {msg}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn run_import_returns_error_for_too_small_artifact() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("small.cnxp");
        std::fs::write(&artifact, b"CNXP").unwrap(); // Only 4 bytes, < 8
        let err = run_import(&kit, artifact.to_str().unwrap(), false, "", "")
            .expect_err("too-small artifact should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("artifact too small"),
                    "unexpected message: {msg}"
                );
                assert!(msg.contains("4 bytes"), "should mention size: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn run_import_returns_error_for_bad_magic() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("badmagic.cnxp");
        let mut data = b"BADM".to_vec();
        data.extend(&[0u8, 0, 0, 0]); // manifest_len = 0
        std::fs::write(&artifact, &data).unwrap();
        let err = run_import(&kit, artifact.to_str().unwrap(), false, "", "")
            .expect_err("bad magic should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(msg.contains("magic mismatch"), "unexpected message: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn run_import_returns_error_for_truncated_artifact() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("truncated.cnxp");
        let mut data = ARTIFACT_MAGIC.to_vec();
        data.extend(&100u32.to_le_bytes()); // manifest_len = 100
        data.extend(b"{ }"); // Only 2 bytes, but header says 100
        std::fs::write(&artifact, &data).unwrap();
        let err = run_import(&kit, artifact.to_str().unwrap(), false, "", "")
            .expect_err("truncated artifact should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("artifact truncated"),
                    "unexpected message: {msg}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn run_import_returns_error_for_version_mismatch() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("badversion.cnxp");
        let manifest = ArtifactManifest {
            format_version: "0.0".to_string(), // Wrong version
            codenexus_version: "0.3.2".into(),
            exported_at: 0,
            source_db_path: "/dummy".into(),
            project: None,
            original_size: 0,
            payload_blake3: None,
        };
        let manifest_json = serde_json::to_vec(&manifest).unwrap();
        let mut data = ARTIFACT_MAGIC.to_vec();
        data.extend(&(manifest_json.len() as u32).to_le_bytes());
        data.extend(&manifest_json);
        data.extend(b"fake_compressed_data");
        std::fs::write(&artifact, &data).unwrap();
        let err = run_import(&kit, artifact.to_str().unwrap(), false, "", "")
            .expect_err("version mismatch should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("version mismatch"),
                    "unexpected message: {msg}"
                );
                assert!(msg.contains("0.0"), "should mention bad version: {msg}");
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    // Covers line 127: serde_json::from_slice error path when manifest JSON
    // is malformed (valid magic + manifest_len, but invalid JSON content).
    #[test]
    fn run_import_returns_error_for_malformed_manifest_json() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("malformed.cnxp");
        let bad_manifest = b"{ this is not valid json";
        let mut data = ARTIFACT_MAGIC.to_vec();
        data.extend(&(bad_manifest.len() as u32).to_le_bytes());
        data.extend(bad_manifest);
        data.extend(b"fake_compressed_data");
        std::fs::write(&artifact, &data).unwrap();
        let err = run_import(&kit, artifact.to_str().unwrap(), false, "", "")
            .expect_err("malformed manifest JSON should error");
        // serde_json::from_slice error is wrapped via `?` on line 127,
        // producing a serde_json error (converted to CodeNexusError).
        // The error should NOT be InvalidInput (that's for our explicit checks);
        // it should be a serialization/deserialization error.
        let msg = err.to_string();
        assert!(
            msg.to_lowercase().contains("json")
                || msg.to_lowercase().contains("deserialize")
                || msg.to_lowercase().contains("parse"),
            "unexpected error for malformed manifest: {msg}"
        );
    }

    // Covers the case where the manifest_len is 0 (header says 0 bytes for
    // manifest). This triggers serde_json::from_slice on an empty slice,
    // which returns an EOF error.
    #[test]
    fn run_import_returns_error_for_zero_manifest_len() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("zerolen.cnxp");
        let mut data = ARTIFACT_MAGIC.to_vec();
        data.extend(&0u32.to_le_bytes()); // manifest_len = 0
        data.extend(b"fake_compressed_data");
        std::fs::write(&artifact, &data).unwrap();
        let err = run_import(&kit, artifact.to_str().unwrap(), false, "", "")
            .expect_err("zero manifest_len should error");
        let msg = err.to_string();
        // Empty slice → serde_json EOF error
        assert!(!msg.is_empty(), "error message should not be empty");
    }

    #[test]
    fn run_import_returns_error_for_reindex_without_path() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("valid.cnxp");
        let manifest = ArtifactManifest {
            format_version: ARTIFACT_FORMAT_VERSION.to_string(),
            codenexus_version: "0.3.2".into(),
            exported_at: 0,
            source_db_path: "/dummy".into(),
            project: None,
            original_size: 0,
            payload_blake3: None,
        };
        let manifest_json = serde_json::to_vec(&manifest).unwrap();
        let compressed =
            oxiarc_zstd::compress_with_level(&b"fake_db_bytes"[..], 19).expect("zstd encode");
        let mut data = ARTIFACT_MAGIC.to_vec();
        data.extend(&(manifest_json.len() as u32).to_le_bytes());
        data.extend(&manifest_json);
        data.extend(&compressed);
        std::fs::write(&artifact, &data).unwrap();

        let err = run_import(&kit, artifact.to_str().unwrap(), true, "", "demo")
            .expect_err("reindex without path should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("--reindex requires --path"),
                    "should mention --reindex requires --path: {msg}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn run_import_returns_error_for_reindex_without_name() {
        let (dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let artifact = dir.path().join("valid2.cnxp");
        let manifest = ArtifactManifest {
            format_version: ARTIFACT_FORMAT_VERSION.to_string(),
            codenexus_version: "0.3.2".into(),
            exported_at: 0,
            source_db_path: "/dummy".into(),
            project: None,
            original_size: 0,
            payload_blake3: None,
        };
        let manifest_json = serde_json::to_vec(&manifest).unwrap();
        let compressed =
            oxiarc_zstd::compress_with_level(&b"fake_db_bytes"[..], 19).expect("zstd encode");
        let mut data = ARTIFACT_MAGIC.to_vec();
        data.extend(&(manifest_json.len() as u32).to_le_bytes());
        data.extend(&manifest_json);
        data.extend(&compressed);
        std::fs::write(&artifact, &data).unwrap();

        let err = run_import(&kit, artifact.to_str().unwrap(), true, "/some/path", "")
            .expect_err("reindex without name should error");
        match err {
            CodeNexusError::InvalidInput(msg) => {
                assert!(
                    msg.contains("--reindex requires --name"),
                    "should mention --reindex requires --name: {msg}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    // Round-trip test: export a DB to an artifact, then import it back.
    // Covers zstd_decompress success path (lines 62-76) and run_import
    // file-write success path (lines 139-168).
    #[test]
    fn run_import_round_trips_with_export_artifact() {
        let (src_dir, src_db) = fresh_db_path();
        let src_kit = build_kit_for_db(&src_db);
        let artifact = src_dir.path().join("roundtrip.cnxp");

        let export_output =
            crate::service::export::run_export(&src_kit, artifact.to_str().unwrap(), "demo")
                .expect("run_export should succeed");

        let (_dst_dir, dst_db) = fresh_db_path();
        let dst_kit = build_kit_for_db(&dst_db);
        let import_output = run_import(&dst_kit, artifact.to_str().unwrap(), false, "", "")
            .expect("import should succeed for valid artifact");

        assert_eq!(import_output.artifact, artifact.to_str().unwrap());
        assert!(import_output.db_size > 0, "db_size should be > 0");
        assert!(!import_output.reindexed);
        assert_eq!(
            import_output.manifest.format_version,
            ARTIFACT_FORMAT_VERSION
        );
        assert_eq!(import_output.manifest.project.as_deref(), Some("demo"));
        assert_eq!(
            import_output.manifest.original_size,
            export_output.original_size
        );
    }

    // Covers run_import reindex success path (lines 146-160).
    #[cfg(feature = "lang-rust")]
    #[test]
    fn run_import_with_reindex_succeeds() {
        let (src_dir, src_db) = fresh_db_path();
        let src_kit = build_kit_for_db(&src_db);
        let artifact = src_dir.path().join("reindex.cnxp");

        crate::service::export::run_export(&src_kit, artifact.to_str().unwrap(), "demo")
            .expect("run_export should succeed");

        let reindex_src = TempDir::new().unwrap();
        std::fs::write(
            reindex_src.path().join("lib.rs"),
            "pub fn add(a: i32, b: i32) -> i32 { a + b }\n",
        )
        .unwrap();

        let (_dst_dir, dst_db) = fresh_db_path();
        let dst_kit = build_kit_for_db(&dst_db);
        let import_output = run_import(
            &dst_kit,
            artifact.to_str().unwrap(),
            true,
            reindex_src.path().to_str().unwrap(),
            "reindexed_project",
        )
        .expect("import with reindex should succeed");

        assert!(
            import_output.reindexed,
            "reindex=true → reindexed should be true"
        );
        assert!(import_output.db_size > 0);
    }

    // ===== #[forge] wrapper tests via init_kit =====

    /// RAII guard that resets the global Kit on Drop, ensuring test isolation.
    #[cfg(feature = "cli")]
    struct KitGuard;

    #[cfg(feature = "cli")]
    impl KitGuard {
        fn new() -> Self {
            crate::service::runtime::force_reset_kit_for_testing();
            Self
        }
    }

    #[cfg(feature = "cli")]
    impl Drop for KitGuard {
        fn drop(&mut self) {
            crate::service::runtime::force_reset_kit_for_testing();
        }
    }

    #[serial_test::serial(kit_init)]
    #[cfg(feature = "cli")]
    #[test]
    fn import_wrapper_fails_with_nonexistent_artifact() {
        let _guard = KitGuard::new();
        let (_dir, db) = fresh_db_path();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let kit = rt.block_on(async {
            let config = KitBootstrapConfig::new(db.to_path_buf());
            build_kit(&config).await.expect("build_kit")
        });
        crate::service::runtime::force_init_kit_for_testing(kit);
        let result = rt.block_on(import(
            "/nonexistent/path/artifact.cnxp".to_string(),
            false,
            String::new(),
            String::new(),
        ));
        let err = result.expect_err("nonexistent artifact should error");
        assert!(
            matches!(err, ApiError::InvalidInput { .. }),
            "expected InvalidInput, got {err:?}"
        );
    }

    #[serial_test::serial(kit_init)]
    #[cfg(feature = "cli")]
    #[test]
    fn import_wrapper_fails_when_kit_not_initialized() {
        let _guard = KitGuard::new();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(import(
            "/nonexistent/path/artifact.cnxp".to_string(),
            false,
            String::new(),
            String::new(),
        ));
        assert!(result.is_err(), "wrapper should fail without kit");
    }

    // Covers the import wrapper success path (lines 180-188):
    // kit() resolves, run_export creates artifact, run_import succeeds,
    // serde_json::to_string succeeds, println outputs JSON.
    #[serial_test::serial(kit_init)]
    #[cfg(feature = "cli")]
    #[test]
    fn import_wrapper_succeeds_via_init_kit() {
        let _guard = KitGuard::new();

        let (src_dir, src_db) = fresh_db_path();
        let src_rt = tokio::runtime::Runtime::new().expect("runtime");
        let src_kit = src_rt.block_on(async {
            let config = KitBootstrapConfig::new(src_db.to_path_buf());
            build_kit(&config).await.expect("build_kit")
        });
        let artifact = src_dir.path().join("wrapper_roundtrip.cnxp");

        // Export to create a valid artifact.
        crate::service::export::run_export(&src_kit, artifact.to_str().unwrap(), "demo")
            .expect("run_export should succeed");

        // Set up a fresh kit for the import side.
        let (_dst_dir, dst_db) = fresh_db_path();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let dst_kit = rt.block_on(async {
            let config = KitBootstrapConfig::new(dst_db.to_path_buf());
            build_kit(&config).await.expect("build_kit")
        });
        crate::service::runtime::force_init_kit_for_testing(dst_kit);
        let result = rt.block_on(import(
            artifact.to_string_lossy().into_owned(),
            false,
            String::new(),
            String::new(),
        ));
        assert!(
            result.is_ok(),
            "import wrapper should succeed: {:?}",
            result.err()
        );
    }

    // Covers the import wrapper with reindex=false and a nonexistent artifact
    // through the #[forge] wrapper → ApiError conversion path.
    #[serial_test::serial(kit_init)]
    #[cfg(feature = "cli")]
    #[test]
    fn import_wrapper_with_malformed_artifact_returns_api_error() {
        let _guard = KitGuard::new();
        let (dir, db) = fresh_db_path();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let kit = rt.block_on(async {
            let config = KitBootstrapConfig::new(db.to_path_buf());
            build_kit(&config).await.expect("build_kit")
        });
        crate::service::runtime::force_init_kit_for_testing(kit);

        let bad_artifact = dir.path().join("too_small.cnxp");
        std::fs::write(&bad_artifact, b"CNXP").unwrap();

        let result = rt.block_on(import(
            bad_artifact.to_string_lossy().into_owned(),
            false,
            String::new(),
            String::new(),
        ));
        let err = result.expect_err("too-small artifact should error");
        assert!(
            matches!(err, ApiError::InvalidInput { .. }),
            "expected InvalidInput, got {err:?}"
        );
    }
}