bctx 0.1.38

bctx CLI — intercept CLI commands and compress output for LLM coding agents
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
use super::agent_config;
use super::init::{
    owners_path, read_owners, write_owners, CLAUDE_MD_STUB, GOOSE_END, GOOSE_START,
    SHELL_HOOK_OWNERS, SUPPORTED_AGENTS, VSCODE_MCP_OWNERS,
};
use anyhow::Result;
use std::path::{Path, PathBuf};

const SHELLS: &[&str] = &["zsh", "bash", "fish"];

// ── Public entry point ────────────────────────────────────────────────────────

pub fn handle(agent: Option<String>) -> Result<()> {
    match agent.as_deref() {
        Some(name) => {
            let was_configured = is_configured(name);
            uninstall_agent(name)?;
            match read_owners(SHELL_HOOK_OWNERS) {
                Some(mut owners) => {
                    owners.retain(|o| o != name);
                    if owners.is_empty() {
                        remove_all_shell_hooks()?;
                        std::fs::remove_file(owners_path(SHELL_HOOK_OWNERS)).ok();
                    } else {
                        write_owners(SHELL_HOOK_OWNERS, &owners)?;
                    }
                }
                // Installed before the owner list existed: go by what is still configured.
                None if was_configured => remove_shell_hooks_if_last(name)?,
                None => {}
            }
        }
        None => {
            let mut removed = 0u32;
            for name in SUPPORTED_AGENTS {
                if is_configured(name) {
                    println!("Removing: {name}");
                    uninstall_agent(name)?;
                    removed += 1;
                    println!();
                }
            }
            std::fs::remove_file(owners_path(SHELL_HOOK_OWNERS)).ok();
            // Every agent is gone, so nothing relies on the shared VS Code entry any more.
            if read_owners(VSCODE_MCP_OWNERS).is_some() {
                std::fs::remove_file(owners_path(VSCODE_MCP_OWNERS)).ok();
                remove_shared_vscode_entry(&super::home_dir())?;
            }
            if removed == 0 {
                println!("No bctx agent configurations found.");
                println!("Run with --agent to remove a specific agent:");
                for name in SUPPORTED_AGENTS {
                    println!("  bctx uninstall --agent {name}");
                }
            }
        }
    }
    Ok(())
}

/// For installs without an owner list: the shared shell hook goes when the last configured
/// agent goes. While any other agent remains, the hook stays.
fn remove_shell_hooks_if_last(removed: &str) -> Result<()> {
    if SHELLS.contains(&removed) {
        return Ok(());
    }
    if SUPPORTED_AGENTS
        .iter()
        .any(|a| !SHELLS.contains(a) && is_configured(a))
    {
        return Ok(());
    }
    remove_all_shell_hooks()
}

fn remove_all_shell_hooks() -> Result<()> {
    for shell in SHELLS {
        if is_configured(shell) {
            uninstall_agent(shell)?;
        }
    }
    Ok(())
}

// ── Detection (was bctx ever configured for this agent?) ─────────────────────

