ripgrepx 0.4.0

Instant ripgrep via a persistent candidate index, for the terminal and AI agents over MCP
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
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! `rgx --agent install|uninstall|list|skill`: wire rgx into AI coding agents.
//!
//! An install only writes where rgx owns the namespace (Claude skill dir, Gemini extension), or, for
//! shared files (Codex AGENTS.md, Cursor/VS Code config), edits idempotently — a removable marked
//! block or a merged JSON key — never a blind append. MCP registration that belongs to a host's own
//! CLI is printed, not run. The skill text is version-controlled in `assets/skill.md` and embedded at
//! build time so the installed copy can't drift from the binary (see `CLAUDE.md`).

use std::io::{IsTerminal, Write as _};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};

const SKILL_MD: &str = include_str!("../assets/skill.md");
const VERSION: &str = env!("CARGO_PKG_VERSION");

const BLOCK_BEGIN: &str = "<!-- >>> rgx (managed) >>> -->";
const BLOCK_END: &str = "<!-- <<< rgx (managed) <<< -->";

const CURSOR_DESC: &str = "Prefer rgx over rg/grep/find/fd when searching this repo";

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Target {
    Claude,
    Codex,
    Cursor,
    Gemini,
    VsCode,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    User,
    Project,
}

impl Target {
    const ALL: [Target; 5] = [
        Target::Claude,
        Target::Codex,
        Target::Cursor,
        Target::Gemini,
        Target::VsCode,
    ];

    fn parse(s: &str) -> Option<Target> {
        match s.to_ascii_lowercase().as_str() {
            "claude" | "claude-code" | "claudecode" => Some(Target::Claude),
            "codex" => Some(Target::Codex),
            "cursor" => Some(Target::Cursor),
            "gemini" | "gemini-cli" => Some(Target::Gemini),
            "vscode" | "vs-code" | "code" | "copilot" => Some(Target::VsCode),
            _ => None,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Target::Claude => "Claude Code",
            Target::Codex => "Codex",
            Target::Cursor => "Cursor",
            Target::Gemini => "Gemini CLI",
            Target::VsCode => "VS Code",
        }
    }

    fn default_scope(self) -> Scope {
        match self {
            Target::Claude | Target::Codex | Target::Gemini => Scope::User,
            Target::Cursor | Target::VsCode => Scope::Project,
        }
    }

    fn supports(self, scope: Scope) -> bool {
        !(self == Target::Cursor && scope == Scope::User)
    }
}

impl Scope {
    fn label(self) -> &'static str {
        match self {
            Scope::User => "user",
            Scope::Project => "project",
        }
    }
}

/// Filesystem roots, injected so the installer is testable without touching a real `$HOME`.
pub struct Env {
    home: PathBuf,
    cwd: PathBuf,
}

impl Env {
    fn from_system() -> Result<Env> {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .context("HOME is not set")?;
        let cwd = std::env::current_dir().context("current directory")?;
        Ok(Env { home, cwd })
    }

    fn base(&self, scope: Scope) -> &Path {
        match scope {
            Scope::User => &self.home,
            Scope::Project => &self.cwd,
        }
    }
}

/// A single filesystem change an install will make. Built up front so the plan can be previewed and
/// confirmed before anything is written; `Note` is a manual step printed for the user (e.g. an
/// `mcp add` command rgx won't run itself).
enum Action {
    Write {
        path: PathBuf,
        contents: String,
    },
    MergeJson {
        path: PathBuf,
        root_key: &'static str,
    },
    Block {
        path: PathBuf,
        body: String,
    },
    Note(String),
}

struct Opts {
    targets: Vec<Target>,
    scope: Option<Scope>,
    yes: bool,
    dry_run: bool,
}

/// `rgx --agent skill`: print the skill document (no side effects).
pub fn print_skill() {
    print!("{SKILL_MD}");
}

