trusty-search 0.22.2

Machine-wide hybrid code search service: BM25 + vector + KG, zero cold-start, MCP server
Documentation
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
//! Handler for `trusty-search migrate mcp-vector-search`.
//!
//! Why: migrating away from mcp-vector-search has two distinct sides — the
//! project indexes (handled by reusing `convert.rs`) *and* the Claude MCP
//! configuration files that still point at the old `mcp-vector-search` server
//! command. `convert` only does indexes; `migrate` does both so a user can
//! switch tools in a single command.
//! What: `handle_migrate` orchestrates an MCP-config rewrite phase and an
//! index-migration phase, each independently skippable.
//! Test: `cargo run -- migrate mcp-vector-search --dry-run` prints the
//! settings files and projects it would touch without modifying anything.

use super::convert::{convert_one, find_all_mvs_configs, parse_mvs_config, ConvertStatus};
use super::daemon_utils::daemon_base_url;
use anyhow::Result;
use clap::ValueEnum;
use colored::Colorize;
use serde_json::Value;
use std::path::{Path, PathBuf};
use trusty_common::claude_config::{
    default_settings_max_depth, discover_claude_settings, mcp_server_entry, write_json_atomic,
};

/// The MCP server keys (legacy spellings) we replace with `trusty-search`.
const LEGACY_MCP_KEYS: &[&str] = &["mcp-vector-search", "mcp_vector_search"];

/// The canonical key written for the migrated trusty-search MCP server.
const TRUSTY_KEY: &str = "trusty-search";

/// What the user is migrating *from*.
///
/// Why: model the migration source as an enum (validated at parse time by
/// clap) so additional sources can be added without changing the CLI surface.
/// What: a single variant today — `mcp-vector-search`.
/// Test: `cargo run -- migrate bogus` → clap rejects with a usage hint.
#[derive(Debug, Clone, ValueEnum)]
pub enum MigrateTarget {
    /// Migrate from mcp-vector-search (MCP config + project indexes)
    McpVectorSearch,
}

/// Outcome of attempting to migrate one Claude settings file.
///
/// Why: the summary table needs to distinguish a real rewrite from a no-op
/// skip (already migrated / nothing to do) and a hard failure.
/// What: enumerates the four terminal states of `migrate_config_file`.
/// Test: unit tests assert `Migrated`, `AlreadyMigrated`, and `NoChange`.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigMigrateStatus {
    /// The file contained a legacy key and was rewritten.
    Migrated,
    /// The file already contained a `trusty-search` key — left untouched.
    AlreadyMigrated,
    /// No legacy key and no trusty-search key — left untouched.
    NoChange,
    /// An IO/parse error occurred.
    Failed(String),
}

/// Result of migrating one Claude settings file (path + terminal status).
///
/// Why: pairs the file path with its outcome so the summary renderer can
/// print one line per file.
/// What: returned by `migrate_config_file`.
/// Test: unit tests inspect `status` after rewriting fixture files.
#[derive(Debug)]
pub struct ConfigMigrateResult {
    pub path: PathBuf,
    pub status: ConfigMigrateStatus,
}

/// Entry point for `trusty-search migrate`.
///
/// Why: a single command that switches a machine from mcp-vector-search to
/// trusty-search, touching both Claude MCP config and project indexes.
/// What: runs the MCP-config phase and/or the index phase depending on the
/// `--mcp-only` / `--indexes-only` flags.
/// Test: `migrate mcp-vector-search --dry-run` prints both phases' plans.
pub async fn handle_migrate(
    target: MigrateTarget,
    dry_run: bool,
    mcp_only: bool,
    indexes_only: bool,
) -> Result<()> {
    // `target` has one variant today; the match keeps future sources explicit.
    match target {
        MigrateTarget::McpVectorSearch => {}
    }

    if dry_run {
        println!(
            "{} Dry run — no files or indexes will be modified.\n",
            "·".dimmed()
        );
    }

    if !indexes_only {
        run_mcp_phase(dry_run)?;
    }

    if !mcp_only {
        if !indexes_only {
            println!();
        }
        run_index_phase(dry_run).await?;
    }

    Ok(())
}