fn is_configured(agent: &str) -> bool {
    let home = super::home_dir();
    let h = |rel: &str| PathBuf::from(&home).join(rel);

    match agent {
        "claude" => {
            has_bctx_mcp_key(&h(".claude.json"), "mcpServers")
                || has_bctx_mcp_key(&h(".claude/mcp.json"), "mcpServers")
                || h(".claude/bctx-hook.sh").exists()
        }
        "cursor" => has_bctx_mcp_key(&h(".cursor/mcp.json"), "mcpServers"),
        "windsurf" => has_bctx_mcp_key(&h(".codeium/windsurf/mcp_config.json"), "mcpServers"),
        "gemini" => has_bctx_mcp_key(&h(".gemini/settings.json"), "mcpServers"),
        "zed" => has_bctx_mcp_key(&h(".config/zed/settings.json"), "context_servers"),
        "continue" => has_bctx_continue_entry(&h(".continue/config.json")),
        "cline" | "roo" | "copilot" => {
            #[cfg(target_os = "macos")]
            {
                let p = PathBuf::from(&home).join("Library/Application Support/Code/User/mcp.json");
                has_bctx_mcp_key(&p, "servers")
            }
            #[cfg(not(target_os = "macos"))]
            {
                let p = h(".config/Code/User/mcp.json");
                has_bctx_mcp_key(&p, "servers")
            }
        }
        "antigravity" => has_bctx_mcp_key(&h(".gemini/antigravity/mcp_config.json"), "mcpServers"),
        "amazonq" => has_bctx_mcp_key(&h(".aws/amazonq/mcp.json"), "mcpServers"),
        "kiro" => has_bctx_mcp_key(&h(".kiro/settings/mcp.json"), "mcpServers"),
        "codex" => has_bctx_mcp_key(&h(".codex/mcp.json"), "mcpServers"),
        "trae" => {
            #[cfg(target_os = "macos")]
            {
                let p = PathBuf::from(&home).join("Library/Application Support/Trae/User/mcp.json");
                has_bctx_mcp_key(&p, "servers")
            }
            #[cfg(not(target_os = "macos"))]
            false
        }
        "aider" => file_contains(&h(".aider.conf.yml"), AIDER_START),
        "goose" => file_contains(&h(".config/goose/config.yaml"), GOOSE_START),
        "jetbrains" => jetbrains_mcp_files(&home)
            .iter()
            .any(|p| has_bctx_mcp_key(p, "mcpServers")),
        "opencode" => has_bctx_mcp_key(&h(".opencode/config.json"), "mcpServers"),
        "amp" => has_bctx_mcp_key(&h(".config/amp/settings.json"), "amp.mcpServers"),
        "pear" => has_bctx_mcp_key(&vscode_family_mcp(&home, "PearAI"), "servers"),
        "void" => has_bctx_mcp_key(&vscode_family_mcp(&home, "Void"), "servers"),
        "neovim" => h(NEOVIM_SNIPPET).exists(),
        "zsh" => shell_has_bctx_hook(&h(".zshrc")),
        "bash" => shell_has_bctx_hook(&h(".bashrc")) || shell_has_bctx_hook(&h(".bash_profile")),
        "fish" => h(FISH_HOOK).exists(),
        _ => false,
    }
}

const AIDER_START: &str = "# bctx — route git/bash through the context-aware lens pipeline";
const AIDER_END: &str = "# bctx binary:";
/// How entries written before 0.1.37 ended: their last line was the `- mcp` argument.
const GOOSE_END_BEFORE_0_1_37: &str = "- mcp";
const NEOVIM_SNIPPET: &str = ".config/nvim/lua/bctx_mcp.lua";
const FISH_HOOK: &str = ".config/fish/conf.d/bctx.fish";

fn file_contains(path: &Path, needle: &str) -> bool {
    std::fs::read_to_string(path).is_ok_and(|s| s.contains(needle))
}

/// `mcp.json` of a VSCode-family editor (PearAI, Void), where `init` writes `servers.bctx`.
fn vscode_family_mcp(home: &str, app: &str) -> PathBuf {
    #[cfg(target_os = "macos")]
    let base = PathBuf::from(home).join("Library/Application Support");
    #[cfg(not(target_os = "macos"))]
    let base = PathBuf::from(home).join(".config");
    base.join(app).join("User/mcp.json")
}

/// One `mcp.json` per installed JetBrains IDE settings directory.
fn jetbrains_mcp_files(home: &str) -> Vec<PathBuf> {
    #[cfg(target_os = "macos")]
    let root = PathBuf::from(home).join("Library/Application Support/JetBrains");
    #[cfg(not(target_os = "macos"))]
    let root = PathBuf::from(home).join(".config/JetBrains");
    std::fs::read_dir(root)
        .map(|rd| {
            rd.flatten()
                .map(|e| e.path())
                .filter(|p| p.is_dir())
                .map(|p| p.join("mcp.json"))
                .collect()
        })
        .unwrap_or_default()
}

