leindex 2.1.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
use super::services_commands::service_row_state;
use super::*;

#[tokio::test]
async fn test_standalone_system_one_reaches_wizard_without_neural_flags() {
    let options = crate::cli::leindex::setup::SetupOptions {
        system_one: true,
        ..Default::default()
    };
    let error = cmd_setup_impl(false, false, false, None, false, false, false, options)
        .await
        .unwrap_err()
        .to_string();
    assert!(error.contains("requires a terminal"), "{error}");
    assert!(!error.contains("NoFlags"), "{error}");
}

#[test]
fn test_service_row_state_requires_http_health() {
    let mut status = crate::services::ServiceStatus {
        name: "test".into(),
        pid: None,
        port_open: true,
        http_ready: false,
        endpoint: "http://127.0.0.1:8181".into(),
        model: None,
        served_model: None,
        auto_start: false,
    };
    assert_eq!(service_row_state(&status), "down");
    status.pid = Some(123);
    assert_eq!(service_row_state(&status), "starting");
    status.http_ready = true;
    assert_eq!(service_row_state(&status), "up");
}

#[test]
fn test_cli_parsing() {
    let cli = Cli::try_parse_from(["leindex", "index", "/path/to/project"]).unwrap();
    assert!(matches!(cli.command, Some(Commands::Index { .. })));
}

#[test]
fn test_mcp_command_parsing() {
    let cli = Cli::try_parse_from(["leindex", "mcp"]).unwrap();
    assert!(matches!(cli.command, Some(Commands::Mcp { .. })));
}

#[test]
fn test_stdio_flag_parsing() {
    let cli = Cli::try_parse_from(["leindex", "--stdio"]).unwrap();
    assert!(cli.stdio);
}

#[test]
fn test_search_command() {
    let cli = Cli::try_parse_from(["leindex", "search", "test query"]).unwrap();
    match cli.command {
        Some(Commands::Search { query, top_k, .. }) => {
            assert_eq!(query, "test query");
            assert_eq!(top_k, 10);
        }
        _ => panic!("Expected Search command"),
    }
}

#[test]
fn test_phase_command_parsing() {
    let cli = Cli::try_parse_from(["leindex", "phase", "--phase", "2", "--mode", "ultra"]).unwrap();
    match cli.command {
        Some(Commands::Phase {
            phase, all, mode, ..
        }) => {
            assert_eq!(phase, Some(2));
            assert!(!all);
            assert_eq!(mode, "ultra");
        }
        _ => panic!("Expected Phase command"),
    }
}

#[test]
fn test_dashboard_command_parsing() {
    let cli = Cli::try_parse_from(["leindex", "dashboard"]).unwrap();
    match cli.command {
        Some(Commands::Dashboard { port, prod }) => {
            assert_eq!(port, 5173);
            assert!(!prod);
        }
        _ => panic!("Expected Dashboard command"),
    }
}

#[test]
fn test_dashboard_command_with_port() {
    let cli = Cli::try_parse_from(["leindex", "dashboard", "--port", "3000"]).unwrap();
    match cli.command {
        Some(Commands::Dashboard { port, prod }) => {
            assert_eq!(port, 3000);
            assert!(!prod);
        }
        _ => panic!("Expected Dashboard command"),
    }
}

#[test]
fn test_dashboard_command_prod() {
    let cli = Cli::try_parse_from(["leindex", "dashboard", "--prod"]).unwrap();
    match cli.command {
        Some(Commands::Dashboard { port, prod }) => {
            assert_eq!(port, 5173);
            assert!(prod);
        }
        _ => panic!("Expected Dashboard command"),
    }
}

#[test]
fn test_tools_help_command_parsing() {
    let cli = Cli::try_parse_from(["leindex", "tools", "help", "project_map"]).unwrap();
    match cli.command {
        Some(Commands::Tools {
            command: ToolCommands::Inspect { name },
        }) => assert_eq!(name, "project_map"),
        _ => panic!("Expected tools help command"),
    }
}

#[test]
fn test_tools_run_command_parsing() {
    let cli = Cli::try_parse_from([
        "leindex",
        "tools",
        "run",
        "project_map",
        "--args",
        "{\"depth\":1}",
        "--set",
        "include_symbols=true",
    ])
    .unwrap();

    match cli.command {
        Some(Commands::Tools {
            command:
                ToolCommands::Run {
                    name,
                    args_json,
                    set,
                },
        }) => {
            assert_eq!(name, "project_map");
            assert_eq!(args_json, "{\"depth\":1}");
            assert_eq!(set, vec!["include_symbols=true"]);
        }
        _ => panic!("Expected tools run command"),
    }
}

