codenexus 0.4.0-rc.2

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

//! Search command: search for symbols by name or content.

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
#[cfg(any(feature = "cli", feature = "mcp", test))]
use std::str::FromStr;

#[cfg(any(feature = "cli", feature = "mcp", test))]
use crate::kit::{AsyncKit, AsyncReady, QueryModule, StorageModule};
#[cfg(any(feature = "cli", feature = "mcp", test))]
use crate::query::structured::{SearchEngine, SearchMode, SearchParams};
#[cfg(any(feature = "cli", feature = "mcp", test))]
use crate::query::SearchResult;
#[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", test))]
use crate::service::project::resolve_project_id;
#[cfg(any(feature = "cli", feature = "mcp"))]
use crate::service::runtime::kit;

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

/// JSON-serializable search result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SearchOutput {
    pub count: usize,
    pub results: Vec<Value>,
}

/// Converts a [`SearchResult`] into a JSON object for API output.
#[cfg(any(feature = "cli", feature = "mcp", test))]
fn search_result_to_json(r: &SearchResult) -> Value {
    json!({
        "name": r.name,
        "label": r.label,
        "filePath": r.file_path,
        "startLine": r.start_line,
        "qualifiedName": r.qualified_name,
        "score": r.score,
        "matchReason": r.match_reason,
    })
}

/// Runs search against an injected Kit (testable core).
///
/// When `mode` is non-empty, uses [`SearchEngine`] with the corresponding
/// [`SearchMode`] for multi-mode search (exact/regex/fuzzy/graph/multi).
/// When `mode` is empty, falls back to the legacy `QueryModule` search
/// (structured or BM25 full-text based on `fulltext` flag).
#[cfg(any(feature = "cli", feature = "mcp", test))]
pub fn run_search(
    kit: &AsyncKit<AsyncReady>,
    text: &str,
    fulltext: bool,
    limit: u32,
    mode: &str,
    project: &str,
) -> Result<SearchOutput, CodeNexusError> {
    if mode.is_empty() {
        // Empty mode → legacy path (backward compatible). `--project` must
        // filter here too: both QueryModule calls used to hardcode `None`,
        // silently returning every project's rows even though the CLI help /
        // MCP tool description promise "project — project name or id
        // (empty = all projects)".
        let q = kit.require::<QueryModule>()?;
        let project_id = if project.is_empty() {
            None
        } else {
            let storage = kit.require::<StorageModule>()?;
            Some(resolve_project_id(&*storage, project)?)
        };
        let results = if fulltext {
            q.fulltext_search(text, project_id.as_deref(), limit as usize)
        } else {
            q.search(text, project_id.as_deref(), limit as usize)
        }?;
        let results: Vec<Value> = results.iter().map(search_result_to_json).collect();
        Ok(SearchOutput {
            count: results.len(),
            results,
        })
    } else {
        // Non-empty mode: parse strictly, reject unknown values.
        let search_mode = SearchMode::from_str(mode)
            .map_err(|e| CodeNexusError::InvalidInput(format!("invalid search mode: {e}")))?;
        let storage = kit.require::<StorageModule>()?;
        let project_id = if project.is_empty() {
            project.to_string()
        } else {
            resolve_project_id(&*storage, project)?
        };
        let engine = SearchEngine::new(&*storage);
        let params = SearchParams {
            query: text.to_string(),
            mode: search_mode,
            limit: limit as usize,
            ..Default::default()
        };
        let results = engine.search(&project_id, &params)?;
        let results: Vec<Value> = results.iter().map(search_result_to_json).collect();
        Ok(SearchOutput {
            count: results.len(),
            results,
        })
    }
}

/// CLI wrapper — prints result to stdout as JSON.
#[cfg(feature = "cli")]
#[forge::log(args, err_detail)]
#[forge(
    name = "search",
    version = "0.3.5",
    description = "Search for symbols by name (structured) or content (BM25 full-text).",
    cli = true
)]
async fn search(
    text: String,
    fulltext: bool,
    limit: u32,
    mode: String,
    project: String,
) -> Result<(), ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    let result = run_search(&kit, &text, fulltext, limit, &mode, &project)
        .map_err(|e| to_api_error(e, "search_error"))?;
    let json = serde_json::to_string(&result)
        .map_err(|e| to_api_error(CodeNexusError::from(e), "search_error"))?;
    println!("{json}");
    Ok(())
}