// Detection is read-only, so a JSONC config that lists bctx counts as configured.
fn has_bctx_mcp_key(path: &Path, key: &str) -> bool {
    let Ok(raw) = std::fs::read_to_string(path) else {
        return false;
    };
    let Some(cfg) = agent_config::parse_lenient(&raw) else {
        return false;
    };
    cfg[key].get("bctx").is_some()
}

fn has_bctx_continue_entry(path: &Path) -> bool {
    let Ok(raw) = std::fs::read_to_string(path) else {
        return false;
    };
    let Some(cfg) = agent_config::parse_lenient(&raw) else {
        return false;
    };
    cfg["mcpServers"].as_array().is_some_and(|arr| {
        arr.iter()
            .any(|e| e.get("name").and_then(|v| v.as_str()) == Some("bctx"))
    })
}

fn shell_has_bctx_hook(path: &Path) -> bool {
    std::fs::read_to_string(path).is_ok_and(|s| s.contains("# bctx —"))
}

// ── Dispatch ──────────────────────────────────────────────────────────────────

fn uninstall_agent(agent: &str) -> Result<()> {
    match agent {
        "claude" => uninstall_claude(),
        "cursor" => uninstall_cursor(),
        "windsurf" => uninstall_windsurf(),
        "gemini" => uninstall_gemini(),
        "zed" => uninstall_zed(),
        "continue" => uninstall_continue(),
        "cline" | "roo" => uninstall_vscode_extension(agent),
        "copilot" => uninstall_vscode_extension("copilot"),
        "antigravity" => uninstall_antigravity(),
        "amazonq" => uninstall_amazonq(),
        "kiro" => uninstall_kiro(),
        "codex" => uninstall_codex(),
        "trae" => uninstall_trae(),
        "aider" => uninstall_aider(),
        "goose" => {
            let path = home_path(".config/goose/config.yaml");
            let current = std::fs::read_to_string(&path).unwrap_or_default();
            let end = if current.contains(GOOSE_END) {
                GOOSE_END
            } else {
                GOOSE_END_BEFORE_0_1_37
            };
            remove_block(&path, GOOSE_START, end)
        }
        "jetbrains" => jetbrains_mcp_files(&super::home_dir())
            .iter()
            .try_for_each(|p| remove_mcp_key(p, "mcpServers")),
        "opencode" => remove_mcp_key(&home_path(".opencode/config.json"), "mcpServers"),
        "amp" => remove_mcp_key(&home_path(".config/amp/settings.json"), "amp.mcpServers"),
        "pear" => remove_servers_key(&vscode_family_mcp(&super::home_dir(), "PearAI")),
        "void" => remove_servers_key(&vscode_family_mcp(&super::home_dir(), "Void")),
        "neovim" => uninstall_neovim(),
        "zsh" => uninstall_shell("zsh"),
        "bash" => uninstall_shell("bash"),
        "fish" => uninstall_shell("fish"),
        other => {
            eprintln!("bctx uninstall: unknown agent '{other}'");
            eprintln!("Supported agents:");
            for name in SUPPORTED_AGENTS {
                eprintln!("  {name}");
            }
            std::process::exit(1);
        }
    }
}

// ── Claude Code ───────────────────────────────────────────────────────────────