#[test]
fn test_find_tool_handler_accepts_short_and_full_names() {
    assert!(find_tool_handler("LeIndex [Project Map]").is_some());
    assert!(find_tool_handler("project_map").is_some());
    assert!(find_tool_handler("project-map").is_some());
}

#[test]
fn test_cleanup_command_parsing() {
    let cli = Cli::try_parse_from(["leindex", "cleanup"]).unwrap();
    match cli.command {
        Some(Commands::Cleanup {
            max_age_days,
            dry_run,
            stale_daemons,
            store,
        }) => {
            assert_eq!(max_age_days, 7);
            assert!(!dry_run);
            assert!(!stale_daemons);
            assert!(!store);
        }
        _ => panic!("Expected Cleanup command"),
    }
}

#[test]
fn test_cleanup_command_with_flags() {
    let cli = Cli::try_parse_from([
        "leindex",
        "cleanup",
        "--max-age-days",
        "14",
        "--dry-run",
        "--stale-daemons",
    ])
    .unwrap();
    match cli.command {
        Some(Commands::Cleanup {
            max_age_days,
            dry_run,
            stale_daemons,
            store,
        }) => {
            assert_eq!(max_age_days, 14);
            assert!(dry_run);
            assert!(stale_daemons);
            assert!(!store);
        }
        _ => panic!("Expected Cleanup command"),
    }
}

#[test]
fn test_memory_report_flag_parsing() {
    // VAL-MEASURE-020: --memory-report is an opt-in CLI surface
    let cli = Cli::try_parse_from([
        "leindex",
        "--memory-report",
        "/tmp/mem-report.json",
        "index",
        "/tmp/project",
    ])
    .unwrap();
    assert_eq!(
        cli.memory_report,
        Some(PathBuf::from("/tmp/mem-report.json"))
    );
    assert!(matches!(cli.command, Some(Commands::Index { .. })));
}

#[test]
fn test_memory_report_flag_absent_by_default() {
    let cli = Cli::try_parse_from(["leindex", "index", "/tmp/project"]).unwrap();
    assert!(cli.memory_report.is_none());
}

#[test]
fn test_retention_command_parsing() {
    // WS4 Task 9: `leindex retention --report` is registered.
    let cli = Cli::try_parse_from(["leindex", "retention", "--report"]).unwrap();
    match cli.command {
        Some(Commands::Retention { report, .. }) => {
            assert!(report, "--report must be parsed");
        }
        _ => panic!("Expected Retention command"),
    }
}

#[test]
fn test_retention_command_without_report_flag() {
    let cli = Cli::try_parse_from(["leindex", "retention"]).unwrap();
    match cli.command {
        Some(Commands::Retention { report, .. }) => {
            assert!(!report, "report flag defaults to false");
        }
        _ => panic!("Expected Retention command"),
    }
}

#[test]
fn test_retention_gc_command_parsing() {
    let cli =
        Cli::try_parse_from(["leindex", "retention", "--gc", "--max-generations", "3"]).unwrap();
    match cli.command {
        Some(Commands::Retention {
            gc,
            max_generations,
            dry_run,
            ..
        }) => {
            assert!(gc, "--gc must be parsed");
            assert_eq!(max_generations, 3, "--max-generations must be parsed");
            assert!(!dry_run, "dry_run defaults to false");
        }
        _ => panic!("Expected Retention command"),
    }
}

#[test]
fn test_setup_command_parsing() {
    // VAL-SETUP-001: setup command is registered
    let cli = Cli::try_parse_from(["leindex", "setup", "--neural", "--cpu"]).unwrap();
    match cli.command {
        Some(Commands::Setup {
            neural,
            no_neural,
            cpu,
            gpu,
            check,
            warmup: _,
            remote_gemma: _,
            options: _,
        }) => {
            assert!(neural);
            assert!(!no_neural);
            assert!(cpu);
            assert!(gpu.is_none());
            assert!(!check);
        }
        _ => panic!("Expected Setup command"),
    }
}

#[test]
fn test_setup_command_gpu_amd() {
    let cli = Cli::try_parse_from(["leindex", "setup", "--neural", "--gpu", "amd"]).unwrap();
    match cli.command {
        Some(Commands::Setup {
            neural, cpu, gpu, ..
        }) => {
            assert!(neural);
            assert!(!cpu);
            assert_eq!(gpu.as_deref(), Some("amd"));
        }
        _ => panic!("Expected Setup command"),
    }
}