/// MCP-config migration phase: scan + rewrite every Claude settings file.
///
/// Why: keeps the config-rewrite orchestration (scan → migrate → summarize)
/// separate from the async index phase.
/// What: locates settings files, migrates each, prints a summary table.
/// Test: covered indirectly by `--dry-run` runs and the unit tests below.
fn run_mcp_phase(dry_run: bool) -> Result<()> {
    let home =
        dirs::home_dir().ok_or_else(|| anyhow::anyhow!("could not determine home directory"))?;
    println!(
        "🔍 Scanning for Claude MCP settings under {}",
        home.display()
    );

    let files = discover_claude_settings(&home, default_settings_max_depth());
    if files.is_empty() {
        println!("{} No Claude settings files found.", "·".dimmed());
        return Ok(());
    }
    println!("{} Found {} settings file(s).\n", "·".dimmed(), files.len());

    let mut migrated = 0usize;
    let mut skipped = 0usize;
    let mut failed = 0usize;

    for (i, path) in files.iter().enumerate() {
        let result = migrate_config_file(path, dry_run);
        print_config_line(i + 1, files.len(), &result);
        match result.status {
            ConfigMigrateStatus::Migrated => migrated += 1,
            ConfigMigrateStatus::AlreadyMigrated | ConfigMigrateStatus::NoChange => skipped += 1,
            ConfigMigrateStatus::Failed(_) => failed += 1,
        }
    }

    println!();
    if dry_run {
        println!(
            "{} MCP config dry run: {} would migrate, {} skipped, {} failed",
            "·".dimmed(),
            migrated,
            skipped,
            failed
        );
    } else {
        println!(
            "{} MCP config: {} migrated, {} skipped, {} failed",
            "".green(),
            migrated,
            skipped,
            failed
        );
    }
    Ok(())
}

/// Index-migration phase: reuse the `convert all` logic.
///
/// Why: index migration is identical to `convert all`; rather than duplicate
/// the discovery + HTTP dance, we call the shared `convert.rs` helpers.
/// What: scans `$HOME` for mcp-vector-search configs and (unless dry-run)
/// registers + reindexes each via the daemon.
/// Test: `migrate mcp-vector-search --indexes-only --dry-run` enumerates
/// every detected project.
async fn run_index_phase(dry_run: bool) -> Result<()> {
    println!("🔍 Scanning for mcp-vector-search project indexes…");
    let configs = find_all_mvs_configs();
    if configs.is_empty() {
        println!("{} No mcp-vector-search projects found.", "·".dimmed());
        return Ok(());
    }
    println!("{} Found {} project(s).\n", "·".dimmed(), configs.len());

    let base = if dry_run {
        // Dry run never contacts the daemon, so an empty base is harmless.
        String::new()
    } else {
        let base = daemon_base_url();
        crate::commands::daemon_guard::ensure_daemon_running_or_exit(&base).await?;
        base
    };

    let total = configs.len();
    let mut migrated = 0usize;
    let mut already = 0usize;
    let mut dry = 0usize;
    let mut failed = 0usize;

    for (i, config_path) in configs.into_iter().enumerate() {
        let result = match parse_mvs_config(&config_path) {
            Ok((root, name)) => convert_one(root, name, &base, dry_run).await,
            Err(e) => {
                println!(
                    "  {} {} {} {}",
                    format!("[{}/{}]", i + 1, total).dimmed(),
                    "".red(),
                    config_path.display().to_string().dimmed(),
                    format!("(parse: {e})").red()
                );
                failed += 1;
                continue;
            }
        };
        print_index_line(i + 1, total, &result);
        match result.status {
            ConvertStatus::Queued => migrated += 1,
            ConvertStatus::AlreadyRegistered => already += 1,
            ConvertStatus::DryRun => dry += 1,
            ConvertStatus::Failed(_) => failed += 1,
        }
    }

    println!();
    if dry_run {
        println!("{} Index dry run: {} project(s)", "·".dimmed(), dry);
    } else {
        println!(
            "{} Indexes: {} queued, {} already registered, {} failed",
            "".green(),
            migrated,
            already,
            failed
        );
    }
    Ok(())
}