fn uninstall_claude() -> Result<()> {
    let home = super::home_dir();
    let claude_dir = PathBuf::from(&home).join(".claude");

    // ~/.claude.json
    let claude_json = PathBuf::from(&home).join(".claude.json");
    remove_mcp_key(&claude_json, "mcpServers")?;

    // ~/.claude/mcp.json (Claude Code desktop / current CLI format)
    let claude_mcp = claude_dir.join("mcp.json");
    remove_mcp_key(&claude_mcp, "mcpServers")?;

    // VSCode extension mcp.json (macOS)
    #[cfg(target_os = "macos")]
    release_vscode_entry(&home, "claude")?;

    // settings.json — remove the bctx-hook entry from PreToolUse and the mcp__bctx__* allows
    let settings_path = claude_dir.join("settings.json");
    let settings = std::fs::read_to_string(&settings_path)
        .ok()
        .and_then(|raw| parse_for_removal(&settings_path, &raw, settings_list_bctx));
    if let Some(mut cfg) = settings {
        let mut changed = false;
        // pointer_mut, not cfg["a"]["b"]: indexing inserts missing keys as null.
        if let Some(arr) = cfg
            .pointer_mut("/hooks/PreToolUse")
            .and_then(serde_json::Value::as_array_mut)
        {
            let before = arr.len();
            arr.retain(|h| {
                !h["hooks"]
                    .as_array()
                    .and_then(|hs| hs.first())
                    .and_then(|h| h["command"].as_str())
                    .is_some_and(|c| c.contains("bctx-hook"))
            });
            changed |= arr.len() < before;
        }
        if let Some(arr) = cfg
            .pointer_mut("/permissions/allow")
            .and_then(serde_json::Value::as_array_mut)
        {
            let before = arr.len();
            arr.retain(|p| !p.as_str().is_some_and(|s| s.starts_with("mcp__bctx__")));
            changed |= arr.len() < before;
        }
        if changed {
            std::fs::write(&settings_path, serde_json::to_string_pretty(&cfg)?)?;
            println!("  ✓ settings.json hook entry and bctx skill permissions removed");
        }
    }

    // rules/bctx.md is ours; CLAUDE.md only while it is still exactly what init wrote
    remove_file_if(&claude_dir.join("rules/bctx.md"), |_| true)?;
    let rules_dir = claude_dir.join("rules");
    if std::fs::read_dir(&rules_dir).is_ok_and(|mut rd| rd.next().is_none()) {
        std::fs::remove_dir(&rules_dir)?;
    }
    let claude_md = claude_dir.join("CLAUDE.md");
    remove_file_if(&claude_md, |content| content == CLAUDE_MD_STUB)?;
    if file_contains(&claude_md, "@rules/bctx.md") {
        println!(
            "  → {} still imports @rules/bctx.md (you edited it); remove that section by hand",
            claude_md.display()
        );
    }

    // bctx-hook.sh
    let hook_path = claude_dir.join("bctx-hook.sh");
    if hook_path.exists() {
        std::fs::remove_file(&hook_path)?;
        println!("  ✓ bctx-hook.sh removed");
    }

    println!("  → Restart Claude Code to deactivate.");
    Ok(())
}

// ── Cursor ────────────────────────────────────────────────────────────────────

fn uninstall_cursor() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".cursor/mcp.json");
    remove_mcp_key(&path, "mcpServers")?;

    #[cfg(target_os = "macos")]
    remove_vscode_mcp_entry(&home, "Cursor/User")?;

    println!("  → Restart Cursor to deactivate.");
    Ok(())
}

// ── Windsurf ──────────────────────────────────────────────────────────────────

fn uninstall_windsurf() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".codeium/windsurf/mcp_config.json");
    remove_mcp_key(&path, "mcpServers")?;

    #[cfg(target_os = "macos")]
    remove_vscode_mcp_entry(&home, "Windsurf/User")?;

    println!("  → Restart Windsurf to deactivate.");
    Ok(())
}

// ── Gemini CLI ────────────────────────────────────────────────────────────────

fn uninstall_gemini() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".gemini/settings.json");
    remove_mcp_key(&path, "mcpServers")?;
    println!("  → Restart Gemini CLI to deactivate.");
    Ok(())
}

// ── Zed ───────────────────────────────────────────────────────────────────────

fn uninstall_zed() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".config/zed/settings.json");
    remove_mcp_key(&path, "context_servers")?;
    println!("  → Restart Zed to deactivate.");
    Ok(())
}