#[test]
fn test_setup_command_gpu_nvidia() {
    let cli = Cli::try_parse_from(["leindex", "setup", "--neural", "--gpu", "nvidia"]).unwrap();
    match cli.command {
        Some(Commands::Setup {
            neural, cpu, gpu, ..
        }) => {
            assert!(neural);
            assert!(!cpu);
            assert_eq!(gpu.as_deref(), Some("nvidia"));
        }
        _ => panic!("Expected Setup command"),
    }
}

#[test]
fn test_setup_command_no_neural() {
    // VAL-SETUP-013: --no-neural flag
    let cli = Cli::try_parse_from(["leindex", "setup", "--no-neural"]).unwrap();
    match cli.command {
        Some(Commands::Setup {
            neural,
            no_neural,
            cpu,
            gpu,
            check,
            warmup: _,
            remote_gemma: _,
            options: _,
        }) => {
            assert!(!neural);
            assert!(no_neural);
            assert!(!cpu);
            assert!(gpu.is_none());
            assert!(!check);
        }
        _ => panic!("Expected Setup command"),
    }
}

#[test]
fn test_config_command_parsing() {
    // `leindex config <action>` parses into the setup_config subcommand
    // surface; dispatch happens in run().
    let cli = Cli::try_parse_from(["leindex", "config", "show"]).unwrap();
    assert!(matches!(
        cli.command,
        Some(Commands::Config {
            action: crate::cli::leindex::setup_config::ConfigAction::Show
        })
    ));

    let cli = Cli::try_parse_from(["leindex", "config", "set", "search.search_mode", "\"text\""])
        .unwrap();
    match cli.command {
        Some(Commands::Config {
            action: crate::cli::leindex::setup_config::ConfigAction::Set { key, value },
        }) => {
            assert_eq!(key, "search.search_mode");
            assert_eq!(value, "\"text\"");
        }
        _ => panic!("Expected Config Set command"),
    }
}

#[test]
fn test_setup_command_check() {
    // VAL-SETUP-014: --check flag
    let cli = Cli::try_parse_from(["leindex", "setup", "--check"]).unwrap();
    match cli.command {
        Some(Commands::Setup { check, .. }) => assert!(check),
        _ => panic!("Expected Setup command"),
    }
}

#[test]
fn test_setup_command_remote_gemma() {
    // --remote-gemma parses standalone; the neural implication is applied in
    // cmd_setup_impl (neural || remote_gemma), not by clap.
    let cli = Cli::try_parse_from(["leindex", "setup", "--remote-gemma"]).unwrap();
    match cli.command {
        Some(Commands::Setup {
            neural,
            remote_gemma,
            ..
        }) => {
            assert!(remote_gemma);
            assert!(!neural); // parse-level; implied at resolve time
        }
        _ => panic!("Expected Setup command"),
    }
}

#[test]
fn test_setup_command_neural_gpu_conflict_rejected() {
    // VAL-SETUP-015: conflicting flags produce error
    let result = Cli::try_parse_from(["leindex", "setup", "--neural", "--cpu", "--gpu", "amd"]);
    assert!(result.is_err());
}

#[test]
fn test_setup_command_neural_no_neural_conflict_rejected() {
    // VAL-SETUP-015: --neural + --no-neural is a conflict
    let result = Cli::try_parse_from(["leindex", "setup", "--neural", "--no-neural"]);
    assert!(result.is_err());
}

#[test]
fn test_setup_help_is_valid() {
    // VAL-SETUP-001: leindex setup --help exits 0
    let result = Cli::try_parse_from(["leindex", "setup", "--help"]);
    assert!(result.is_err()); // clap exits with error for --help
    let err = result.unwrap_err();
    assert!(matches!(err.kind(), ErrorKind::DisplayHelp));
}

// -----------------------------------------------------------------------
// format_analysis_output (VAL-OUT-001..006)
// -----------------------------------------------------------------------

fn mock_search_result(
    rank: usize,
    file_path: &str,
    symbol: &str,
    score: f32,
) -> crate::search::SearchResult {
    crate::search::SearchResult {
        rank,
        node_id: format!("node-{rank}"),
        file_path: file_path.to_string(),
        symbol_name: symbol.to_string(),
        symbol_type: Some("function".to_string()),
        signature: None,
        complexity: 1,
        caller_count: None,
        dependency_count: None,
        language: "rust".to_string(),
        score: crate::search::Score {
            overall: score,
            tfidf: 0.0,
            neural: 0.0,
            structural: 0.0,
            text_match: 0.0,
            fragment: 0.0,
        },
        context: None,
        byte_range: (0, 0),
        fragment_byte_range: None,
        line_number: Some(10 + rank),
    }
}