/// MCP wrapper — returns result for MCP protocol.
#[cfg(feature = "mcp")]
#[forge(
    name = "search",
    version = "0.3.5",
    tool_name = "search",
    description = "Search for symbols by name or content. Params: text (required); fulltext — false: structured name search, true: BM25 full-text content search; mode — exact|regex|fuzzy|graph|multi (empty = legacy name/BM25 path); limit — max results (default 50); project — project name or id (empty = all projects)."
)]
async fn search_mcp(
    text: String,
    fulltext: bool,
    limit: u32,
    mode: String,
    project: String,
) -> Result<SearchOutput, ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    run_search(&kit, &text, fulltext, limit, &mode, &project)
        .map_err(|e| to_api_error(e, "search_error"))
}

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

    fn fresh_db_path() -> (TempDir, PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("svc_search_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")
    }

    fn seed_project(storage: &dyn Storage, id: &str, name: &str) {
        storage
            .execute(&format!(
                "CREATE (:Project {{id: '{id}', name: '{name}', rootPath: '/demo', language: 'rust', fileCount: 1, indexedAt: 1000, lastCommit: 'abc'}});"
            ))
            .expect("create project");
    }

    #[test]
    fn run_search_returns_empty_on_fresh_db() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let output = run_search(&kit, "foo", false, 10, "", "").expect("run should succeed");
        assert_eq!(output.count, 0);
        assert!(output.results.is_empty());
    }

    #[test]
    fn run_search_finds_symbol_by_name() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thing", false, 10, "", "").expect("run should succeed");
        let _ = output;
    }

    #[test]
    fn run_search_empty_text_returns_error() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let err = run_search(&kit, "   ", false, 10, "", "").expect_err("empty text should error");
        assert!(matches!(err, CodeNexusError::Query(_)));
    }

    #[test]
    fn run_search_fulltext_empty_text_returns_error() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let err = run_search(&kit, "", true, 10, "", "").expect_err("empty fulltext should error");
        assert!(matches!(err, CodeNexusError::Query(_)));
    }

    #[test]
    fn search_output_serializes_to_json() {
        let output = SearchOutput {
            count: 1,
            results: vec![json!({
                "name": "foo",
                "label": "Function",
                "filePath": "/src/a.rs",
                "startLine": 1,
                "qualifiedName": "demo.foo",
                "score": 0.95,
            })],
        };
        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"count\":1"));
        assert!(json.contains("\"name\":\"foo\""));
        assert!(json.contains("\"label\":\"Function\""));
    }

    #[test]
    fn search_result_to_json_maps_all_fields() {
        let r = SearchResult {
            name: "foo".into(),
            label: "Function".into(),
            file_path: Some("/src/a.rs".into()),
            start_line: Some(42),
            qualified_name: Some("demo.foo".into()),
            score: 0.8,
            match_reason: "exact".into(),
            degree: 0,
        };
        let v = search_result_to_json(&r);
        assert_eq!(v["name"], "foo");
        assert_eq!(v["label"], "Function");
        assert_eq!(v["filePath"], "/src/a.rs");
        assert_eq!(v["startLine"], 42);
        assert_eq!(v["qualifiedName"], "demo.foo");
        let score = v["score"].as_f64().expect("score should be a number");
        assert!(
            (score - 0.8).abs() < 1e-6,
            "score should be ~0.8, got {score}"
        );
    }

    #[test]
    fn search_result_to_json_handles_none_fields() {
        let r = SearchResult {
            name: "bar".into(),
            label: "Class".into(),
            file_path: None,
            start_line: None,
            qualified_name: None,
            score: 0.0,
            match_reason: String::new(),
            degree: 0,
        };
        let v = search_result_to_json(&r);
        assert_eq!(v["name"], "bar");
        assert!(v["filePath"].is_null());
        assert!(v["startLine"].is_null());
        assert!(v["qualifiedName"].is_null());
    }

    // ===== run_search with mode parameter =====

    #[test]
    fn run_search_with_exact_mode_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thing", false, 10, "exact", "demo")
            .expect("exact mode search should succeed");
        assert!(output.count > 0, "should find do_thing in exact mode");
    }

    // ===== legacy (empty-mode) path: `--project` filtering =====

    /// Seeds two projects (id/name alpha, beta) each with one distinct
    /// function directly into the DB file and closes the seed connection.
    ///
    /// Must run BEFORE [`build_kit_for_db`]: a LadybugDB connection opened
    /// before a write does not observe it in-process (verified: a
    /// QueryModule connection opened first reads an empty snapshot even
    /// though the StorageModule connection that made the writes sees the
    /// rows). Committing the fixture to the file first and opening the Kit
    /// afterwards keeps every module's connection consistent.
    fn seed_two_projects(db: &std::path::Path) {
        use crate::storage::repository::Repository;
        let repo = Repository::open(db).expect("open seed repository");
        let conn = repo.connection();
        conn.init_schema().expect("init schema");
        for (id, name) in [("alpha", "alpha"), ("beta", "beta")] {
            conn.execute(&format!(
                "CREATE (:Project {{id: '{id}', name: '{name}', rootPath: '/{id}', language: 'rust', fileCount: 1, indexedAt: 1000, lastCommit: 'abc'}});"
            ))
            .expect("create project");
        }
        conn.execute("CREATE (:Function {id: 'f_alpha', project: 'alpha', name: 'project_alpha_fn', qualifiedName: 'alpha.project_alpha_fn', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create alpha function");
        conn.execute("CREATE (:Function {id: 'f_beta', project: 'beta', name: 'project_beta_fn', qualifiedName: 'beta.project_beta_fn', filePath: '/src/b.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create beta function");
    }

    #[test]
    fn run_search_empty_mode_filters_by_project_name() {
        let (_dir, db) = fresh_db_path();
        seed_two_projects(&db);
        let kit = build_kit_for_db(&db);

        // Empty project = all projects (both rows visible).
        let all = run_search(&kit, "project_alpha_fn", false, 50, "", "")
            .expect("unfiltered search should succeed");
        assert_eq!(
            all.count, 1,
            "unfiltered name search finds alpha's function"
        );

        // Name filter must drop other projects' rows.
        let own = run_search(&kit, "project_beta_fn", false, 50, "", "beta")
            .expect("filtered search should succeed");
        assert_eq!(own.count, 1, "beta's own function must be found");

        let foreign = run_search(&kit, "project_alpha_fn", false, 50, "", "beta")
            .expect("filtered search should succeed");
        assert_eq!(
            foreign.count, 0,
            "alpha's function must not leak into beta's search: {:?}",
            foreign.results
        );
    }

    #[test]
    fn run_search_empty_mode_filters_by_project_id() {
        let (_dir, db) = fresh_db_path();
        seed_two_projects(&db);
        let kit = build_kit_for_db(&db);

        let by_id = run_search(&kit, "project_alpha_fn", false, 50, "", "alpha")
            .expect("id-filtered search should succeed");
        assert_eq!(by_id.count, 1, "project id must resolve like a name");
    }

    #[test]
    fn run_search_empty_mode_fulltext_filters_by_project() {
        let (_dir, db) = fresh_db_path();
        seed_two_projects(&db);
        let kit = build_kit_for_db(&db);

        let foreign = run_search(&kit, "project_alpha_fn", true, 50, "", "beta")
            .expect("filtered fulltext search should succeed");
        assert_eq!(
            foreign.count, 0,
            "fulltext must not leak alpha's function into beta: {:?}",
            foreign.results
        );
        let own = run_search(&kit, "project_beta_fn", true, 50, "", "beta")
            .expect("filtered fulltext search should succeed");
        assert_eq!(own.count, 1, "fulltext must find beta's own function");
    }

    #[test]
    fn run_search_empty_mode_unknown_project_errors() {
        let (_dir, db) = fresh_db_path();
        seed_two_projects(&db);
        let kit = build_kit_for_db(&db);

        let err = run_search(&kit, "project_alpha_fn", false, 50, "", "gamma")
            .expect_err("unknown project must error");
        assert!(
            matches!(err, CodeNexusError::ProjectNotFound(_)),
            "expected ProjectNotFound, got {err:?}"
        );
    }

    #[test]
    fn run_search_with_regex_mode_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_.*", false, 10, "regex", "demo")
            .expect("regex mode search should succeed");
        assert!(output.count > 0, "should find do_thing with regex do_.*");
    }

    #[test]
    fn run_search_with_fuzzy_mode_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thng", false, 10, "fuzzy", "demo")
            .expect("fuzzy mode search should succeed");
        // Fuzzy search should find do_thing even with a typo
        assert!(output.count > 0, "should find do_thing with fuzzy do_thng");
    }

    #[test]
    fn run_search_with_invalid_mode_returns_error() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        // Non-empty but invalid mode must error (never silently fall back).
        let err = run_search(&kit, "foo", false, 10, "invalid_mode", "")
            .expect_err("invalid mode should error");
        assert!(
            matches!(err, CodeNexusError::InvalidInput(_)),
            "expected InvalidInput, got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("invalid_mode"),
            "error should mention bad mode: {msg}"
        );
    }

    #[test]
    fn run_search_with_empty_mode_uses_legacy_path() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let output =
            run_search(&kit, "foo", false, 10, "", "").expect("empty mode should use legacy path");
        assert_eq!(output.count, 0);
    }

    // ===== run_search: graph_enhanced and multi_signal modes =====

    #[test]
    fn run_search_with_graph_enhanced_mode_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thing", false, 10, "graph", "demo")
            .expect("graph_enhanced mode should succeed");
        assert!(output.count > 0, "should find do_thing in graph mode");
    }

    #[test]
    fn run_search_with_graph_enhanced_alias_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thing", false, 10, "graph_enhanced", "demo")
            .expect("graph_enhanced alias should succeed");
        assert!(
            output.count > 0,
            "should find do_thing with graph_enhanced alias"
        );
    }

    #[test]
    fn run_search_with_multi_signal_mode_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thing", false, 10, "multi", "demo")
            .expect("multi_signal mode should succeed");
        assert!(output.count > 0, "should find do_thing in multi mode");
    }

    #[test]
    fn run_search_with_multi_signal_alias_finds_symbol() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'do_thing', qualifiedName: 'demo.do_thing', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "do_thing", false, 10, "multi_signal", "demo")
            .expect("multi_signal alias should succeed");
        assert!(
            output.count > 0,
            "should find do_thing with multi_signal alias"
        );
    }

    #[test]
    fn run_search_with_graph_enhanced_on_empty_db_returns_empty() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_search(&kit, "foo", false, 10, "graph", "demo")
            .expect("graph mode on empty DB should succeed");
        assert_eq!(output.count, 0);
    }

    #[test]
    fn run_search_with_multi_signal_on_empty_db_returns_empty() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_search(&kit, "foo", false, 10, "multi", "demo")
            .expect("multi mode on empty DB should succeed");
        assert_eq!(output.count, 0);
    }

    // ===== run_search: fulltext mode exercises legacy fulltext path =====

    #[test]
    fn run_search_fulltext_on_non_empty_db_succeeds() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        storage.execute("CREATE (:Function {id: 'f1', project: 'demo', name: 'fetch_data', qualifiedName: 'demo.fetch_data', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create function");
        let output = run_search(&kit, "fetch_data", true, 10, "", "")
            .expect("fulltext search should succeed");
        let _ = output;
    }

    #[test]
    fn run_search_with_exact_mode_on_empty_db_returns_empty() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_search(&kit, "foo", false, 10, "exact", "demo")
            .expect("exact mode on empty DB should succeed");
        assert_eq!(output.count, 0);
    }

    #[test]
    fn run_search_with_regex_mode_on_empty_db_returns_empty() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_search(&kit, "foo.*", false, 10, "regex", "demo")
            .expect("regex mode on empty DB should succeed");
        assert_eq!(output.count, 0);
    }

    #[test]
    fn run_search_with_fuzzy_mode_on_empty_db_returns_empty() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_search(&kit, "foo", false, 10, "fuzzy", "demo")
            .expect("fuzzy mode on empty DB should succeed");
        assert_eq!(output.count, 0);
    }

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

    #[serial_test::serial(kit_init)]
    #[cfg(feature = "cli")]
    #[test]
    fn search_wrapper_succeeds_via_init_kit() {
        use crate::service::runtime::{init_kit, reset_kit_for_testing};

        reset_kit_for_testing();
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        // The wrapper passes `--project demo`; the legacy path now resolves it
        // (name → id) and would otherwise fail with ProjectNotFound on a DB
        // without that project — seed it first via the same connection the
        // resolver reads from.
        let storage = kit.require::<crate::kit::StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        init_kit(kit).expect("init_kit");

        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(search(
            "foo".to_string(),
            false,
            10,
            "".to_string(),
            "demo".to_string(),
        ));
        assert!(result.is_ok(), "wrapper should succeed: {:?}", result.err());

        reset_kit_for_testing();
    }

    #[serial_test::serial(kit_init)]
    #[cfg(feature = "cli")]
    #[test]
    fn search_wrapper_fails_when_kit_not_initialized() {
        use crate::service::runtime::reset_kit_for_testing;

        reset_kit_for_testing();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(search(
            "foo".to_string(),
            false,
            10,
            "".to_string(),
            "demo".to_string(),
        ));
        assert!(result.is_err(), "wrapper should fail without kit");
        reset_kit_for_testing();
    }
}