/// `rgx --agent install [targets] [--user|--project] [--dry-run|--yes]`.
pub fn install_cli(args: &[String]) -> Result<()> {
    let opts = parse_args(args)?;
    let env = Env::from_system()?;
    let targets = resolve_targets(&opts.targets, &env)?;
    let mut plan = Vec::new();
    for t in targets {
        let sc = resolve_scope(t, opts.scope)?;
        plan.push((t, sc, plan_target(&env, t, sc)));
    }

    println!("rgx --agent install will make these changes:");
    for (t, sc, actions) in &plan {
        println!("\n{} ({}):", t.label(), sc.label());
        for a in actions {
            println!("  {}", describe(&env, a));
        }
    }

    if opts.dry_run {
        println!("\n(dry run — nothing written)");
        return Ok(());
    }
    if !opts.yes && !confirm_proceed("\nApply these changes?")? {
        println!("aborted; nothing written");
        return Ok(());
    }

    println!();
    for (t, sc, actions) in plan {
        println!("{} ({}):", t.label(), sc.label());
        for a in actions {
            match apply(a)? {
                Done::Wrote(p) => println!("  wrote   {}", p.display()),
                Done::Manual(n) => println!("  {n}"),
            }
        }
    }
    Ok(())
}

/// `rgx --agent uninstall [targets] [--user|--project] [--dry-run|--yes]`.
pub fn uninstall_cli(args: &[String]) -> Result<()> {
    let opts = parse_args(args)?;
    let env = Env::from_system()?;
    let targets = if opts.targets.is_empty() {
        Target::ALL.to_vec()
    } else {
        opts.targets
    };
    let mut plan = Vec::new();
    for t in targets {
        let sc = resolve_scope(t, opts.scope)?;
        plan.push((t, sc, pending_removals(&env, t, sc)));
    }
    if plan.iter().all(|(_, _, items)| items.is_empty()) {
        println!("nothing installed for the selected agents");
        return Ok(());
    }

    println!("rgx --agent uninstall will remove:");
    for (t, sc, items) in &plan {
        if items.is_empty() {
            continue;
        }
        println!("\n{} ({}):", t.label(), sc.label());
        for item in items {
            println!("  {item}");
        }
    }

    if opts.dry_run {
        println!("\n(dry run — nothing removed)");
        return Ok(());
    }
    if !opts.yes && !confirm_proceed("\nRemove these?")? {
        println!("aborted; nothing removed");
        return Ok(());
    }

    println!();
    for (t, sc, items) in plan {
        if items.is_empty() {
            continue;
        }
        let removed = uninstall_target(&env, t, sc)?;
        println!("{} ({}):", t.label(), sc.label());
        for line in removed {
            println!("  removed {line}");
        }
    }
    Ok(())
}

/// `rgx --agent list`: show each target, whether it's detected, and whether rgx is installed.
pub fn list() -> Result<()> {
    let env = Env::from_system()?;
    for t in Target::ALL {
        let detected = if detect(&env, t) { "detected" } else { "-" };
        let sc = t.default_scope();
        let installed = if is_installed(&env, t, sc) {
            "installed"
        } else {
            "-"
        };
        println!("  {:<12} {:<10} {}", t.label(), detected, installed);
    }
    Ok(())
}

fn parse_args(args: &[String]) -> Result<Opts> {
    let mut opts = Opts {
        targets: Vec::new(),
        scope: None,
        yes: false,
        dry_run: false,
    };
    for a in args {
        match a.as_str() {
            "--user" => opts.scope = Some(Scope::User),
            "--project" | "--repo" => opts.scope = Some(Scope::Project),
            "--yes" | "-y" => opts.yes = true,
            "--dry-run" | "-n" => opts.dry_run = true,
            s if s.starts_with('-') => bail!("unknown flag {s:?}"),
            s => opts.targets.push(Target::parse(s).with_context(|| {
                format!("unknown target {s:?} (use: claude, codex, cursor, gemini, vscode)")
            })?),
        }
    }
    Ok(opts)
}

fn resolve_scope(t: Target, scope: Option<Scope>) -> Result<Scope> {
    let sc = scope.unwrap_or_else(|| t.default_scope());
    if !t.supports(sc) {
        bail!("{} supports project scope only", t.label());
    }
    Ok(sc)
}

fn resolve_targets(requested: &[Target], env: &Env) -> Result<Vec<Target>> {
    if !requested.is_empty() {
        return Ok(requested.to_vec());
    }
    let found: Vec<Target> = Target::ALL
        .into_iter()
        .filter(|t| detect(env, *t))
        .collect();
    if found.is_empty() {
        bail!(
            "no agents detected; name one explicitly, e.g. `rgx --agent install claude`\n\
             targets: claude, codex, cursor, gemini, vscode"
        );
    }
    Ok(found)
}

