code-graph-cli 3.0.3

Code intelligence engine for TypeScript/JavaScript/Rust/Python/Go — query the dependency graph instead of reading source files.
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
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

/// Hook scripts embedded at compile time so `code-graph setup` works after `cargo install`.
const EMBEDDED_HOOKS: &[(&str, &str)] = &[
    (
        "codegraph-pretool-bash.sh",
        include_str!("hooks/codegraph-pretool-bash.sh"),
    ),
    (
        "codegraph-pretool-search.sh",
        include_str!("hooks/codegraph-pretool-search.sh"),
    ),
];

/// The hook matcher entries that code-graph adds to settings.json.
const BASH_HOOK_PATH: &str = ".claude/hooks/codegraph-pretool-bash.sh";
const SEARCH_HOOK_PATH: &str = ".claude/hooks/codegraph-pretool-search.sh";
const PERMISSION_ENTRY: &str = "Bash(code-graph *)";

/// Run the setup (or uninstall) workflow.
pub fn run(global: bool, uninstall: bool) -> Result<()> {
    let base_dir = resolve_base_dir(global)?;

    if uninstall {
        run_uninstall(&base_dir)?;
    } else {
        run_install(&base_dir, global)?;
    }

    Ok(())
}

/// Determine the target directory for hook installation.
fn resolve_base_dir(global: bool) -> Result<PathBuf> {
    if global {
        let home = std::env::var("HOME").context("HOME environment variable not set")?;
        Ok(PathBuf::from(home).join(".claude"))
    } else {
        // Project-level: use .claude/ relative to cwd
        Ok(PathBuf::from(".claude"))
    }
}

/// Install hooks and configure settings.
fn run_install(base_dir: &Path, global: bool) -> Result<()> {
    let hooks_dir = base_dir.join("hooks");
    let settings_path = base_dir.join("settings.json");

    // Ensure directories exist
    fs::create_dir_all(&hooks_dir)
        .with_context(|| format!("Failed to create hooks directory: {}", hooks_dir.display()))?;

    // 1. Write embedded hook scripts to disk
    let mut hooks_installed = Vec::new();
    for &(hook_file, content) in EMBEDDED_HOOKS {
        let dest = hooks_dir.join(hook_file);
        fs::write(&dest, content)
            .with_context(|| format!("Failed to write hook script: {}", dest.display()))?;
        set_executable(&dest)?;
        hooks_installed.push(hook_file);
    }

    // 2. Merge hook config into settings.json
    let settings_modified = merge_settings(&settings_path, global)?;

    // 3. Clean up MCP config (project-level only — global has no .mcp.json)
    let mut mcp_actions = Vec::new();
    if !global {
        mcp_actions = cleanup_mcp(base_dir)?;
    }

    // 4. Print summary
    println!("code-graph setup complete!\n");
    println!(
        "  Target: {}",
        if global {
            "global (~/.claude/)"
        } else {
            "project (.claude/)"
        }
    );
    println!("\n  Hooks installed:");
    for hook in &hooks_installed {
        println!("    + {}/hooks/{}", base_dir.display(), hook);
    }
    if settings_modified {
        println!("\n  Settings updated:");
        println!("    ~ {}", settings_path.display());
    }
    if !mcp_actions.is_empty() {
        println!("\n  MCP cleanup:");
        for action in &mcp_actions {
            println!("    - {action}");
        }
    }

    Ok(())
}

/// Uninstall code-graph hooks and permissions.
fn run_uninstall(base_dir: &Path) -> Result<()> {
    let hooks_dir = base_dir.join("hooks");
    let settings_path = base_dir.join("settings.json");

    // 1. Remove hook scripts
    let mut removed = Vec::new();
    for &(hook_file, _) in EMBEDDED_HOOKS {
        let path = hooks_dir.join(hook_file);
        if path.exists() {
            fs::remove_file(&path)
                .with_context(|| format!("Failed to remove hook file: {}", path.display()))?;
            removed.push(hook_file);
        }
    }

    // 2. Remove hook entries from settings.json
    let settings_modified = remove_from_settings(&settings_path)?;

    // 3. Print summary
    println!("code-graph uninstall complete!\n");
    if !removed.is_empty() {
        println!("  Hooks removed:");
        for hook in &removed {
            println!("    - {}/hooks/{}", base_dir.display(), hook);
        }
    }
    if settings_modified {
        println!("\n  Settings updated:");
        println!("    ~ {}", settings_path.display());
    }

    Ok(())
}

