leindex 1.6.1

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
//! leedit - Code Editing Engine
//!
//! *Le Edit* (The Editing) - AST-based code editing with tree-sitter and git worktree isolation

#![warn(missing_docs)]
#![warn(unused_extern_crates)]

// Submodules
mod command;
mod engine;
mod history;
mod refactor;

// Re-exports from legraphe
pub use crate::graph::pdg::{Edge, EdgeType, Node, NodeType, ProgramDependenceGraph as PDG};

// Re-exports from lestockage
pub use crate::storage::{Storage, StorageConfig, UniqueProjectId};

// Public API re-exports from command module
pub use command::{
    EditChange, EditCommand, EditPreview, EditRequest, EditResult, EditType, ImpactAnalysis,
    ResolvedEditChange, RiskLevel,
};

// Public API re-exports from engine module
pub(crate) use engine::{atomic_write, atomic_write_async, atomic_write_with_expected_async};
pub use engine::{
    replace_near_definitions, replace_whole_word, Diff, EditEngine, EditError, Impact, Result,
    WorktreeManager, WorktreeSession,
};

// Public API re-exports from history module
pub use history::EditHistory;

// Public API re-exports from refactor module
pub use refactor::Refactor;

// =========================================================================
// Tests
// =========================================================================

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

    fn create_test_pdg() -> PDG {
        PDG::new()
    }

    /// Helper to create a test UniqueProjectId
    fn make_test_id() -> UniqueProjectId {
        UniqueProjectId::new("test_project".to_string(), "abcd1234".to_string(), 0)
    }

    /// Helper to create test storage
    fn make_test_storage() -> Storage {
        Storage::open_with_config(
            ":memory:",
            StorageConfig {
                db_path: ":memory:".to_string(),
                wal_enabled: false,
                cache_size_pages: None,
            },
        )
        .unwrap()
    }

    #[test]
    fn test_edit_request_creation() {
        let project_id = make_test_id();
        let file_path = std::path::PathBuf::from("test.py");
        let changes = vec![EditChange::ReplaceText {
            start: 0,
            end: 10,
            new_text: "new content".to_string(),
        }];

        let request = EditRequest {
            project_id,
            file_path,
            changes,
            preview_only: true,
        };

        assert!(request.preview_only);
        assert_eq!(request.changes.len(), 1);
    }

    #[test]
    fn test_edit_change_replace_text() {
        let change = EditChange::ReplaceText {
            start: 0,
            end: 10,
            new_text: "replacement".to_string(),
        };

        assert!(matches!(change, EditChange::ReplaceText { .. }));
    }

    #[test]
    fn test_edit_change_rename_symbol() {
        let change = EditChange::RenameSymbol {
            old_name: "oldFunc".to_string(),
            new_name: "newFunc".to_string(),
        };

        if let EditChange::RenameSymbol { old_name, new_name } = change {
            assert_eq!(old_name, "oldFunc");
            assert_eq!(new_name, "newFunc");
        } else {
            panic!("Expected RenameSymbol");
        }
    }

    #[test]
    fn test_edit_change_extract_function() {
        let change = EditChange::ExtractFunction {
            start: 10,
            end: 50,
            function_name: "extractedFunc".to_string(),
        };

        assert!(matches!(change, EditChange::ExtractFunction { .. }));
    }

    #[test]
    fn test_edit_change_inline_variable() {
        let change = EditChange::InlineVariable {
            variable_name: "myVar".to_string(),
        };

        assert!(matches!(change, EditChange::InlineVariable { .. }));
    }

    #[test]
    fn test_risk_level_comparison() {
        assert_eq!(RiskLevel::Low, RiskLevel::Low);
        assert_ne!(RiskLevel::Low, RiskLevel::High);
    }

    #[test]
    fn test_edit_history_new() {
        let history = EditHistory::new();
        assert!(history.is_empty());
        assert_eq!(history.current_index(), 0);
    }

    #[test]
    fn test_edit_history_record_command() {
        let mut history = EditHistory::new();
        let project_id = make_test_id();
        let command = EditCommand::Edit {
            project_id,
            file_path: std::path::PathBuf::from("test.py"),
            changes: vec![],
            timestamp: chrono::Utc::now(),
            original_content: None,
            modified_content: None,
        };

        history.record_command(command);
        assert_eq!(history.len(), 1);
        assert_eq!(history.current_index(), 1);
        assert!(!history.is_empty());
    }

    #[test]
    fn test_edit_history_undo() {
        let mut history = EditHistory::new();
        let project_id = make_test_id();
        let command = EditCommand::Edit {
            project_id,
            file_path: std::path::PathBuf::from("test.py"),
            changes: vec![],
            timestamp: chrono::Utc::now(),
            original_content: None,
            modified_content: None,
        };

        history.record_command(command.clone());
        let undone = history.undo();

        assert!(undone.is_some());
        assert_eq!(history.current_index(), 0);
    }

    #[test]
    fn test_edit_history_undo_empty() {
        let mut history = EditHistory::new();
        let result = history.undo();
        assert!(result.is_none());
    }

    #[test]
    fn test_edit_history_redo() {
        let mut history = EditHistory::new();
        let project_id = make_test_id();
        let command = EditCommand::Edit {
            project_id,
            file_path: std::path::PathBuf::from("test.py"),
            changes: vec![],
            timestamp: chrono::Utc::now(),
            original_content: None,
            modified_content: None,
        };

        history.record_command(command.clone());
        history.undo();
        let redone = history.redo();

        assert!(redone.is_some());
        assert_eq!(history.current_index(), 1);
    }

    #[test]
    fn test_edit_history_redo_empty() {
        let mut history = EditHistory::new();
        let result = history.redo();
        assert!(result.is_none());
    }

    #[test]
    fn test_edit_history_rollback_point() {
        let mut history = EditHistory::new();
        let project_id = make_test_id();

        // Add some commands
        for i in 0..3 {
            let command = EditCommand::Edit {
                project_id: project_id.clone(),
                file_path: std::path::PathBuf::from(format!("test{}.py", i)),
                changes: vec![],
                timestamp: chrono::Utc::now(),
                original_content: None,
                modified_content: None,
            };
            history.record_command(command);
        }

        // Create rollback point
        history.create_rollback_point("before_change_3".to_string());
        assert_eq!(history.current_index(), 3);

        // Add more commands
        let command = EditCommand::Edit {
            project_id: project_id.clone(),
            file_path: std::path::PathBuf::from("test3.py"),
            changes: vec![],
            timestamp: chrono::Utc::now(),
            original_content: None,
            modified_content: None,
        };
        history.record_command(command);
        assert_eq!(history.current_index(), 4);

        // Rollback
        let _ = history.rollback("before_change_3");
        assert_eq!(history.current_index(), 3);
    }

    #[test]
    fn test_edit_history_rollback_nonexistent() {
        let mut history = EditHistory::new();
        let result = history.rollback("nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_edit_history_undo_clears_redo_stack() {
        let mut history = EditHistory::new();
        let project_id = make_test_id();

        // Add 3 commands
        for i in 0..3 {
            let command = EditCommand::Edit {
                project_id: project_id.clone(),
                file_path: std::path::PathBuf::from(format!("test{}.py", i)),
                changes: vec![],
                timestamp: chrono::Utc::now(),
                original_content: None,
                modified_content: None,
            };
            history.record_command(command);
        }

        // Undo twice
        history.undo();
        history.undo();
        assert_eq!(history.current_index(), 1);

        // Add a new command - should clear redo stack
        let command = EditCommand::Edit {
            project_id: project_id.clone(),
            file_path: std::path::PathBuf::from("new.py"),
            changes: vec![],
            timestamp: chrono::Utc::now(),
            original_content: None,
            modified_content: None,
        };
        history.record_command(command);

        assert_eq!(history.len(), 2); // Only 2 commands now
        assert_eq!(history.current_index(), 2);
    }

    #[test]
    fn test_worktree_manager_new() {
        let manager = WorktreeManager::new();
        assert_eq!(
            manager.base_path,
            std::path::PathBuf::from("/tmp/leedit-worktrees")
        );
    }

    #[test]
    fn test_impact_analysis_default() {
        let analysis = ImpactAnalysis {
            affected_nodes: vec![],
            affected_files: vec![],
            breaking_changes: vec![],
            risk_level: RiskLevel::Low,
        };

        assert_eq!(analysis.risk_level, RiskLevel::Low);
        assert!(analysis.affected_nodes.is_empty());
    }

    #[test]
    fn test_edit_preview_default() {
        let preview = EditPreview {
            diff: String::new(),
            impact: ImpactAnalysis {
                affected_nodes: vec![],
                affected_files: vec![],
                breaking_changes: vec![],
                risk_level: RiskLevel::Low,
            },
            files_affected: vec![],
        };

        assert!(preview.diff.is_empty());
        assert_eq!(preview.impact.risk_level, RiskLevel::Low);
    }

    #[test]
    fn test_edit_result_default() {
        let result = EditResult {
            success: false,
            changes_applied: 0,
            files_modified: vec![],
            modified_contents: None,
            original_contents: None,
            error: None,
        };

        assert!(!result.success);
        assert_eq!(result.changes_applied, 0);
        assert!(result.files_modified.is_empty());
        assert!(result.error.is_none());
    }

    #[test]
    fn test_edit_result_success() {
        let result = EditResult {
            success: true,
            changes_applied: 5,
            files_modified: vec![std::path::PathBuf::from("test.py")],
            modified_contents: None,
            original_contents: None,
            error: None,
        };

        assert!(result.success);
        assert_eq!(result.changes_applied, 5);
        assert_eq!(result.files_modified.len(), 1);
    }

    #[tokio::test]
    async fn test_edit_engine_creation() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());

        let engine = EditEngine::new(pdg, storage);
        assert!(engine.is_ok());
    }

    #[tokio::test]
    async fn test_edit_engine_preview_edit() {
        let dir = tempfile::tempdir().expect("tempdir");
        let file_path = dir.path().join("test.py");
        std::fs::write(&file_path, b"hello world").expect("write test file");

        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        let project_id = make_test_id();
        let request = EditRequest {
            project_id,
            file_path: file_path.clone(),
            changes: vec![EditChange::ReplaceText {
                start: 0,
                end: 5, // "hello"
                new_text: "goodbye".to_string(),
            }],
            preview_only: true,
        };

        let result = engine.preview_edit(&request).await;
        assert!(
            result.is_ok(),
            "preview_edit should succeed: {:?}",
            result.err()
        );
        let preview = result.unwrap();
        // The edited file is always in affected list
        assert!(!preview.files_affected.is_empty());
        assert!(matches!(preview.impact.risk_level, RiskLevel::Low));
        // Diff should contain some content
        assert!(!preview.diff.is_empty());
    }

    #[tokio::test]
    async fn test_edit_engine_history_state() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        let (index, len) = engine.history_state().await;
        assert_eq!(index, 0);
        assert_eq!(len, 0);
    }

    #[tokio::test]
    async fn test_edit_engine_rollback_point() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        let result = engine.create_rollback_point("test_point".to_string()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_edit_engine_undo_no_history() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        let result = engine.undo().await;
        assert!(result.is_ok());
        let edit_result = result.unwrap();
        assert!(!edit_result.success);
        assert!(edit_result.error.is_some());
    }

    #[tokio::test]
    async fn test_edit_engine_redo_no_history() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        let result = engine.redo().await;
        assert!(result.is_ok());
        let edit_result = result.unwrap();
        assert!(!edit_result.success);
        assert!(edit_result.error.is_some());
    }

    #[tokio::test]
    async fn test_edit_engine_rollback_nonexistent() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        let result = engine.rollback("nonexistent").await;
        assert!(result.is_ok());
        let edit_result = result.unwrap();
        assert!(!edit_result.success);
        assert!(edit_result.error.is_some());
    }

    #[test]
    fn test_edit_command_edit_variant() {
        let project_id = make_test_id();
        let command = EditCommand::Edit {
            project_id,
            file_path: std::path::PathBuf::from("test.py"),
            changes: vec![],
            timestamp: chrono::Utc::now(),
            original_content: None,
            modified_content: None,
        };

        assert!(matches!(command, EditCommand::Edit { .. }));
    }

    #[test]
    fn test_edit_command_rollback_point_variant() {
        let command = EditCommand::RollbackPoint {
            name: "test_point".to_string(),
            timestamp: chrono::Utc::now(),
        };

        assert!(matches!(command, EditCommand::RollbackPoint { .. }));
    }

    #[test]
    fn test_edit_error_display() {
        let error = EditError::FileNotFound(std::path::PathBuf::from("missing.py"));
        let msg = format!("{}", error);
        assert!(msg.contains("missing.py"));
    }

    #[test]
    fn test_edit_error_invalid_range() {
        let error = EditError::InvalidRange {
            start: 10,
            end: 5,
            file: std::path::PathBuf::from("test.py"),
        };
        let msg = format!("{}", error);
        assert!(msg.contains("10-5"));
        assert!(msg.contains("test.py"));
    }

    #[test]
    fn test_edit_error_symbol_not_found() {
        let error = EditError::SymbolNotFound("mySymbol".to_string());
        let msg = format!("{}", error);
        assert!(msg.contains("mySymbol"));
    }

    #[test]
    fn test_edit_change_clone() {
        let change = EditChange::ReplaceText {
            start: 0,
            end: 10,
            new_text: "test".to_string(),
        };
        let cloned = change.clone();
        assert_eq!(change, cloned);
    }

    #[test]
    fn test_edit_change_equality() {
        let change1 = EditChange::ReplaceText {
            start: 0,
            end: 10,
            new_text: "test".to_string(),
        };
        let change2 = EditChange::ReplaceText {
            start: 0,
            end: 10,
            new_text: "test".to_string(),
        };
        assert_eq!(change1, change2);
    }

    #[test]
    fn test_edit_history_default() {
        let history = EditHistory::default();
        assert!(history.is_empty());
    }

    #[test]
    fn test_edit_result_clone() {
        let result = EditResult {
            success: true,
            changes_applied: 1,
            files_modified: vec![std::path::PathBuf::from("test.py")],
            modified_contents: None,
            original_contents: None,
            error: None,
        };
        let cloned = result.clone();
        assert_eq!(result.success, cloned.success);
        assert_eq!(result.changes_applied, cloned.changes_applied);
    }

    #[test]
    fn test_refactor_rename_symbol() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        // Test that rename compiles
        let _result = std::thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(Refactor::rename_symbol(&engine, "old", "new"))
        })
        .join()
        .unwrap();

        // In test environment, just verify no panic
    }

    #[test]
    fn test_refactor_extract_function() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        // Test that extract compiles
        let _result = std::thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(Refactor::extract_function(
                &engine,
                std::path::Path::new("test.py"),
                (0, 10),
                "newFunc",
            ))
        })
        .join()
        .unwrap();

        // In test environment, just verify no panic
    }

    #[test]
    fn test_refactor_inline_variable() {
        let pdg = std::sync::Arc::new(create_test_pdg());
        let storage = std::sync::Arc::new(make_test_storage());
        let engine = EditEngine::new(pdg, storage).unwrap();

        // Test that inline compiles
        let _result = std::thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(Refactor::inline_variable(
                &engine,
                std::path::Path::new("test.py"),
                "myVar",
            ))
        })
        .join()
        .unwrap();

        // In test environment, just verify no panic
    }
}