fn detect(env: &Env, t: Target) -> bool {
    match t {
        Target::Claude => env.home.join(".claude").is_dir(),
        Target::Codex => env.home.join(".codex").is_dir(),
        Target::Gemini => env.home.join(".gemini").is_dir(),
        Target::Cursor => env.cwd.join(".cursor").is_dir() || env.home.join(".cursor").is_dir(),
        Target::VsCode => env.cwd.join(".vscode").is_dir() || on_path("code"),
    }
}

fn is_installed(env: &Env, t: Target, scope: Scope) -> bool {
    match t {
        Target::Claude => claude_skill(env, scope).is_file(),
        Target::Gemini => gemini_dir(env, scope)
            .join("gemini-extension.json")
            .is_file(),
        Target::Cursor => env.cwd.join(".cursor/rules/rgx.mdc").is_file(),
        Target::Codex => has_block(&codex_agents(env, scope)),
        Target::VsCode => json_has_rgx(&env.cwd.join(".vscode/mcp.json"), "servers"),
    }
}

fn plan_target(env: &Env, t: Target, scope: Scope) -> Vec<Action> {
    match t {
        Target::Claude => {
            let cmd = match scope {
                Scope::User => "claude mcp add rgx -- rgx --agent mcp",
                Scope::Project => "claude mcp add --scope project rgx -- rgx --agent mcp",
            };
            vec![
                Action::Write {
                    path: claude_skill(env, scope),
                    contents: SKILL_MD.to_string(),
                },
                Action::Note(format!("register MCP: {cmd}")),
            ]
        }
        Target::Codex => vec![
            Action::Block {
                path: codex_agents(env, scope),
                body: skill_body().to_string(),
            },
            Action::Note("register MCP: codex mcp add rgx -- rgx --agent mcp".to_string()),
        ],
        Target::Cursor => vec![
            Action::Write {
                path: env.cwd.join(".cursor/rules/rgx.mdc"),
                contents: format!(
                    "---\ndescription: {CURSOR_DESC}\nalwaysApply: true\n---\n\n{}",
                    skill_body()
                ),
            },
            Action::MergeJson {
                path: env.cwd.join(".cursor/mcp.json"),
                root_key: "mcpServers",
            },
        ],
        Target::Gemini => {
            let dir = gemini_dir(env, scope);
            let manifest = json!({
                "name": "rgx",
                "version": VERSION,
                "mcpServers": { "rgx": rgx_server() },
                "contextFileName": "GEMINI.md",
            });
            vec![
                Action::Write {
                    path: dir.join("gemini-extension.json"),
                    contents: format!("{}\n", to_pretty(&manifest).unwrap_or_default()),
                },
                Action::Write {
                    path: dir.join("GEMINI.md"),
                    contents: skill_body().to_string(),
                },
            ]
        }
        Target::VsCode => match scope {
            Scope::Project => vec![
                Action::MergeJson {
                    path: env.cwd.join(".vscode/mcp.json"),
                    root_key: "servers",
                },
                Action::Block {
                    path: env.cwd.join(".github/copilot-instructions.md"),
                    body: skill_body().to_string(),
                },
            ],
            Scope::User => vec![
                Action::Note(
                    "register MCP: code --add-mcp \
                     '{\"name\":\"rgx\",\"command\":\"rgx\",\"args\":[\"--agent\",\"mcp\"]}'"
                        .to_string(),
                ),
                Action::Note(
                    "add the skill to your user copilot-instructions in VS Code settings"
                        .to_string(),
                ),
            ],
        },
    }
}

enum Done {
    Wrote(PathBuf),
    Manual(String),
}

fn apply(action: Action) -> Result<Done> {
    match action {
        Action::Write { path, contents } => {
            write_file(&path, &contents)?;
            Ok(Done::Wrote(path))
        }
        Action::MergeJson { path, root_key } => {
            merge_mcp_json(&path, root_key)?;
            Ok(Done::Wrote(path))
        }
        Action::Block { path, body } => {
            upsert_block(&path, &body)?;
            Ok(Done::Wrote(path))
        }
        Action::Note(n) => Ok(Done::Manual(n)),
    }
}