// ── Continue ──────────────────────────────────────────────────────────────────

fn uninstall_continue() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".continue/config.json");
    if !path.exists() {
        return Ok(());
    }
    let raw = std::fs::read_to_string(&path)?;
    let lists_bctx = |c: &serde_json::Value| {
        c["mcpServers"].as_array().is_some_and(|arr| {
            arr.iter()
                .any(|e| e.get("name").and_then(|v| v.as_str()) == Some("bctx"))
        })
    };
    let Some(mut cfg) = parse_for_removal(&path, &raw, lists_bctx) else {
        return Ok(());
    };
    if let Some(arr) = cfg
        .get_mut("mcpServers")
        .and_then(serde_json::Value::as_array_mut)
    {
        let before = arr.len();
        arr.retain(|e| e.get("name").and_then(|v| v.as_str()) != Some("bctx"));
        if arr.len() < before {
            std::fs::write(&path, serde_json::to_string_pretty(&cfg)?)?;
            println!("  ✓ ~/.continue/config.json — bctx entry removed");
        }
    }
    println!("  → Reload Continue extension to deactivate.");
    Ok(())
}

// ── VSCode extensions (Cline, Roo Code, Copilot) ─────────────────────────────

fn uninstall_vscode_extension(label: &str) -> Result<()> {
    release_vscode_entry(&super::home_dir(), label)?;
    println!("  ({label}) → Reload VSCode window to deactivate.");
    Ok(())
}

/// The VS Code `mcp.json` entry is shared: it goes only when the last agent relying on it is
/// uninstalled. Installs from before the owner list remove it, as they always did.
fn release_vscode_entry(home: &str, agent: &str) -> Result<()> {
    if let Some(mut owners) = read_owners(VSCODE_MCP_OWNERS) {
        owners.retain(|o| o != agent);
        if !owners.is_empty() {
            write_owners(VSCODE_MCP_OWNERS, &owners)?;
            println!(
                "  (VS Code mcp.json entry kept: {} still use it)",
                owners.join(", ")
            );
            return Ok(());
        }
        std::fs::remove_file(owners_path(VSCODE_MCP_OWNERS)).ok();
    }
    remove_shared_vscode_entry(home)
}

fn remove_shared_vscode_entry(home: &str) -> Result<()> {
    #[cfg(target_os = "macos")]
    remove_vscode_mcp_entry(home, "Code/User")?;
    #[cfg(not(target_os = "macos"))]
    remove_servers_key(&PathBuf::from(home).join(".config/Code/User/mcp.json"))?;
    Ok(())
}

// ── Antigravity ───────────────────────────────────────────────────────────────

fn uninstall_antigravity() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".gemini/antigravity/mcp_config.json");
    remove_mcp_key(&path, "mcpServers")?;

    #[cfg(target_os = "macos")]
    remove_vscode_mcp_entry(&home, "Antigravity/User")?;

    println!("  → Restart Antigravity to deactivate.");
    Ok(())
}

// ── Amazon Q ──────────────────────────────────────────────────────────────────

fn uninstall_amazonq() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".aws/amazonq/mcp.json");
    remove_mcp_key(&path, "mcpServers")?;
    println!("  → Restart Amazon Q to deactivate.");
    Ok(())
}

// ── AWS Kiro ──────────────────────────────────────────────────────────────────

fn uninstall_kiro() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".kiro/settings/mcp.json");
    remove_mcp_key(&path, "mcpServers")?;
    println!("  → Restart Kiro to deactivate.");
    Ok(())
}

// ── OpenAI Codex CLI ──────────────────────────────────────────────────────────

fn uninstall_codex() -> Result<()> {
    let home = super::home_dir();
    let path = PathBuf::from(&home).join(".codex/mcp.json");
    remove_mcp_key(&path, "mcpServers")?;
    println!("  → Restart Codex CLI to deactivate.");
    Ok(())
}

