colgrep 1.5.0

Semantic code search powered by ColBERT
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
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
use anyhow::{Context, Result};
use colored::Colorize;
use serde_json;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

/// The marketplace identifier for the colgrep plugin
/// Note: Must not conflict with plugin name on case-insensitive filesystems
const MARKETPLACE_ID: &str = "lightonai-colgrep";

/// The plugin name as registered in Claude Code
const PLUGIN_NAME: &str = "colgrep";

/// Minimum required Claude Code version for plugin support
const MIN_CLAUDE_VERSION: &str = "2.0.36";

/// Embedded marketplace and plugin files (bundled with the crate for cargo install support)
const MARKETPLACE_JSON: &str = include_str!("marketplace.json");
const PLUGIN_JSON: &str = include_str!("plugin.json");
const HOOK_JSON: &str = include_str!("hook.json");

use super::SKILL_MD;

/// Get the marketplace directory path (in user's data directory)
fn get_marketplace_dir() -> Result<PathBuf> {
    let data_dir = dirs::data_dir().context("Could not determine data directory")?;
    Ok(data_dir.join("colgrep").join("claude-marketplace"))
}

/// Create the full marketplace directory structure with all files
/// Structure:
/// marketplace/
/// ├── .claude-plugin/
/// │   └── marketplace.json
/// └── plugins/
///     └── colgrep/
///         ├── .claude-plugin/
///         │   └── plugin.json
///         ├── hooks/
///         │   └── hook.json
///         └── skills/
///             └── colgrep/
///                 └── SKILL.md
fn create_marketplace_files() -> Result<PathBuf> {
    let marketplace_dir = get_marketplace_dir()?;

    // Create marketplace root structure
    let marketplace_claude_dir = marketplace_dir.join(".claude-plugin");
    fs::create_dir_all(&marketplace_claude_dir)?;

    // Create plugin directory structure
    let plugin_dir = marketplace_dir.join("plugins").join("colgrep");
    let plugin_claude_dir = plugin_dir.join(".claude-plugin");
    let hooks_dir = plugin_dir.join("hooks");
    let skills_dir = plugin_dir.join("skills").join("colgrep");

    fs::create_dir_all(&plugin_claude_dir)?;
    fs::create_dir_all(&hooks_dir)?;
    fs::create_dir_all(&skills_dir)?;

    // Write marketplace manifest
    fs::write(
        marketplace_claude_dir.join("marketplace.json"),
        MARKETPLACE_JSON,
    )?;

    // Write plugin files
    fs::write(plugin_claude_dir.join("plugin.json"), PLUGIN_JSON)?;
    fs::write(hooks_dir.join("hook.json"), HOOK_JSON)?;
    fs::write(skills_dir.join("SKILL.md"), SKILL_MD)?;

    Ok(marketplace_dir)
}

/// Alias for backward compatibility
fn get_plugin_dir() -> Result<PathBuf> {
    get_marketplace_dir()
}

/// Check if claude CLI is available
fn check_claude_cli() -> Result<()> {
    let shell = get_shell();
    let check = Command::new(&shell)
        .args(["-c", "claude --version"])
        .output()
        .context("Failed to check claude CLI")?;

    if !check.status.success() {
        anyhow::bail!(
            "Claude Code CLI not found. Please install it with:\n  npm install -g @anthropic-ai/claude-code"
        );
    }
    Ok(())
}