fn describe(env: &Env, action: &Action) -> String {
    let _ = env;
    match action {
        Action::Write { path, .. } => {
            let verb = if path.is_file() {
                "overwrite"
            } else {
                "create"
            };
            format!("{verb} {}", path.display())
        }
        Action::MergeJson { path, root_key } => {
            if path.exists() {
                format!("add \"rgx\" to {} ({root_key})", path.display())
            } else {
                format!("create {} with the \"rgx\" server", path.display())
            }
        }
        Action::Block { path, .. } => {
            if has_block(path) {
                format!("update the rgx block in {}", path.display())
            } else if path.exists() {
                format!("add an rgx block to {}", path.display())
            } else {
                format!("create {}", path.display())
            }
        }
        Action::Note(n) => format!("you then run: {n}"),
    }
}

fn pending_removals(env: &Env, t: Target, scope: Scope) -> Vec<String> {
    let mut items = Vec::new();
    let file = |p: PathBuf, items: &mut Vec<String>| {
        if p.is_file() {
            items.push(p.display().to_string());
        }
    };
    match t {
        Target::Claude => file(claude_skill(env, scope), &mut items),
        Target::Gemini => {
            let dir = gemini_dir(env, scope);
            if dir.is_dir() {
                items.push(dir.display().to_string());
            }
        }
        Target::Cursor => {
            file(env.cwd.join(".cursor/rules/rgx.mdc"), &mut items);
            if json_has_rgx(&env.cwd.join(".cursor/mcp.json"), "mcpServers") {
                items.push(format!(
                    "{} (rgx key)",
                    env.cwd.join(".cursor/mcp.json").display()
                ));
            }
        }
        Target::Codex => {
            let p = codex_agents(env, scope);
            if has_block(&p) {
                items.push(format!("{} (rgx block)", p.display()));
            }
        }
        Target::VsCode => {
            if json_has_rgx(&env.cwd.join(".vscode/mcp.json"), "servers") {
                items.push(format!(
                    "{} (rgx key)",
                    env.cwd.join(".vscode/mcp.json").display()
                ));
            }
            let instr = env.cwd.join(".github/copilot-instructions.md");
            if has_block(&instr) {
                items.push(format!("{} (rgx block)", instr.display()));
            }
        }
    }
    items
}

fn confirm_proceed(prompt: &str) -> Result<bool> {
    if !std::io::stdin().is_terminal() {
        bail!("not a terminal; re-run with --yes to apply, or --dry-run to preview");
    }
    print!("{prompt} [y/N] ");
    std::io::stdout().flush().ok();
    let mut line = String::new();
    std::io::stdin().read_line(&mut line)?;
    Ok(matches!(
        line.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}

#[cfg(test)]
fn install_target(env: &Env, t: Target, scope: Scope) -> Result<()> {
    for action in plan_target(env, t, scope) {
        apply(action)?;
    }
    Ok(())
}

fn uninstall_target(env: &Env, t: Target, scope: Scope) -> Result<Vec<String>> {
    let mut removed = Vec::new();
    match t {
        Target::Claude => remove_file_into(&claude_skill(env, scope), &mut removed),
        Target::Gemini => {
            let dir = gemini_dir(env, scope);
            if dir.is_dir() {
                std::fs::remove_dir_all(&dir)
                    .with_context(|| format!("remove {}", dir.display()))?;
                removed.push(dir.display().to_string());
            }
        }
        Target::Cursor => {
            remove_file_into(&env.cwd.join(".cursor/rules/rgx.mdc"), &mut removed);
            remove_mcp_json(
                &env.cwd.join(".cursor/mcp.json"),
                "mcpServers",
                &mut removed,
            )?;
        }
        Target::Codex => remove_block_into(&codex_agents(env, scope), &mut removed)?,
        Target::VsCode => {
            remove_mcp_json(&env.cwd.join(".vscode/mcp.json"), "servers", &mut removed)?;
            remove_block_into(
                &env.cwd.join(".github/copilot-instructions.md"),
                &mut removed,
            )?;
        }
    }
    Ok(removed)
}

fn claude_skill(env: &Env, scope: Scope) -> PathBuf {
    env.base(scope).join(".claude/skills/rgx/SKILL.md")
}

fn codex_agents(env: &Env, scope: Scope) -> PathBuf {
    match scope {
        Scope::User => env.home.join(".codex/AGENTS.md"),
        Scope::Project => env.cwd.join("AGENTS.md"),
    }
}

fn gemini_dir(env: &Env, scope: Scope) -> PathBuf {
    env.base(scope).join(".gemini/extensions/rgx")
}

fn rgx_server() -> Value {
    json!({ "command": "rgx", "args": ["--agent", "mcp"] })
}

fn skill_body() -> &'static str {
    if let Some(rest) = SKILL_MD.strip_prefix("---\n")
        && let Some(idx) = rest.find("\n---\n")
    {
        return rest[idx + 5..].trim_start_matches('\n');
    }
    SKILL_MD
}

fn write_file(path: &Path, contents: &str) -> Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    }
    std::fs::write(path, contents).with_context(|| format!("write {}", path.display()))
}