// ── Trae (ByteDance) ──────────────────────────────────────────────────────────

fn uninstall_trae() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        let home = super::home_dir();
        remove_vscode_mcp_entry(&home, "Trae/User")?;
    }
    println!("  → Restart Trae to deactivate.");
    Ok(())
}

// ── Shell aliases (bash/zsh) ──────────────────────────────────────────────────

fn uninstall_shell(shell: &str) -> Result<()> {
    let home = super::home_dir();
    if shell == "fish" {
        return remove_file_if(&home_path(FISH_HOOK), |_| true);
    }
    let candidates: &[&str] = match shell {
        "zsh" => &[".zshrc"],
        "bash" => &[".bashrc", ".bash_profile"],
        _ => unreachable!(),
    };

    for rel in candidates {
        let path = PathBuf::from(&home).join(rel);
        remove_shell_hook(&path)?;
    }
    Ok(())
}

fn remove_shell_hook(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let content = std::fs::read_to_string(path)?;
    if !content.contains("# bctx —") {
        return Ok(());
    }
    if !end_follows_start(
        &content,
        |l| l.contains("# bctx —"),
        |l| l.starts_with("unset _bctx_cmd") || l.starts_with("# bctx end"),
    ) {
        println!(
            "  → {}: the bctx block has no end marker; left as is, remove it by hand",
            path.display()
        );
        return Ok(());
    }

    // Remove everything from `# bctx —` line through `unset _bctx_cmd` line (inclusive),
    // plus the blank line that init prepended.
    let mut output = String::with_capacity(content.len());
    let mut skip = false;
    for line in content.lines() {
        if line.contains("# bctx —") {
            skip = true;
            // Also drop the preceding blank line that was added by init
            if output.ends_with('\n') {
                output.truncate(output.trim_end_matches('\n').len());
                if !output.is_empty() {
                    output.push('\n');
                }
            }
            continue;
        }
        if skip {
            if line.starts_with("unset _bctx_cmd") || line.starts_with("# bctx end") {
                skip = false;
            }
            continue;
        }
        output.push_str(line);
        output.push('\n');
    }

    std::fs::write(path, &output)?;
    println!("  ✓ {} — bctx hook removed", path.display());
    println!("  → Run: source {}", path.display());
    Ok(())
}

// ── Aider, Neovim ─────────────────────────────────────────────────────────────

fn uninstall_aider() -> Result<()> {
    remove_block(&home_path(".aider.conf.yml"), AIDER_START, AIDER_END)?;
    remove_file_if(&home_path(".bctx/aider-hook.sh"), |_| true)
}

fn uninstall_neovim() -> Result<()> {
    remove_file_if(&home_path(NEOVIM_SNIPPET), |content| {
        content.starts_with("-- bctx MCP server — generated by")
    })
}

// ── File helpers ──────────────────────────────────────────────────────────────

fn home_path(rel: &str) -> PathBuf {
    PathBuf::from(super::home_dir()).join(rel)
}

/// Delete `path` when it exists and `ours` accepts its contents.
fn remove_file_if(path: &Path, ours: impl Fn(&str) -> bool) -> Result<()> {
    let Ok(content) = std::fs::read_to_string(path) else {
        return Ok(());
    };
    if ours(&content) {
        std::fs::remove_file(path)?;
        println!("  ✓ {} removed", path.display());
    }
    Ok(())
}

/// True when a line matching `end` follows the first line matching `start`. Without it,
/// removing "through the end marker" would delete everything after the block.
fn end_follows_start(
    content: &str,
    start: impl Fn(&str) -> bool,
    end: impl Fn(&str) -> bool,
) -> bool {
    let mut lines = content.lines().skip_while(|l| !start(l));
    lines.next().is_some() && lines.any(end)
}