fn mock_analysis_result(
    results: Vec<crate::search::SearchResult>,
) -> crate::cli::leindex::AnalysisResult {
    crate::cli::leindex::AnalysisResult {
        query: "test query".to_string(),
        results,
        // > 300 chars so the context section exercises the expanded budget.
        context: Some("context line\n".repeat(60)),
        tokens_used: 500,
        processing_time_ms: 12,
    }
}

#[test]
fn test_analysis_output_shows_each_file_path() {
    // VAL-OUT-001: every result's file_path appears as readable text.
    let result = mock_analysis_result(vec![
        mock_search_result(1, "src/main.rs", "main", 0.950),
        mock_search_result(2, "src/lib.rs", "helper", 0.800),
        mock_search_result(3, "src/util.rs", "parse", 0.600),
    ]);
    let out = format_analysis_output("test query", &result);
    for path in ["src/main.rs", "src/lib.rs", "src/util.rs"] {
        assert!(out.contains(path), "output must contain file path {}", path);
    }
}

#[test]
fn test_analysis_output_shows_symbol_names() {
    // VAL-OUT-002: every result's symbol_name appears as readable text.
    let result = mock_analysis_result(vec![
        mock_search_result(1, "src/main.rs", "main", 0.950),
        mock_search_result(2, "src/lib.rs", "helper", 0.800),
        mock_search_result(3, "src/util.rs", "parse", 0.600),
    ]);
    let out = format_analysis_output("test query", &result);
    for symbol in ["main", "helper", "parse"] {
        assert!(
            out.contains(symbol),
            "output must contain symbol {}",
            symbol
        );
    }
}

#[test]
fn test_analysis_output_shows_numeric_scores() {
    // VAL-OUT-003: score.overall rendered as a numeric value per entry.
    let result = mock_analysis_result(vec![
        mock_search_result(1, "src/main.rs", "main", 0.950),
        mock_search_result(2, "src/lib.rs", "helper", 0.803),
    ]);
    let out = format_analysis_output("test query", &result);
    assert!(out.contains("score: 0.950"), "output must show score 0.950");
    assert!(out.contains("score: 0.803"), "output must show score 0.803");
}

#[test]
fn test_analysis_context_budget_at_least_1000() {
    // VAL-OUT-004: the budget constant is >= 1000 (enforced by the
    // `const _: () = assert!(...)` at the definition). Behaviorally, a
    // context longer than 1000 chars must be displayed in full rather than
    // truncated at the old 300-char cap.
    let body = "context line\n".repeat(120); // ~1560 chars, well over 1000
    let result = crate::cli::leindex::AnalysisResult {
        query: "test query".to_string(),
        results: vec![],
        context: Some(body),
        tokens_used: 500,
        processing_time_ms: 12,
    };
    let out = format_analysis_output("test query", &result);
    assert_eq!(
        out.matches("context line").count(),
        120,
        "context longer than 1000 chars must be displayed without truncation"
    );
}

#[test]
fn test_analysis_results_appear_before_context() {
    // VAL-OUT-005: result entries precede the Context section.
    let result = mock_analysis_result(vec![mock_search_result(1, "src/main.rs", "main", 0.950)]);
    let out = format_analysis_output("test query", &result);
    let results_pos = out.find("src/main.rs").expect("file path present");
    let context_pos = out.find("Context:").expect("context header present");
    assert!(
        results_pos < context_pos,
        "results must appear before the Context section"
    );
}

#[test]
fn test_analysis_output_not_raw_json() {
    // VAL-OUT-006: structured, human-readable output — never raw JSON.
    let result = mock_analysis_result(vec![mock_search_result(1, "src/main.rs", "main", 0.950)]);
    let out = format_analysis_output("test query", &result);
    assert!(!out.starts_with('{'), "output must not be raw JSON");
    assert!(
        !out.contains("\"results\""),
        "output must not contain a JSON results key"
    );
    assert!(
        !out.contains("\"rank\":"),
        "output must not contain JSON rank keys"
    );
}

#[test]
fn test_analysis_output_empty_results_message() {
    let result = mock_analysis_result(vec![]);
    let out = format_analysis_output("test query", &result);
    assert!(
        out.contains("No results found"),
        "empty results must print 'No results found'"
    );
}