leindex 1.6.0

LeIndex MCP and semantic code search engine for AI tools and large codebases
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
// PDG Persistence Bridge
//
// *Le Pont* (The Bridge) - Converts between legraphe PDG and lestockage records

use crate::graph::pdg::{
    Edge as PDGEdge, EdgeMetadata as PDGEdgeMetadata, EdgeType as PDGEdgeType, Node as PDGNode,
    NodeId, NodeType as PDGNodeType, ProgramDependenceGraph,
};
use crate::storage::edges::{EdgeMetadata as StorageEdgeMetadata, EdgeType as StorageEdgeType};
use crate::storage::nodes::{NodeRecord, NodeType as StorageNodeType};
use crate::storage::schema::Storage;
use rusqlite::{params, Result as SqliteResult};
use std::collections::HashMap;
use std::sync::Arc;

/// Type alias for node database rows to reduce type complexity
type NodeDbRow = (
    i64,
    String,
    String,
    String,
    String,
    String,
    String,
    Option<i32>,
    String,
    Option<Vec<u8>>,
    Option<i64>,
    Option<i64>,
    Option<i32>,
);

/// Errors that can occur during PDG persistence
#[derive(Debug, thiserror::Error)]
pub enum PdgStoreError {
    /// Error originating from the underlying SQLite database
    #[error("SQLite error: {0}")]
    Sqlite(#[from] rusqlite::Error),

    /// The specified node ID was not found in the database
    #[error("Node not found: {0}")]
    NodeNotFound(i64),

    /// An edge refers to a node that does not exist in the database
    #[error("Edge refers to non-existent node: caller={caller}, callee={callee}")]
    EdgeNodeMissing {
        /// ID of the caller node
        caller: i64,
        /// ID of the callee node
        callee: i64,
    },

    /// Failed to serialize PDG data for storage
    #[error("Serialization error: {0}")]
    Serialization(String),

    /// Failed to deserialize stored data back into a PDG
    #[error("Deserialization error: {0}")]
    Deserialization(String),
}

/// Result type for PDG store operations
pub type Result<T> = std::result::Result<T, PdgStoreError>;

/// Convert legraphe NodeType to lestockage NodeType
fn convert_node_type(node_type: &PDGNodeType) -> StorageNodeType {
    match node_type {
        PDGNodeType::Function => StorageNodeType::Function,
        PDGNodeType::Class => StorageNodeType::Class,
        PDGNodeType::Method => StorageNodeType::Method,
        PDGNodeType::Variable => StorageNodeType::Variable,
        PDGNodeType::Module => StorageNodeType::Module,
        PDGNodeType::External => StorageNodeType::External,
    }
}

/// Convert lestockage NodeType to legraphe NodeType
fn convert_storage_node_type(node_type: &StorageNodeType) -> PDGNodeType {
    match node_type {
        StorageNodeType::Function => PDGNodeType::Function,
        StorageNodeType::Class => PDGNodeType::Class,
        StorageNodeType::Method => PDGNodeType::Method,
        StorageNodeType::Variable => PDGNodeType::Variable,
        StorageNodeType::Module => PDGNodeType::Module,
        StorageNodeType::External => PDGNodeType::External,
    }
}

/// Convert legraphe EdgeType to lestockage EdgeType
fn convert_edge_type(edge_type: &PDGEdgeType) -> StorageEdgeType {
    match edge_type {
        PDGEdgeType::Call => StorageEdgeType::Call,
        PDGEdgeType::DataDependency => StorageEdgeType::DataDependency,
        PDGEdgeType::Inheritance => StorageEdgeType::Inheritance,
        PDGEdgeType::Import => StorageEdgeType::Import,
        PDGEdgeType::Containment => StorageEdgeType::Call, // Map Containment to Call for storage
    }
}

/// Convert lestockage EdgeType to legraphe EdgeType
fn convert_storage_edge_type(edge_type: &StorageEdgeType) -> PDGEdgeType {
    match edge_type {
        StorageEdgeType::Call => PDGEdgeType::Call,
        StorageEdgeType::DataDependency => PDGEdgeType::DataDependency,
        StorageEdgeType::Inheritance => PDGEdgeType::Inheritance,
        StorageEdgeType::Import => PDGEdgeType::Import,
        StorageEdgeType::Containment => PDGEdgeType::Containment,
    }
}

/// Convert legraphe EdgeMetadata to lestockage EdgeMetadata
fn convert_edge_metadata(metadata: &PDGEdgeMetadata) -> StorageEdgeMetadata {
    StorageEdgeMetadata {
        call_count: metadata.call_count,
        variable_name: metadata.variable_name.clone(),
        confidence: metadata.confidence,
    }
}

/// Convert lestockage EdgeMetadata to legraphe EdgeMetadata
fn convert_storage_edge_metadata(metadata: &StorageEdgeMetadata) -> PDGEdgeMetadata {
    PDGEdgeMetadata {
        call_count: metadata.call_count,
        variable_name: metadata.variable_name.clone(),
        confidence: metadata.confidence,
    }
}

/// Save a ProgramDependenceGraph to storage
///
/// This function extracts all nodes and edges from the PDG and persists them
/// to the SQLite database. All previous nodes and edges for the project are
/// replaced with the new PDG data.
///
/// # Arguments
///
/// * `storage` - Mutable reference to the storage backend
/// * `project_id` - Project identifier for the PDG
/// * `pdg` - Reference to the ProgramDependenceGraph to save
///
/// # Returns
///
/// `Ok(())` if successful, `Err(PdgStoreError)` if an error occurs
///
/// # Example
///
/// ```ignore
/// let pdg = extract_pdg_from_signatures(signatures, source, "test.rs");
/// save_pdg(&mut storage, "my_project", &pdg)?;
/// ```
pub fn save_pdg(
    storage: &mut Storage,
    project_id: &str,
    pdg: &ProgramDependenceGraph,
) -> Result<()> {
    let tx = storage.conn_mut().transaction()?;

    // Delete existing edges for this project first (to avoid foreign key constraints)
    tx.execute(
        "DELETE FROM intel_edges WHERE caller_id IN (SELECT id FROM intel_nodes WHERE project_id = ?1)",
        params![project_id],
    )?;

    // Then delete existing nodes for this project
    tx.execute(
        "DELETE FROM intel_nodes WHERE project_id = ?1",
        params![project_id],
    )?;

    // Insert all nodes
    let mut node_id_map: HashMap<NodeId, i64> = HashMap::new();

    for node_idx in pdg.node_indices() {
        let pdg_node = pdg
            .get_node(node_idx)
            .ok_or_else(|| PdgStoreError::Serialization("Missing node data".to_string()))?;

        // Note: Embeddings are now externalized to EmbeddingStore, not stored in Node
        // They are persisted separately if needed
        let record = NodeRecord {
            id: None,
            project_id: project_id.to_string(),
            file_path: pdg_node.file_path.to_string(),
            node_id: pdg_node.id.clone(),
            symbol_name: pdg_node.name.clone(),
            qualified_name: pdg_node
                .id
                .split(':')
                .next_back()
                .unwrap_or(&pdg_node.id)
                .to_string(),
            language: pdg_node.language.clone(),
            node_type: convert_node_type(&pdg_node.node_type),
            signature: None, // Could be populated from node content
            complexity: Some(pdg_node.complexity as i32),
            content_hash: blake3::hash(pdg_node.id.as_bytes()).to_hex().to_string(),
            embedding: None, // Embeddings externalized to EmbeddingStore
            byte_range_start: Some(pdg_node.byte_range.0 as i64),
            byte_range_end: Some(pdg_node.byte_range.1 as i64),
            embedding_format: Some(0),
        };

        let db_id: i64 = tx.query_row(
            "INSERT INTO intel_nodes (project_id, file_path, node_id, symbol_name, qualified_name, language, node_type, signature, complexity, content_hash, embedding, byte_range_start, byte_range_end, created_at, updated_at, embedding_format)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
             RETURNING id",
            params![
                record.project_id,
                record.file_path,
                record.node_id,
                record.symbol_name,
                record.qualified_name,
                record.language,
                record.node_type.as_str(),
                record.signature,
                record.complexity,
                record.content_hash,
                record.embedding.as_deref(),
                record.byte_range_start,
                record.byte_range_end,
                chrono::Utc::now().timestamp(),
                chrono::Utc::now().timestamp(),
                record.embedding_format,
            ],
            |row| row.get(0),
        )?;

        node_id_map.insert(node_idx, db_id);
    }

    // Insert all edges
    for edge_idx in pdg.edge_indices() {
        let (source, target) = pdg
            .edge_endpoints(edge_idx)
            .ok_or_else(|| PdgStoreError::Serialization("Edge has no endpoints".to_string()))?;

        let pdg_edge = pdg
            .get_edge(edge_idx)
            .ok_or_else(|| PdgStoreError::Serialization("Missing edge data".to_string()))?;

        let caller_id =
            *node_id_map
                .get(&source)
                .ok_or_else(|| PdgStoreError::EdgeNodeMissing {
                    caller: source.index() as i64,
                    callee: target.index() as i64,
                })?;

        let callee_id =
            *node_id_map
                .get(&target)
                .ok_or_else(|| PdgStoreError::EdgeNodeMissing {
                    caller: source.index() as i64,
                    callee: target.index() as i64,
                })?;

        let metadata = convert_edge_metadata(&pdg_edge.metadata);
        let metadata_json = serde_json::to_string(&metadata)
            .map_err(|e| PdgStoreError::Serialization(e.to_string()))?;

        tx.execute(
            "INSERT INTO intel_edges (caller_id, callee_id, edge_type, metadata)
                 VALUES (?1, ?2, ?3, ?4)
                 ON CONFLICT DO UPDATE SET metadata = excluded.metadata",
            params![
                caller_id,
                callee_id,
                convert_edge_type(&pdg_edge.edge_type).as_str(),
                metadata_json,
            ],
        )?;
    }

    tx.commit()?;
    Ok(())
}

/// Load a ProgramDependenceGraph from storage
///
/// This function reconstructs a PDG from the SQLite database by loading all
/// nodes and edges for a given project. It rebuilds the StableGraph structure
/// along with the symbol_index and file_index.
///
/// # Arguments
///
/// * `storage` - Reference to the storage backend
/// * `project_id` - Project identifier to load
///
/// # Returns
///
/// `Ok(ProgramDependenceGraph)` if successful, `Err(PdgStoreError)` if an error occurs
///
/// # Example
///
/// ```ignore
/// let pdg = load_pdg(&storage, "my_project")?;
/// println!("Loaded {} nodes and {} edges", pdg.node_count(), pdg.edge_count());
/// ```
pub fn load_pdg(storage: &Storage, project_id: &str) -> Result<ProgramDependenceGraph> {
    let mut pdg = ProgramDependenceGraph::new();
    let mut db_id_to_node_id: HashMap<i64, NodeId> = HashMap::new();

    // Load all nodes for the project
    let mut nodes_stmt = storage.conn().prepare(
        "SELECT id, file_path, node_id, symbol_name, qualified_name, language, node_type, complexity, content_hash, embedding, byte_range_start, byte_range_end, embedding_format
         FROM intel_nodes WHERE project_id = ?1"
    )?;

    let node_rows: Vec<NodeDbRow> = nodes_stmt
        .query_map(params![project_id], |row| {
            Ok((
                row.get::<_, i64>(0)?,             // id
                row.get::<_, String>(1)?,          // file_path
                row.get::<_, String>(2)?,          // node_id
                row.get::<_, String>(3)?,          // symbol_name
                row.get::<_, String>(4)?,          // qualified_name
                row.get::<_, String>(5)?,          // language
                row.get::<_, String>(6)?,          // node_type
                row.get::<_, Option<i32>>(7)?,     // complexity
                row.get::<_, String>(8)?,          // content_hash
                row.get::<_, Option<Vec<u8>>>(9)?, // embedding
                row.get::<_, Option<i64>>(10)?,    // byte_range_start
                row.get::<_, Option<i64>>(11)?,    // byte_range_end
                row.get::<_, Option<i32>>(12)?,    // embedding_format
            ))
        })?
        .collect::<SqliteResult<Vec<_>>>()?;

    for (
        db_id,
        file_path,
        node_id_str,
        symbol_name,
        _qualified_name,
        language,
        node_type_str,
        complexity,
        _content_hash,
        _embedding_blob,
        start,
        end,
        _embedding_format,
    ) in node_rows
    {
        let node_type = StorageNodeType::from_str_name(&node_type_str).ok_or_else(|| {
            PdgStoreError::Deserialization(format!("Invalid node type: {}", node_type_str))
        })?;

        let pdg_node = PDGNode {
            id: node_id_str,
            node_type: convert_storage_node_type(&node_type),
            name: symbol_name,
            file_path: Arc::from(file_path),
            byte_range: (start.unwrap_or(0) as usize, end.unwrap_or(0) as usize),
            complexity: complexity.unwrap_or(0) as u32,
            language,
        };

        let node_id = pdg.add_node(pdg_node);
        db_id_to_node_id.insert(db_id, node_id);
    }

    // Load all edges for the project using a JOIN query
    let mut edges_stmt = storage.conn().prepare(
        "SELECT e.caller_id, e.callee_id, e.edge_type, e.metadata
         FROM intel_edges e
         INNER JOIN intel_nodes n1 ON e.caller_id = n1.id
         INNER JOIN intel_nodes n2 ON e.callee_id = n2.id
         WHERE n1.project_id = ?1 AND n2.project_id = ?1",
    )?;

    let edge_rows: Vec<(i64, i64, String, Option<String>)> = edges_stmt
        .query_map(params![project_id], |row| {
            Ok((
                row.get::<_, i64>(0)?,            // caller_id
                row.get::<_, i64>(1)?,            // callee_id
                row.get::<_, String>(2)?,         // edge_type
                row.get::<_, Option<String>>(3)?, // metadata
            ))
        })?
        .collect::<SqliteResult<Vec<_>>>()?;

    for (caller_id, callee_id, edge_type_str, metadata_json) in edge_rows {
        let caller_node_id = *db_id_to_node_id
            .get(&caller_id)
            .ok_or_else(|| PdgStoreError::NodeNotFound(caller_id))?;

        let callee_node_id = *db_id_to_node_id
            .get(&callee_id)
            .ok_or_else(|| PdgStoreError::NodeNotFound(callee_id))?;

        let edge_type = StorageEdgeType::from_str_name(&edge_type_str).ok_or_else(|| {
            PdgStoreError::Deserialization(format!("Invalid edge type: {}", edge_type_str))
        })?;

        let metadata = match metadata_json.as_deref() {
            Some(json) => serde_json::from_str(json).map_err(|e| {
                PdgStoreError::Deserialization(format!("Invalid edge metadata: {}", e))
            })?,
            None => StorageEdgeMetadata {
                call_count: None,
                variable_name: None,
                confidence: None,
            },
        };

        let pdg_edge = PDGEdge {
            edge_type: convert_storage_edge_type(&edge_type),
            metadata: convert_storage_edge_metadata(&metadata),
        };

        pdg.add_edge(caller_node_id, callee_node_id, pdg_edge);
    }

    Ok(pdg)
}

/// Check if a PDG exists for a project
///
/// # Arguments
///
/// * `storage` - Reference to the storage backend
/// * `project_id` - Project identifier to check
///
/// # Returns
///
/// `true` if the project has at least one node, `false` otherwise
pub fn pdg_exists(storage: &Storage, project_id: &str) -> SqliteResult<bool> {
    let count: i64 = storage.conn().query_row(
        "SELECT COUNT(*) FROM intel_nodes WHERE project_id = ?1",
        params![project_id],
        |row| row.get(0),
    )?;
    Ok(count > 0)
}

/// Delete a PDG from storage
pub fn delete_pdg(storage: &mut Storage, project_id: &str) -> SqliteResult<()> {
    // Delete edges first
    storage.conn().execute(
        "DELETE FROM intel_edges WHERE caller_id IN (SELECT id FROM intel_nodes WHERE project_id = ?1)",
        params![project_id],
    )?;

    // Then delete nodes
    storage.conn().execute(
        "DELETE FROM intel_nodes WHERE project_id = ?1",
        params![project_id],
    )?;

    // Delete indexed files records
    storage.conn().execute(
        "DELETE FROM indexed_files WHERE project_id = ?1",
        params![project_id],
    )?;

    Ok(())
}

/// Delete nodes and edges for a specific file in a project
pub fn delete_file_data(
    storage: &mut Storage,
    project_id: &str,
    file_path: &str,
) -> SqliteResult<()> {
    // Delete edges where caller or callee belongs to this file
    storage.conn().execute(
        "DELETE FROM intel_edges WHERE 
         caller_id IN (SELECT id FROM intel_nodes WHERE project_id = ?1 AND file_path = ?2) OR
         callee_id IN (SELECT id FROM intel_nodes WHERE project_id = ?1 AND file_path = ?2)",
        params![project_id, file_path],
    )?;

    // Delete nodes for this file
    storage.conn().execute(
        "DELETE FROM intel_nodes WHERE project_id = ?1 AND file_path = ?2",
        params![project_id, file_path],
    )?;

    // Delete indexed file record
    storage.conn().execute(
        "DELETE FROM indexed_files WHERE project_id = ?1 AND file_path = ?2",
        params![project_id, file_path],
    )?;

    Ok(())
}

/// Get all indexed files for a project with their hashes
pub fn get_indexed_files(
    storage: &Storage,
    project_id: &str,
) -> SqliteResult<HashMap<String, String>> {
    let mut stmt = storage
        .conn()
        .prepare("SELECT file_path, file_hash FROM indexed_files WHERE project_id = ?1")?;

    let rows = stmt.query_map(params![project_id], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
    })?;