fn remove_file_into(path: &Path, removed: &mut Vec<String>) {
    if path.is_file() && std::fs::remove_file(path).is_ok() {
        removed.push(path.display().to_string());
    }
}

fn to_pretty(v: &Value) -> Result<String> {
    serde_json::to_string_pretty(v).context("serialize JSON")
}

fn merge_mcp_json(path: &Path, root_key: &str) -> Result<()> {
    let mut root = read_json(path)?;
    let obj = root
        .as_object_mut()
        .with_context(|| format!("{} is not a JSON object", path.display()))?;
    let servers = obj
        .entry(root_key)
        .or_insert_with(|| Value::Object(Map::new()))
        .as_object_mut()
        .with_context(|| format!("{root_key} in {} is not an object", path.display()))?;
    servers.insert("rgx".to_string(), rgx_server());
    write_file(path, &format!("{}\n", to_pretty(&root)?))
}

fn remove_mcp_json(path: &Path, root_key: &str, removed: &mut Vec<String>) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let mut root = read_json(path)?;
    let gone = root
        .as_object_mut()
        .and_then(|o| o.get_mut(root_key))
        .and_then(|s| s.as_object_mut())
        .map(|s| s.remove("rgx").is_some())
        .unwrap_or(false);
    if gone {
        write_file(path, &format!("{}\n", to_pretty(&root)?))?;
        removed.push(format!("{} (rgx key)", path.display()));
    }
    Ok(())
}

fn read_json(path: &Path) -> Result<Value> {
    if !path.exists() {
        return Ok(Value::Object(Map::new()));
    }
    let text = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    if text.trim().is_empty() {
        return Ok(Value::Object(Map::new()));
    }
    serde_json::from_str(&text).with_context(|| format!("parse {}", path.display()))
}

fn json_has_rgx(path: &Path, root_key: &str) -> bool {
    read_json(path)
        .ok()
        .and_then(|v| v.get(root_key).and_then(|s| s.get("rgx")).map(|_| ()))
        .is_some()
}

fn block_text(body: &str) -> String {
    format!("{BLOCK_BEGIN}\n{}\n{BLOCK_END}\n", body.trim())
}

fn upsert_block(path: &Path, body: &str) -> Result<()> {
    let existing = if path.exists() {
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?
    } else {
        String::new()
    };
    let block = block_text(body);
    let new = match find_block(&existing) {
        Some((s, e)) => format!("{}{}{}", &existing[..s], block, &existing[e..]),
        None if existing.trim().is_empty() => block,
        None => format!("{}\n\n{}", existing.trim_end(), block),
    };
    write_file(path, &new)
}

fn remove_block_into(path: &Path, removed: &mut Vec<String>) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let existing =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    if let Some((s, e)) = find_block(&existing) {
        let trimmed = format!("{}{}", &existing[..s], &existing[e..]);
        let trimmed = trimmed.trim();
        if trimmed.is_empty() {
            std::fs::remove_file(path).with_context(|| format!("remove {}", path.display()))?;
        } else {
            write_file(path, &format!("{trimmed}\n"))?;
        }
        removed.push(format!("{} (rgx block)", path.display()));
    }
    Ok(())
}

fn has_block(path: &Path) -> bool {
    std::fs::read_to_string(path)
        .map(|s| find_block(&s).is_some())
        .unwrap_or(false)
}