/// Set the executable bit on a file (Unix).
#[cfg(unix)]
fn set_executable(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = fs::metadata(path)?.permissions();
    perms.set_mode(perms.mode() | 0o111);
    fs::set_permissions(path, perms)?;
    Ok(())
}

#[cfg(not(unix))]
fn set_executable(_path: &Path) -> Result<()> {
    Ok(())
}

/// Merge code-graph hook entries into settings.json without clobbering existing hooks.
fn merge_settings(settings_path: &Path, global: bool) -> Result<bool> {
    let mut settings: serde_json::Value = if settings_path.exists() {
        let content = fs::read_to_string(settings_path)?;
        serde_json::from_str(&content).with_context(|| {
            format!(
                "{} contains invalid JSON — fix or delete it first",
                settings_path.display()
            )
        })?
    } else {
        serde_json::json!({})
    };

    let mut modified = false;

    // Determine command prefix based on scope
    // Global installs use ~/.claude/ (shell-expandable, portable across machines)
    // Project installs use .claude/ (relative to project root)
    let (bash_cmd, search_cmd) = if global {
        (
            "~/.claude/hooks/codegraph-pretool-bash.sh".to_string(),
            "~/.claude/hooks/codegraph-pretool-search.sh".to_string(),
        )
    } else {
        (BASH_HOOK_PATH.to_string(), SEARCH_HOOK_PATH.to_string())
    };

    // Ensure hooks.PreToolUse exists
    let settings_obj = settings
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("settings.json root is not a JSON object"))?;
    let hooks = settings_obj
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let hooks_obj = hooks
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("settings.json \"hooks\" is not a JSON object"))?;
    let pre_tool_use = hooks_obj
        .entry("PreToolUse")
        .or_insert_with(|| serde_json::json!([]));

    let arr = pre_tool_use
        .as_array_mut()
        .ok_or_else(|| anyhow::anyhow!("settings.json \"hooks.PreToolUse\" is not a JSON array"))?;

    // Add/update Bash matcher with codegraph hook
    modified |= ensure_hook_entry(arr, "Bash", &bash_cmd)?;

    // Add/update Grep|Glob matcher with codegraph hook
    modified |= ensure_hook_entry(arr, "Grep|Glob", &search_cmd)?;

    // Add permission
    let settings_obj = settings
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("settings.json root is not a JSON object"))?;
    let permissions = settings_obj
        .entry("permissions")
        .or_insert_with(|| serde_json::json!({}));
    let permissions_obj = permissions
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("settings.json \"permissions\" is not a JSON object"))?;
    let allow = permissions_obj
        .entry("allow")
        .or_insert_with(|| serde_json::json!([]));

    let allow_arr = allow.as_array_mut().ok_or_else(|| {
        anyhow::anyhow!("settings.json \"permissions.allow\" is not a JSON array")
    })?;
    let perm_str = serde_json::Value::String(PERMISSION_ENTRY.to_string());
    if !allow_arr.contains(&perm_str) {
        allow_arr.push(perm_str);
        modified = true;
    }

    // Remove stale MCP permissions
    let before_len = allow_arr.len();
    allow_arr.retain(|v| {
        v.as_str()
            .is_none_or(|s| !s.starts_with("mcp__code-graph__"))
    });
    if allow_arr.len() != before_len {
        modified = true;
    }

    if modified {
        let content = serde_json::to_string_pretty(&settings)?;
        fs::write(settings_path, content + "\n")?;
    }

    Ok(modified)
}