    let mut result = HashMap::new();
    for row in rows {
        let (path, hash) = row?;
        result.insert(path, hash);
    }

    Ok(result)
}

/// Check if any indexed files exist for a project (lightweight query)
pub fn has_indexed_files(storage: &Storage, project_id: &str) -> bool {
    storage
        .conn()
        .query_row(
            "SELECT COUNT(*) FROM indexed_files WHERE project_id = ?1 LIMIT 1",
            params![project_id],
            |row| row.get::<_, i64>(0),
        )
        .unwrap_or(0)
        > 0
}

/// Update indexed file record
pub fn update_indexed_file(
    storage: &mut Storage,
    project_id: &str,
    file_path: &str,
    hash: &str,
) -> SqliteResult<()> {
    storage.conn().execute(
        "INSERT INTO indexed_files (file_path, project_id, file_hash, last_indexed)
         VALUES (?1, ?2, ?3, ?4)
         ON CONFLICT(file_path) DO UPDATE SET file_hash = ?3, last_indexed = ?4",
        params![file_path, project_id, hash, chrono::Utc::now().timestamp()],
    )?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::schema::Storage;
    use tempfile::NamedTempFile;

    fn create_test_pdg() -> ProgramDependenceGraph {
        let mut pdg = ProgramDependenceGraph::new();

        let n1 = pdg.add_node(PDGNode {
            id: "func1".to_string(),
            node_type: PDGNodeType::Function,
            name: "func1".to_string(),
            file_path: Arc::from("test.rs"),
            byte_range: (0, 100),
            complexity: 5,
            language: "rust".to_string(),
        });

        let n2 = pdg.add_node(PDGNode {
            id: "func2".to_string(),
            node_type: PDGNodeType::Function,
            name: "func2".to_string(),
            file_path: Arc::from("test.rs"),
            byte_range: (100, 200),
            complexity: 3,
            language: "rust".to_string(),
        });

        pdg.add_edge(
            n1,
            n2,
            PDGEdge {
                edge_type: PDGEdgeType::Call,
                metadata: PDGEdgeMetadata {
                    call_count: Some(5),
                    variable_name: None,
                    confidence: None,
                },
            },
        );

        pdg
    }

    #[test]
    fn test_save_and_load_pdg() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut storage = Storage::open(temp_file.path()).unwrap();

        let pdg = create_test_pdg();
        save_pdg(&mut storage, "test_project", &pdg).unwrap();

        assert!(pdg_exists(&storage, "test_project").unwrap());

        let loaded = load_pdg(&storage, "test_project").unwrap();
        assert_eq!(loaded.node_count(), 2);
        assert_eq!(loaded.edge_count(), 1);

        let func1 = loaded.find_by_symbol("func1").unwrap();
        let node1 = loaded.get_node(func1).unwrap();
        assert_eq!(node1.complexity, 5);
    }

    #[test]
    fn test_save_pdg_replaces_existing() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut storage = Storage::open(temp_file.path()).unwrap();

        let pdg1 = create_test_pdg();
        save_pdg(&mut storage, "test_project", &pdg1).unwrap();
        assert_eq!(load_pdg(&storage, "test_project").unwrap().node_count(), 2);

        let mut pdg2 = ProgramDependenceGraph::new();
        pdg2.add_node(PDGNode {
            id: "new_func".to_string(),
            node_type: PDGNodeType::Function,
            name: "new_func".to_string(),
            file_path: Arc::from("new.rs"),
            byte_range: (0, 50),
            complexity: 1,
            language: "rust".to_string(),
        });

        save_pdg(&mut storage, "test_project", &pdg2).unwrap();
        assert_eq!(load_pdg(&storage, "test_project").unwrap().node_count(), 1);
    }

    #[test]
    fn test_load_nonexistent_project() {
        let temp_file = NamedTempFile::new().unwrap();
        let storage = Storage::open(temp_file.path()).unwrap();

        let loaded = load_pdg(&storage, "nonexistent").unwrap();
        assert_eq!(loaded.node_count(), 0);
        assert_eq!(loaded.edge_count(), 0);
    }

    #[test]
    fn test_delete_pdg() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut storage = Storage::open(temp_file.path()).unwrap();

        let pdg = create_test_pdg();
        save_pdg(&mut storage, "test_project", &pdg).unwrap();
        assert!(pdg_exists(&storage, "test_project").unwrap());

        delete_pdg(&mut storage, "test_project").unwrap();
        assert!(!pdg_exists(&storage, "test_project").unwrap());
    }

    #[test]
    fn test_convert_node_types() {
        assert_eq!(
            convert_node_type(&PDGNodeType::Function),
            StorageNodeType::Function
        );
        assert_eq!(
            convert_node_type(&PDGNodeType::Class),
            StorageNodeType::Class
        );
        assert_eq!(
            convert_node_type(&PDGNodeType::Method),
            StorageNodeType::Method
        );
        assert_eq!(
            convert_node_type(&PDGNodeType::Variable),
            StorageNodeType::Variable
        );
        assert_eq!(
            convert_node_type(&PDGNodeType::Module),
            StorageNodeType::Module
        );

        assert_eq!(
            convert_storage_node_type(&StorageNodeType::Function),
            PDGNodeType::Function
        );
        assert_eq!(
            convert_storage_node_type(&StorageNodeType::Class),
            PDGNodeType::Class
        );
        assert_eq!(
            convert_storage_node_type(&StorageNodeType::Method),
            PDGNodeType::Method
        );
        assert_eq!(
            convert_storage_node_type(&StorageNodeType::Variable),
            PDGNodeType::Variable
        );
        assert_eq!(
            convert_storage_node_type(&StorageNodeType::Module),
            PDGNodeType::Module
        );

        // External node type round-trip
        assert_eq!(
            convert_node_type(&PDGNodeType::External),
            StorageNodeType::External
        );
        assert_eq!(
            convert_storage_node_type(&StorageNodeType::External),
            PDGNodeType::External
        );
    }

    #[test]
    fn test_convert_edge_types() {
        assert_eq!(convert_edge_type(&PDGEdgeType::Call), StorageEdgeType::Call);
        assert_eq!(
            convert_edge_type(&PDGEdgeType::DataDependency),
            StorageEdgeType::DataDependency
        );
        assert_eq!(
            convert_edge_type(&PDGEdgeType::Inheritance),
            StorageEdgeType::Inheritance
        );
        assert_eq!(
            convert_edge_type(&PDGEdgeType::Import),
            StorageEdgeType::Import
        );

        assert_eq!(
            convert_storage_edge_type(&StorageEdgeType::Call),
            PDGEdgeType::Call
        );
        assert_eq!(
            convert_storage_edge_type(&StorageEdgeType::DataDependency),
            PDGEdgeType::DataDependency
        );
        assert_eq!(
            convert_storage_edge_type(&StorageEdgeType::Inheritance),
            PDGEdgeType::Inheritance
        );
        assert_eq!(
            convert_storage_edge_type(&StorageEdgeType::Import),
            PDGEdgeType::Import
        );
    }

    #[test]
    fn test_edge_metadata_conversion() {
        let pdg_meta = PDGEdgeMetadata {
            call_count: Some(42),
            variable_name: Some("x".to_string()),
            confidence: None,
        };

        let storage_meta = convert_edge_metadata(&pdg_meta);
        assert_eq!(storage_meta.call_count, Some(42));
        assert_eq!(storage_meta.variable_name, Some("x".to_string()));

        let converted_back = convert_storage_edge_metadata(&storage_meta);
        assert_eq!(converted_back.call_count, Some(42));
        assert_eq!(converted_back.variable_name, Some("x".to_string()));
    }

    #[test]
    fn test_save_pdg_with_all_edge_types() {
        let temp_file = NamedTempFile::new().unwrap();
        let mut storage = Storage::open(temp_file.path()).unwrap();

        let mut pdg = ProgramDependenceGraph::new();

        let n1 = pdg.add_node(PDGNode {
            id: "child".to_string(),
            node_type: PDGNodeType::Class,
            name: "Child".to_string(),
            file_path: Arc::from("test.rs"),
            byte_range: (0, 50),
            complexity: 1,
            language: "rust".to_string(),
        });

        let n2 = pdg.add_node(PDGNode {
            id: "parent".to_string(),
            node_type: PDGNodeType::Class,
            name: "Parent".to_string(),
            file_path: Arc::from("test.rs"),
            byte_range: (50, 100),
            complexity: 1,
            language: "rust".to_string(),
        });

        let n3 = pdg.add_node(PDGNode {
            id: "data_user".to_string(),
            node_type: PDGNodeType::Function,
            name: "data_user".to_string(),
            file_path: Arc::from("test.rs"),
            byte_range: (100, 150),
            complexity: 1,
            language: "rust".to_string(),
        });

        pdg.add_edge(
            n1,
            n2,
            PDGEdge {
                edge_type: PDGEdgeType::Inheritance,
                metadata: PDGEdgeMetadata {
                    call_count: None,
                    variable_name: None,
                    confidence: None,
                },
            },
        );

        pdg.add_edge(
            n3,
            n1,
            PDGEdge {
                edge_type: PDGEdgeType::DataDependency,
                metadata: PDGEdgeMetadata {
                    call_count: None,
                    variable_name: Some("child_instance".to_string()),
                    confidence: None,
                },
            },
        );

        save_pdg(&mut storage, "test_project", &pdg).unwrap();

        let loaded = load_pdg(&storage, "test_project").unwrap();
        assert_eq!(loaded.node_count(), 3);
        assert_eq!(loaded.edge_count(), 2);

        // Verify edges by checking connectivity
        let child_id = loaded.find_by_symbol("child").unwrap();
        let parent_id = loaded.find_by_symbol("parent").unwrap();
        let data_user_id = loaded.find_by_symbol("data_user").unwrap();

        // Child should have Parent as neighbor (inheritance)
        let child_neighbors = loaded.neighbors(child_id);
        assert!(child_neighbors.contains(&parent_id));

        // data_user should have Child as neighbor (data dependency)
        let data_user_neighbors = loaded.neighbors(data_user_id);
        assert!(data_user_neighbors.contains(&child_id));
    }
}