fn find_block(s: &str) -> Option<(usize, usize)> {
    let start = s.find(BLOCK_BEGIN)?;
    let end_marker = s[start..].find(BLOCK_END)? + start + BLOCK_END.len();
    let end = s[end_marker..]
        .find('\n')
        .map(|n| end_marker + n + 1)
        .unwrap_or(end_marker);
    Some((start, end))
}

fn on_path(bin: &str) -> bool {
    std::env::var_os("PATH")
        .map(|paths| {
            std::env::split_paths(&paths)
                .any(|dir| dir.join(bin).is_file() || dir.join(format!("{bin}.exe")).is_file())
        })
        .unwrap_or(false)
}

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

    fn temp_env() -> (tempfile::TempDir, Env) {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().join("home");
        let cwd = dir.path().join("repo");
        std::fs::create_dir_all(&home).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        let env = Env { home, cwd };
        (dir, env)
    }

    #[test]
    fn installs_every_target_into_its_own_namespace() {
        let (_d, env) = temp_env();
        for t in Target::ALL {
            let scope = t.default_scope();
            install_target(&env, t, scope).unwrap();
        }
        assert!(env.home.join(".claude/skills/rgx/SKILL.md").is_file());
        assert!(
            env.home
                .join(".gemini/extensions/rgx/gemini-extension.json")
                .is_file()
        );
        assert!(env.home.join(".gemini/extensions/rgx/GEMINI.md").is_file());
        assert!(env.cwd.join(".cursor/rules/rgx.mdc").is_file());
        assert!(env.cwd.join(".cursor/mcp.json").is_file());
        assert!(has_block(&env.home.join(".codex/AGENTS.md")));
        assert!(env.cwd.join(".vscode/mcp.json").is_file());
        assert!(has_block(&env.cwd.join(".github/copilot-instructions.md")));

        let mdc = std::fs::read_to_string(env.cwd.join(".cursor/rules/rgx.mdc")).unwrap();
        assert!(mdc.starts_with("---\n"));
        assert!(mdc.contains("alwaysApply: true"));
    }

    #[test]
    fn merge_preserves_existing_servers_and_is_idempotent() {
        let (_d, env) = temp_env();
        let mcp = env.cwd.join(".vscode/mcp.json");
        write_file(
            &mcp,
            "{\n  \"servers\": { \"other\": { \"command\": \"x\" } }\n}\n",
        )
        .unwrap();
        merge_mcp_json(&mcp, "servers").unwrap();
        merge_mcp_json(&mcp, "servers").unwrap();
        let v = read_json(&mcp).unwrap();
        assert!(v["servers"]["other"].is_object());
        assert_eq!(v["servers"]["rgx"]["command"], "rgx");
    }

    #[test]
    fn block_upsert_is_idempotent_and_preserves_surrounding_text() {
        let (_d, env) = temp_env();
        let path = env.cwd.join("AGENTS.md");
        write_file(&path, "# Project\n\nHand-written notes.\n").unwrap();
        upsert_block(&path, "first").unwrap();
        upsert_block(&path, "second").unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert_eq!(text.matches(BLOCK_BEGIN).count(), 1);
        assert!(text.contains("Hand-written notes."));
        assert!(text.contains("second"));
        assert!(!text.contains("first"));
    }

    #[test]
    fn uninstall_removes_block_and_json_key_but_keeps_user_content() {
        let (_d, env) = temp_env();
        install_target(&env, Target::Codex, Scope::User).unwrap();
        let agents = codex_agents(&env, Scope::User);
        std::fs::write(
            &agents,
            format!("# Mine\n\n{}", std::fs::read_to_string(&agents).unwrap()),
        )
        .unwrap();
        let removed = uninstall_target(&env, Target::Codex, Scope::User).unwrap();
        assert!(!removed.is_empty());
        let text = std::fs::read_to_string(&agents).unwrap();
        assert!(text.contains("# Mine"));
        assert!(!text.contains(BLOCK_BEGIN));

        install_target(&env, Target::VsCode, Scope::Project).unwrap();
        uninstall_target(&env, Target::VsCode, Scope::Project).unwrap();
        assert!(!json_has_rgx(&env.cwd.join(".vscode/mcp.json"), "servers"));
    }

    #[test]
    fn cursor_rejects_user_scope() {
        assert!(resolve_scope(Target::Cursor, Some(Scope::User)).is_err());
        assert!(resolve_scope(Target::Cursor, None).is_ok());
    }
}