/// Ensure a hook command exists under the given matcher in the PreToolUse array.
/// Returns true if any modification was made.
fn ensure_hook_entry(
    pre_tool_use: &mut Vec<serde_json::Value>,
    matcher: &str,
    command: &str,
) -> Result<bool> {
    let hook_entry = serde_json::json!({
        "type": "command",
        "command": command
    });

    // Find existing matcher group
    for entry in pre_tool_use.iter_mut() {
        if entry.get("matcher").and_then(|m| m.as_str()) == Some(matcher) {
            let entry_obj = entry.as_object_mut().ok_or_else(|| {
                anyhow::anyhow!("PreToolUse entry for matcher \"{matcher}\" is not a JSON object")
            })?;
            let hooks = entry_obj
                .entry("hooks")
                .or_insert_with(|| serde_json::json!([]));
            let hooks_arr = hooks.as_array_mut().ok_or_else(|| {
                anyhow::anyhow!("\"hooks\" for matcher \"{matcher}\" is not a JSON array")
            })?;

            // Check if our hook is already there
            let already_has = hooks_arr.iter().any(|h| {
                h.get("command")
                    .and_then(|c| c.as_str())
                    .is_some_and(|c| c.contains("codegraph-pretool"))
            });

            if !already_has {
                hooks_arr.push(hook_entry);
                return Ok(true);
            }
            return Ok(false);
        }
    }

    // No existing matcher group — create one
    pre_tool_use.push(serde_json::json!({
        "matcher": matcher,
        "hooks": [hook_entry]
    }));
    Ok(true)
}

/// Remove code-graph hook entries from settings.json.
fn remove_from_settings(settings_path: &Path) -> Result<bool> {
    if !settings_path.exists() {
        return Ok(false);
    }

    let content = fs::read_to_string(settings_path)?;
    let mut settings: serde_json::Value =
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}));

    let mut modified = false;

    // Remove hooks
    if let Some(hooks) = settings.get_mut("hooks")
        && let Some(pre_tool_use) = hooks.get_mut("PreToolUse")
        && let Some(arr) = pre_tool_use.as_array_mut()
    {
        for entry in arr.iter_mut() {
            if let Some(hooks_arr) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
                let before = hooks_arr.len();
                hooks_arr.retain(|h| {
                    h.get("command")
                        .and_then(|c| c.as_str())
                        .is_none_or(|c| !c.contains("codegraph-pretool"))
                });
                if hooks_arr.len() != before {
                    modified = true;
                }
            }
        }
        // Remove empty matcher groups
        let before = arr.len();
        arr.retain(|entry| {
            entry
                .get("hooks")
                .and_then(|h| h.as_array())
                .is_some_and(|a| !a.is_empty())
        });
        if arr.len() != before {
            modified = true;
        }
    }

    // Remove permission
    if let Some(permissions) = settings.get_mut("permissions")
        && let Some(allow) = permissions.get_mut("allow")
        && let Some(arr) = allow.as_array_mut()
    {
        let before = arr.len();
        arr.retain(|v| v.as_str() != Some(PERMISSION_ENTRY));
        if arr.len() != before {
            modified = true;
        }
    }

    if modified {
        let content = serde_json::to_string_pretty(&settings)?;
        fs::write(settings_path, content + "\n")?;
    }

    Ok(modified)
}