/// Install the colgrep plugin for Claude Code
pub fn install_claude_code() -> Result<()> {
    // Check claude CLI is available
    check_claude_cli()?;

    // Get the shell to use for command execution
    let shell = get_shell();

    // Step 1: Create marketplace files in local directory
    println!("Creating colgrep marketplace files...");
    let marketplace_dir = create_marketplace_files()?;
    let marketplace_path = marketplace_dir.to_string_lossy();
    println!(
        "{} Marketplace files created at {}",
        "".green(),
        marketplace_path
    );

    // Step 2: Remove existing marketplace entry (if any) to avoid conflicts
    let _ = Command::new(&shell)
        .args([
            "-c",
            &format!("claude plugin marketplace remove {}", MARKETPLACE_ID),
        ])
        .output();

    // Step 3: Uninstall existing plugin (if any) to ensure clean install
    let _ = Command::new(&shell)
        .args(["-c", &format!("claude plugin uninstall {}", PLUGIN_NAME)])
        .output();

    // Step 4: Add marketplace using local path
    println!("Adding colgrep marketplace to Claude Code...");
    let marketplace_add = Command::new(&shell)
        .args([
            "-c",
            &format!("claude plugin marketplace add \"{}\"", marketplace_path),
        ])
        .output()
        .context("Failed to execute claude CLI")?;

    if !marketplace_add.status.success() {
        let stderr = String::from_utf8_lossy(&marketplace_add.stderr);
        let stdout = String::from_utf8_lossy(&marketplace_add.stdout);
        eprintln!(
            "{} Failed to add marketplace: {} {}",
            "Error:".red(),
            stderr,
            stdout
        );
        eprintln!(
            "{}",
            format!(
                "Do you have Claude Code version {} or higher installed?",
                MIN_CLAUDE_VERSION
            )
            .yellow()
        );
        anyhow::bail!("Failed to add marketplace");
    }
    println!("{} Added colgrep marketplace", "".green());

    // Step 5: Install the plugin from the marketplace
    println!("Installing colgrep plugin...");
    let plugin_install = Command::new(&shell)
        .args([
            "-c",
            &format!("claude plugin install {}@{}", PLUGIN_NAME, MARKETPLACE_ID),
        ])
        .output()
        .context("Failed to execute claude CLI")?;

    if !plugin_install.status.success() {
        let stderr = String::from_utf8_lossy(&plugin_install.stderr);
        let stdout = String::from_utf8_lossy(&plugin_install.stdout);
        eprintln!(
            "{} Failed to install plugin: {} {}",
            "Error:".red(),
            stderr,
            stdout
        );
        eprintln!(
            "{}",
            format!(
                "Do you have Claude Code version {} or higher installed?",
                MIN_CLAUDE_VERSION
            )
            .yellow()
        );
        anyhow::bail!("Failed to install plugin");
    }
    println!("{} Installed colgrep plugin", "".green());

    // Print success message and usage instructions
    print_install_success();

    Ok(())
}

/// Get the Claude Code settings.json path
fn get_claude_settings_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Could not determine home directory")?;
    Ok(home.join(".claude").join("settings.json"))
}

/// Remove colgrep-related hooks from ~/.claude/settings.json
fn remove_hooks_from_settings() -> Result<bool> {
    let settings_path = get_claude_settings_path()?;

    if !settings_path.exists() {
        return Ok(false);
    }

    let content = fs::read_to_string(&settings_path).context("Failed to read settings.json")?;

    let mut settings: serde_json::Value =
        serde_json::from_str(&content).context("Failed to parse settings.json")?;

    let mut modified = false;

    // Remove hooks that contain "colgrep" in their commands
    if let Some(hooks) = settings.get_mut("hooks") {
        if let Some(hooks_obj) = hooks.as_object_mut() {
            for (_event_name, matchers) in hooks_obj.iter_mut() {
                if let Some(matchers_arr) = matchers.as_array_mut() {
                    // Filter out matchers that have colgrep-related hooks
                    let original_len = matchers_arr.len();
                    matchers_arr.retain(|matcher| {
                        if let Some(hooks_list) = matcher.get("hooks").and_then(|h| h.as_array()) {
                            // Check if any hook command contains "colgrep"
                            let has_colgrep = hooks_list.iter().any(|hook| {
                                hook.get("command")
                                    .and_then(|c| c.as_str())
                                    .map(|cmd| cmd.contains("colgrep"))
                                    .unwrap_or(false)
                            });
                            !has_colgrep // Keep only non-colgrep hooks
                        } else {
                            true // Keep if no hooks array
                        }
                    });
                    if matchers_arr.len() != original_len {
                        modified = true;
                    }
                }
            }

            // Remove empty hook event arrays
            let empty_events: Vec<String> = hooks_obj
                .iter()
                .filter(|(_, v)| v.as_array().map(|a| a.is_empty()).unwrap_or(false))
                .map(|(k, _)| k.clone())
                .collect();

            for event in empty_events {
                hooks_obj.remove(&event);
                modified = true;
            }
        }

        // If hooks object is now empty, remove it entirely
        if hooks.as_object().map(|o| o.is_empty()).unwrap_or(false) {
            if let Some(settings_obj) = settings.as_object_mut() {
                settings_obj.remove("hooks");
                modified = true;
            }
        }
    }

    if modified {
        let new_content =
            serde_json::to_string_pretty(&settings).context("Failed to serialize settings.json")?;
        fs::write(&settings_path, new_content).context("Failed to write settings.json")?;
    }

    Ok(modified)
}