/// Rewrite one Claude settings file, replacing any legacy mcp-vector-search
/// MCP server entry with a `trusty-search` entry.
///
/// Why: this is the load-bearing surgery — it must preserve every unrelated
/// JSON key, be idempotent, and never corrupt the file on failure. The
/// atomic-write + backup mechanics live in `trusty_common::claude_config`;
/// this function adds the migration-specific concerns (detecting legacy
/// keys, removing them, and distinguishing the four terminal states for
/// the summary table).
/// What: classifies the file (NoChange / AlreadyMigrated / migration
/// needed). When migration is needed, removes any legacy mcp-vector-search
/// keys and inserts the canonical trusty-search entry in a single atomic
/// write via `trusty_common::claude_config::write_json_atomic`. The
/// trusty-search entry shape comes from `mcp_server_entry(TRUSTY_KEY,
/// &["serve"])`, matching `patch_mcp_server`'s upsert exactly so the two
/// helpers stay in lock-step.
/// Test: `test_migrate_config_replaces_key` and `test_migrate_config_idempotent`
/// assert the rewrite and the no-op-on-already-migrated behaviour.
pub fn migrate_config_file(path: &Path, dry_run: bool) -> ConfigMigrateResult {
    let fail = |msg: String| ConfigMigrateResult {
        path: path.to_path_buf(),
        status: ConfigMigrateStatus::Failed(msg),
    };
    let result = |status| ConfigMigrateResult {
        path: path.to_path_buf(),
        status,
    };

    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => return fail(format!("read: {e}")),
    };
    let mut root: Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(e) => return fail(format!("parse: {e}")),
    };

    let servers = match root.get_mut("mcpServers").and_then(Value::as_object_mut) {
        Some(s) => s,
        // No mcpServers block at all — nothing to migrate.
        None => return result(ConfigMigrateStatus::NoChange),
    };

    // Idempotency: a trusty-search entry already present means a previous run
    // (or the user) already migrated this file — never double-migrate.
    if servers.contains_key(TRUSTY_KEY) {
        return result(ConfigMigrateStatus::AlreadyMigrated);
    }

    let legacy_present = LEGACY_MCP_KEYS.iter().any(|k| servers.contains_key(*k));
    if !legacy_present {
        return result(ConfigMigrateStatus::NoChange);
    }

    // Drop every legacy key and insert the canonical trusty-search entry in
    // a single atomic write. We do not call `patch_mcp_server` here because
    // it would create its own `.bak` of the already-stripped file — we want
    // the user's pre-migration content as the backup, which means a single
    // read-modify-write through `write_json_atomic`.
    for k in LEGACY_MCP_KEYS {
        servers.remove(*k);
    }
    servers.insert(
        TRUSTY_KEY.to_string(),
        mcp_server_entry(TRUSTY_KEY, &["serve"]),
    );

    if dry_run {
        return result(ConfigMigrateStatus::Migrated);
    }

    match write_json_atomic(path, &root) {
        Ok(()) => result(ConfigMigrateStatus::Migrated),
        Err(e) => fail(format!("write: {e}")),
    }
}

/// Render one MCP-config result line for the summary table.
fn print_config_line(idx: usize, total: usize, r: &ConfigMigrateResult) {
    let prefix = format!("[{idx}/{total}]");
    let path = r.path.display().to_string();
    match &r.status {
        ConfigMigrateStatus::Migrated => println!("  {} {} {}", prefix.dimmed(), "".green(), path),
        ConfigMigrateStatus::AlreadyMigrated => println!(
            "  {} {} {} {}",
            prefix.dimmed(),
            "".cyan(),
            path.dimmed(),
            "(already migrated)".dimmed()
        ),
        ConfigMigrateStatus::NoChange => println!(
            "  {} {} {} {}",
            prefix.dimmed(),
            "·".dimmed(),
            path.dimmed(),
            "(no mcp-vector-search entry)".dimmed()
        ),
        ConfigMigrateStatus::Failed(msg) => println!(
            "  {} {} {} {}",
            prefix.dimmed(),
            "".red(),
            path.dimmed(),
            format!("({msg})").red()
        ),
    }
}