/// Remove the block `init` appended: the line containing `start` through the first line
/// starting with `end`, plus the blank line before it. Deletes the file if nothing is left.
fn remove_block(path: &Path, start: &str, end: &str) -> Result<()> {
    let Ok(content) = std::fs::read_to_string(path) else {
        return Ok(());
    };
    if !content.contains(start) {
        return Ok(());
    }
    if !end_follows_start(
        &content,
        |l| l.contains(start),
        |l| l.trim_start().starts_with(end),
    ) {
        println!(
            "  → {}: the bctx block has no end marker; left as is, remove it by hand",
            path.display()
        );
        return Ok(());
    }
    let mut kept: Vec<&str> = Vec::new();
    let mut skipping = false;
    for line in content.lines() {
        if !skipping && line.contains(start) {
            skipping = true;
            if kept.last().is_some_and(|l| l.trim().is_empty()) {
                kept.pop();
            }
            continue;
        }
        if skipping {
            skipping = !line.trim_start().starts_with(end);
            continue;
        }
        kept.push(line);
    }
    if kept.iter().all(|l| l.trim().is_empty()) {
        std::fs::remove_file(path)?;
        println!("  ✓ {} removed", path.display());
    } else {
        std::fs::write(path, kept.join("\n") + "\n")?;
        println!("  ✓ {} — bctx removed", path.display());
    }
    Ok(())
}

// ── JSON helpers ──────────────────────────────────────────────────────────────

/// Parse a config bctx is about to remove its entry from. A file that is not plain JSON is
/// never rewritten (that would drop the user's comments); if it still lists bctx, say what
/// to remove by hand.
fn parse_for_removal(
    path: &Path,
    raw: &str,
    lists_bctx: impl Fn(&serde_json::Value) -> bool,
) -> Option<serde_json::Value> {
    if let Ok(cfg) = serde_json::from_str(raw.strip_prefix('\u{feff}').unwrap_or(raw)) {
        return Some(cfg);
    }
    if agent_config::parse_lenient(raw).is_some_and(|c| lists_bctx(&c)) {
        println!(
            "  ! {} still lists bctx, but it has comments, so bctx left it untouched; remove the bctx entry by hand",
            path.display()
        );
    }
    None
}

fn settings_list_bctx(cfg: &serde_json::Value) -> bool {
    let hook = cfg["hooks"]["PreToolUse"].as_array().is_some_and(|arr| {
        arr.iter().any(|h| {
            h["hooks"]
                .as_array()
                .and_then(|hs| hs.first())
                .and_then(|h| h["command"].as_str())
                .is_some_and(|c| c.contains("bctx-hook"))
        })
    });
    let allowed = cfg["permissions"]["allow"].as_array().is_some_and(|arr| {
        arr.iter()
            .any(|p| p.as_str().is_some_and(|s| s.starts_with("mcp__bctx__")))
    });
    hook || allowed
}

/// Remove `cfg[key]["bctx"]` from a JSON file.
fn remove_mcp_key(path: &Path, key: &str) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let raw = std::fs::read_to_string(path)?;
    let Some(mut cfg) = parse_for_removal(path, &raw, |c| agent_config::has_bctx(c, key)) else {
        return Ok(());
    };
    if cfg[key].get("bctx").is_some() {
        cfg[key]
            .as_object_mut()
            .expect("mcp key is object")
            .remove("bctx");
        std::fs::write(path, serde_json::to_string_pretty(&cfg)?)?;
        println!("  ✓ {} — bctx removed", path.display());
    }
    Ok(())
}

/// Remove `cfg["servers"]["bctx"]` from a VSCode-family mcp.json.
fn remove_servers_key(path: &Path) -> Result<()> {
    remove_mcp_key(path, "servers")
}

/// Remove bctx from a VSCode-family app's mcp.json (macOS only).
#[cfg(target_os = "macos")]
fn remove_vscode_mcp_entry(home: &str, app_subdir: &str) -> Result<()> {
    let path = PathBuf::from(home)
        .join("Library/Application Support")
        .join(app_subdir)
        .join("mcp.json");
    remove_servers_key(&path)
}