/// Uninstall the colgrep plugin from Claude Code
pub fn uninstall_claude_code() -> Result<()> {
    let shell = get_shell();

    // Step 1: Remove hooks from settings.json
    println!("Removing colgrep hooks from settings...");
    match remove_hooks_from_settings() {
        Ok(true) => println!("{} Removed colgrep hooks from settings.json", "".green()),
        Ok(false) => println!("  No colgrep hooks found in settings.json"),
        Err(e) => eprintln!(
            "{} Failed to clean settings.json: {}",
            "Warning:".yellow(),
            e
        ),
    }

    // Step 2: Uninstall the plugin
    println!("Uninstalling colgrep plugin...");
    let plugin_uninstall = Command::new(&shell)
        .args(["-c", &format!("claude plugin uninstall {}", PLUGIN_NAME)])
        .output()
        .context("Failed to execute claude CLI")?;

    if !plugin_uninstall.status.success() {
        let stderr = String::from_utf8_lossy(&plugin_uninstall.stderr);
        eprintln!("{} Failed to uninstall plugin: {}", "Error:".red(), stderr);
        eprintln!(
            "{}",
            format!(
                "Do you have Claude Code version {} or higher installed?",
                MIN_CLAUDE_VERSION
            )
            .yellow()
        );
        // Continue to try removing from marketplace anyway
    } else {
        println!("{} Uninstalled colgrep plugin", "".green());
    }

    // Step 3: Remove from marketplace
    println!("Removing colgrep from marketplace...");
    let marketplace_remove = Command::new(&shell)
        .args([
            "-c",
            &format!("claude plugin marketplace remove {}", MARKETPLACE_ID),
        ])
        .output()
        .context("Failed to execute claude CLI")?;

    if !marketplace_remove.status.success() {
        let stderr = String::from_utf8_lossy(&marketplace_remove.stderr);
        eprintln!(
            "{} Failed to remove plugin from marketplace: {}",
            "Error:".red(),
            stderr
        );
        eprintln!(
            "{}",
            format!(
                "Do you have Claude Code version {} or higher installed?",
                MIN_CLAUDE_VERSION
            )
            .yellow()
        );
        // Continue to cleanup local files anyway
    } else {
        println!("{} Removed colgrep from marketplace", "".green());
    }

    // Step 4: Clean up local plugin files
    if let Ok(plugin_dir) = get_plugin_dir() {
        if plugin_dir.exists() {
            if let Err(e) = fs::remove_dir_all(&plugin_dir) {
                eprintln!(
                    "{} Failed to remove plugin files at {}: {}",
                    "Warning:".yellow(),
                    plugin_dir.display(),
                    e
                );
            } else {
                println!("{} Removed plugin files", "".green());
            }
        }
    }

    println!();
    println!(
        "{}",
        "Colgrep has been uninstalled from Claude Code.".green()
    );

    Ok(())
}

/// Get the appropriate shell for the current platform
fn get_shell() -> String {
    if cfg!(target_os = "windows") {
        std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string())
    } else {
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())
    }
}