/// Render one index-migration result line for the summary table.
fn print_index_line(idx: usize, total: usize, r: &super::convert::ConvertResult) {
    let prefix = format!("[{idx}/{total}]");
    let path = r.path.display().to_string();
    match &r.status {
        ConvertStatus::Queued => println!(
            "  {} {} {:<24} → {}",
            prefix.dimmed(),
            "".green(),
            r.name,
            path.dimmed()
        ),
        ConvertStatus::AlreadyRegistered => println!(
            "  {} {} {:<24} → {} {}",
            prefix.dimmed(),
            "".cyan(),
            r.name,
            path.dimmed(),
            "(already registered, reindexing)".dimmed()
        ),
        ConvertStatus::DryRun => println!("  {} {:<24} {}", prefix.dimmed(), r.name, path.dimmed()),
        ConvertStatus::Failed(msg) => println!(
            "  {} {} {:<24} → {} {}",
            prefix.dimmed(),
            "".red(),
            r.name,
            path.dimmed(),
            format!("({msg})").red()
        ),
    }
}

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

    /// Why: the scan must reliably locate both global and project-level
    /// `.claude` settings files regardless of nesting depth.
    #[test]
    fn test_scan_finds_settings_files() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let home = tmp.path();

        // Global settings.
        let global = home.join(".claude");
        std::fs::create_dir_all(&global).expect("mkdir global");
        std::fs::write(global.join("settings.json"), "{}").expect("write global");

        // Nested project settings (settings.local.json).
        let proj = home.join("code").join("my-proj").join(".claude");
        std::fs::create_dir_all(&proj).expect("mkdir proj");
        std::fs::write(proj.join("settings.local.json"), "{}").expect("write proj");

        // A noise dir that must be skipped.
        let noise = home.join("node_modules").join(".claude");
        std::fs::create_dir_all(&noise).expect("mkdir noise");
        std::fs::write(noise.join("settings.json"), "{}").expect("write noise");

        let found = discover_claude_settings(home, default_settings_max_depth());
        assert!(
            found.contains(&global.join("settings.json")),
            "global settings missing: {found:?}"
        );
        assert!(
            found.contains(&proj.join("settings.local.json")),
            "project settings missing: {found:?}"
        );
        assert!(
            !found
                .iter()
                .any(|p| p.starts_with(home.join("node_modules"))),
            "node_modules should be skipped: {found:?}"
        );
    }

    /// Why: the core surgery — a legacy key must be removed and the canonical
    /// trusty-search key inserted, while unrelated keys survive.
    #[test]
    fn test_migrate_config_replaces_key() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("settings.local.json");
        let input = serde_json::json!({
            "theme": "dark",
            "mcpServers": {
                "mcp-vector-search": {
                    "command": "mcp-vector-search",
                    "args": ["serve"]
                },
                "other-server": { "command": "other" }
            }
        });
        std::fs::write(&path, serde_json::to_string_pretty(&input).unwrap()).expect("write input");

        let result = migrate_config_file(&path, false);
        assert_eq!(result.status, ConfigMigrateStatus::Migrated);

        let rewritten: Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        let servers = rewritten["mcpServers"].as_object().unwrap();
        assert!(
            !servers.contains_key("mcp-vector-search"),
            "legacy key should be gone"
        );
        assert!(servers.contains_key("trusty-search"), "trusty key missing");
        assert!(
            servers.contains_key("other-server"),
            "unrelated server dropped"
        );
        assert_eq!(
            rewritten["theme"], "dark",
            "unrelated top-level key dropped"
        );
        assert_eq!(servers["trusty-search"]["command"], "trusty-search");
        assert_eq!(servers["trusty-search"]["args"][0], "serve");

        // Backup preserves multi-dot filename: settings.local.json.bak
        assert!(
            path.with_file_name("settings.local.json.bak").exists(),
            "backup file missing"
        );
    }

    /// Why: a file already carrying a trusty-search entry must be left
    /// untouched so repeated `migrate` runs are safe.
    #[test]
    fn test_migrate_config_idempotent() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("settings.json");
        let input = serde_json::json!({
            "mcpServers": {
                "trusty-search": {
                    "command": "trusty-search",
                    "args": ["serve"]
                }
            }
        });
        let serialized = serde_json::to_string_pretty(&input).unwrap();
        std::fs::write(&path, &serialized).expect("write input");

        let result = migrate_config_file(&path, false);
        assert_eq!(result.status, ConfigMigrateStatus::AlreadyMigrated);

        // File must be byte-for-byte unchanged.
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            serialized,
            "file should be untouched"
        );
        assert!(
            !path.with_file_name("settings.json.bak").exists(),
            "no backup should be written for a skipped file"
        );
    }
}