/// Clean up stale MCP configuration.
fn cleanup_mcp(base_dir: &Path) -> Result<Vec<String>> {
    let mut actions = Vec::new();

    // 1. Clean .mcp.json
    let mcp_path = base_dir
        .parent()
        .unwrap_or(Path::new("."))
        .join(".mcp.json");
    if mcp_path.exists() {
        let content = fs::read_to_string(&mcp_path)?;
        if let Ok(mut mcp) = serde_json::from_str::<serde_json::Value>(&content)
            && let Some(servers) = mcp.get_mut("mcpServers").and_then(|s| s.as_object_mut())
            && servers.remove("code-graph").is_some()
        {
            actions.push(format!(
                "Removed 'code-graph' server from {}",
                mcp_path.display()
            ));
            if servers.is_empty() {
                // Remove the file if no servers remain
                fs::remove_file(&mcp_path)?;
                actions.push(format!("Deleted empty {}", mcp_path.display()));
            } else {
                let content = serde_json::to_string_pretty(&mcp)?;
                fs::write(&mcp_path, content + "\n")?;
            }
        }
    }

    // 2. Clean settings.local.json MCP permissions
    let settings_local_path = base_dir.join("settings.local.json");
    if settings_local_path.exists() {
        let content = fs::read_to_string(&settings_local_path)?;
        if let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(&content) {
            let mut local_modified = false;

            // Remove MCP permissions
            if let Some(permissions) = settings.get_mut("permissions")
                && let Some(allow) = permissions.get_mut("allow")
                && let Some(arr) = allow.as_array_mut()
            {
                let before = arr.len();
                arr.retain(|v| {
                    v.as_str()
                        .is_none_or(|s| !s.starts_with("mcp__code-graph__"))
                });
                if arr.len() != before {
                    local_modified = true;
                    actions.push(format!(
                        "Removed {} mcp__code-graph__* permission(s) from {}",
                        before - arr.len(),
                        settings_local_path.display()
                    ));
                }
            }

            // Remove enabledMcpjsonServers code-graph entry
            if let Some(enabled) = settings.get_mut("enabledMcpjsonServers")
                && let Some(arr) = enabled.as_array_mut()
            {
                let before = arr.len();
                arr.retain(|v| v.as_str() != Some("code-graph"));
                if arr.len() != before {
                    local_modified = true;
                    actions.push(format!(
                        "Removed 'code-graph' from enabledMcpjsonServers in {}",
                        settings_local_path.display()
                    ));
                }
            }

            if local_modified {
                let content = serde_json::to_string_pretty(&settings)?;
                fs::write(&settings_local_path, content + "\n")?;
            }
        }
    }

    Ok(actions)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::Cli;
    use clap::Parser;

    #[test]
    fn test_setup_parses() {
        let cli = Cli::parse_from(["code-graph", "setup"]);
        match cli.command {
            crate::cli::Commands::Setup { global, uninstall } => {
                assert!(!global, "--global should default to false");
                assert!(!uninstall, "--uninstall should default to false");
            }
            _ => panic!("expected Setup command"),
        }
    }

    #[test]
    fn test_setup_global_flag() {
        let cli = Cli::parse_from(["code-graph", "setup", "--global"]);
        match cli.command {
            crate::cli::Commands::Setup { global, uninstall } => {
                assert!(global, "--global should be true");
                assert!(!uninstall, "--uninstall should default to false");
            }
            _ => panic!("expected Setup command"),
        }
    }

    #[test]
    fn test_setup_uninstall_flag() {
        let cli = Cli::parse_from(["code-graph", "setup", "--uninstall"]);
        match cli.command {
            crate::cli::Commands::Setup { global, uninstall } => {
                assert!(!global, "--global should default to false");
                assert!(uninstall, "--uninstall should be true");
            }
            _ => panic!("expected Setup command"),
        }
    }

    #[test]
    fn test_ensure_hook_entry_adds_new_matcher() {
        let mut arr: Vec<serde_json::Value> = vec![];
        let modified = ensure_hook_entry(&mut arr, "Bash", "some/hook.sh").unwrap();
        assert!(modified);
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["matcher"], "Bash");
    }

    #[test]
    fn test_ensure_hook_entry_appends_to_existing() {
        let mut arr: Vec<serde_json::Value> = vec![serde_json::json!({
            "matcher": "Bash",
            "hooks": [
                { "type": "command", "command": "other-hook.sh" }
            ]
        })];
        let modified = ensure_hook_entry(&mut arr, "Bash", "codegraph-pretool-bash.sh").unwrap();
        assert!(modified);
        assert_eq!(arr.len(), 1); // Still one matcher group
        let hooks = arr[0]["hooks"].as_array().unwrap();
        assert_eq!(hooks.len(), 2); // Two hooks now
    }

    #[test]
    fn test_ensure_hook_entry_idempotent() {
        let mut arr: Vec<serde_json::Value> = vec![serde_json::json!({
            "matcher": "Bash",
            "hooks": [
                { "type": "command", "command": "codegraph-pretool-bash.sh" }
            ]
        })];
        let modified = ensure_hook_entry(&mut arr, "Bash", "codegraph-pretool-bash.sh").unwrap();
        assert!(!modified); // Already present
        let hooks = arr[0]["hooks"].as_array().unwrap();
        assert_eq!(hooks.len(), 1); // Still one hook
    }

    #[test]
    fn test_merge_settings_creates_new() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let modified = merge_settings(&settings_path, false).unwrap();
        assert!(modified);
        let content = fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        // Should have hooks and permissions
        assert!(settings.get("hooks").is_some());
        assert!(settings.get("permissions").is_some());
        // Should have our permission
        let allow = settings["permissions"]["allow"].as_array().unwrap();
        assert!(allow.contains(&serde_json::Value::String(PERMISSION_ENTRY.to_string())));
    }

    #[test]
    fn test_merge_settings_preserves_existing() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let existing = serde_json::json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Bash",
                        "hooks": [
                            { "type": "command", "command": "rtk-rewrite.sh" }
                        ]
                    }
                ]
            },
            "permissions": {
                "allow": ["Bash(git *)"],
                "deny": []
            }
        });
        fs::write(
            &settings_path,
            serde_json::to_string_pretty(&existing).unwrap(),
        )
        .unwrap();
        merge_settings(&settings_path, false).unwrap();
        let content = fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        // RTK hook should still be there
        let bash_hooks = &settings["hooks"]["PreToolUse"][0]["hooks"];
        let has_rtk = bash_hooks.as_array().unwrap().iter().any(|h| {
            h.get("command")
                .and_then(|c| c.as_str())
                .is_some_and(|c| c == "rtk-rewrite.sh")
        });
        assert!(has_rtk, "RTK hook should be preserved");
        // Our hook should be added
        let has_ours = bash_hooks.as_array().unwrap().iter().any(|h| {
            h.get("command")
                .and_then(|c| c.as_str())
                .is_some_and(|c| c.contains("codegraph-pretool"))
        });
        assert!(has_ours, "codegraph hook should be added");
        // Git permission should be preserved
        let allow = settings["permissions"]["allow"].as_array().unwrap();
        assert!(allow.contains(&serde_json::Value::String("Bash(git *)".to_string())));
    }

    #[test]
    fn test_merge_settings_removes_mcp_permissions() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let existing = serde_json::json!({
            "permissions": {
                "allow": [
                    "mcp__code-graph__find_symbol",
                    "mcp__code-graph__get_stats",
                    "Bash(git *)"
                ]
            }
        });
        fs::write(
            &settings_path,
            serde_json::to_string_pretty(&existing).unwrap(),
        )
        .unwrap();
        merge_settings(&settings_path, false).unwrap();
        let content = fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        let allow = settings["permissions"]["allow"].as_array().unwrap();
        // MCP permissions should be gone
        assert!(
            !allow.iter().any(|v| v
                .as_str()
                .is_some_and(|s| s.starts_with("mcp__code-graph__"))),
            "MCP permissions should be removed"
        );
        // Non-MCP permissions should remain
        assert!(allow.contains(&serde_json::Value::String("Bash(git *)".to_string())));
    }

    #[test]
    fn test_remove_from_settings() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let existing = serde_json::json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Bash",
                        "hooks": [
                            { "type": "command", "command": "rtk-rewrite.sh" },
                            { "type": "command", "command": ".claude/hooks/codegraph-pretool-bash.sh" }
                        ]
                    },
                    {
                        "matcher": "Grep|Glob",
                        "hooks": [
                            { "type": "command", "command": ".claude/hooks/codegraph-pretool-search.sh" }
                        ]
                    }
                ]
            },
            "permissions": {
                "allow": ["Bash(code-graph *)", "Bash(git *)"]
            }
        });
        fs::write(
            &settings_path,
            serde_json::to_string_pretty(&existing).unwrap(),
        )
        .unwrap();
        let modified = remove_from_settings(&settings_path).unwrap();
        assert!(modified);
        let content = fs::read_to_string(&settings_path).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        // RTK hook should remain
        let bash_hooks = &settings["hooks"]["PreToolUse"][0]["hooks"];
        assert_eq!(bash_hooks.as_array().unwrap().len(), 1);
        assert_eq!(bash_hooks[0]["command"], "rtk-rewrite.sh");
        // Grep|Glob matcher should be removed (empty after removing our hook)
        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(
            pre_tool_use.len(),
            1,
            "Empty Grep|Glob matcher should be removed"
        );
        // code-graph permission gone, git permission remains
        let allow = settings["permissions"]["allow"].as_array().unwrap();
        assert!(!allow.contains(&serde_json::Value::String(PERMISSION_ENTRY.to_string())));
        assert!(allow.contains(&serde_json::Value::String("Bash(git *)".to_string())));
    }
}