/// Print success message and usage instructions after installation
fn print_install_success() {
    let border = "".repeat(70);

    println!();
    println!("{}", border.yellow());
    println!();
    println!(
        "  {} {}",
        "".green().bold(),
        "COLGREP INSTALLED FOR CLAUDE CODE".green().bold()
    );
    println!();
    println!("  Colgrep is now available as a semantic search tool in Claude Code.");
    println!("  Claude will automatically use colgrep for code searches.");
    println!();
    println!(
        "  {} {}",
        "".cyan(),
        "Restart Claude Code in a new terminal to enable colgrep.".bold()
    );
    println!();
    println!("  {}", "What happens:".cyan().bold());
    println!("    • Colgrep indexes your project on first search");
    println!("    • Subsequent searches use the cached index");
    println!("    • Index updates automatically when files change");
    println!();
    println!("  {}", "To uninstall:".cyan().bold());
    println!("    {}", "colgrep --uninstall-claude-code".green());
    println!();
    println!("{}", border.yellow());
    println!();
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use std::process::Command;

    /// Test that hook.json is valid JSON
    #[test]
    fn test_hook_json_is_valid() {
        let parsed: Result<Value, _> = serde_json::from_str(HOOK_JSON);
        assert!(
            parsed.is_ok(),
            "hook.json is not valid JSON: {:?}",
            parsed.err()
        );
    }

    /// Test that all hook commands produce valid JSON output
    #[test]
    fn test_hook_commands_produce_valid_json() {
        let hook_config: Value =
            serde_json::from_str(HOOK_JSON).expect("hook.json should be valid JSON");

        let hooks = hook_config
            .get("hooks")
            .expect("hook.json should have 'hooks' field");

        // Iterate through all hook events (SessionStart, PreToolUse, etc.)
        if let Value::Object(events) = hooks {
            for (event_name, matchers) in events {
                if let Value::Array(matcher_list) = matchers {
                    for matcher_entry in matcher_list {
                        let matcher = matcher_entry
                            .get("matcher")
                            .and_then(|m| m.as_str())
                            .unwrap_or("*");

                        if let Some(Value::Array(hook_list)) = matcher_entry.get("hooks") {
                            for hook in hook_list {
                                if let Some(command) = hook.get("command").and_then(|c| c.as_str())
                                {
                                    // Skip commands that run external tools (like colgrep --session-hook)
                                    // which require the actual binary to be installed
                                    if command.contains("colgrep") {
                                        continue;
                                    }

                                    // Execute the command and capture output
                                    let output = Command::new("sh")
                                        .args(["-c", command])
                                        .output()
                                        .expect("Failed to execute hook command");

                                    let stdout = String::from_utf8_lossy(&output.stdout);
                                    let stdout_trimmed = stdout.trim();

                                    // If the command produces output, it should be valid JSON
                                    if !stdout_trimmed.is_empty() {
                                        let parsed: Result<Value, _> =
                                            serde_json::from_str(stdout_trimmed);
                                        assert!(
                                            parsed.is_ok(),
                                            "Hook command for event '{}' matcher '{}' produced invalid JSON.\n\
                                             Command: {}\n\
                                             Output: {}\n\
                                             Error: {:?}",
                                            event_name,
                                            matcher,
                                            command,
                                            stdout_trimmed,
                                            parsed.err()
                                        );

                                        // Verify the JSON has the expected structure for PreToolUse hooks
                                        if event_name == "PreToolUse" {
                                            let json = parsed.unwrap();
                                            assert!(
                                                json.get("hookSpecificOutput").is_some(),
                                                "PreToolUse hook should have 'hookSpecificOutput' field.\n\
                                                 Command: {}\n\
                                                 Output: {}",
                                                command,
                                                stdout_trimmed
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Test that hook.json has required structure
    #[test]
    fn test_hook_json_structure() {
        let hook_config: Value =
            serde_json::from_str(HOOK_JSON).expect("hook.json should be valid JSON");

        // Should have description
        assert!(
            hook_config.get("description").is_some(),
            "hook.json should have 'description' field"
        );

        // Should have hooks object
        let hooks = hook_config
            .get("hooks")
            .expect("hook.json should have 'hooks' field");
        assert!(hooks.is_object(), "'hooks' should be an object");
    }
}