claude-hook-advisor 0.2.1

A Claude Code hook that provides intelligent command suggestions and semantic directory aliasing for enhanced AI-assisted development workflows
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
//! Installation and project setup logic

use anyhow::{anyhow, Context, Result};
use serde_json::{Map, Value};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};




/// Installs Claude Hook Advisor hooks directly into Claude Code settings.
/// 
/// This function:
/// 1. Detects appropriate Claude settings file location (.claude/settings.json or .claude/settings.local.json)
/// 2. Creates a timestamped backup of existing settings
/// 3. Carefully merges our hooks while preserving all existing hooks
/// 4. Only replaces hooks that contain "claude-hook-advisor" in the command
/// 
/// # Returns
/// * `Ok(())` - Hooks installed successfully  
/// * `Err` - If file operations fail or JSON parsing errors occur
pub fn install_claude_hooks() -> Result<()> {
    println!("🔧 Claude Hook Advisor - Hooks Installation");
    println!("===========================================");

    // Determine the best settings file to use
    let settings_path = determine_settings_file()?;
    println!("📁 Using settings file: {}", settings_path.display());

    // Create backup before modifying
    create_settings_backup(&settings_path)?;

    // Load existing settings or create new structure  
    let mut settings = load_or_create_settings(&settings_path)?;

    // Get the current binary path for hooks
    let binary_path = get_current_binary_path()?;
    
    // Merge our hooks into existing settings
    merge_claude_hooks(&mut settings, &binary_path)?;

    // Write updated settings back to file
    write_settings_file(&settings_path, &settings)?;

    println!("✅ Hooks successfully installed!");
    println!("🎯 Claude Hook Advisor will now intercept Bash commands in Claude Code");
    println!("📋 Run claude-hook-advisor --list-directory-aliases to see active directory mappings");

    Ok(())
}

/// Determines the best Claude settings file to use for hook installation.
/// 
/// Priority order:
/// 1. .claude/settings.local.json (preferred - not committed to git)
/// 2. .claude/settings.json (fallback - shared project settings)
/// 
/// Creates the .claude directory if it doesn't exist.
fn determine_settings_file() -> Result<PathBuf> {
    let claude_dir = PathBuf::from(".claude");
    
    // Create .claude directory if it doesn't exist
    if !claude_dir.exists() {
        fs::create_dir_all(&claude_dir)
            .context("Failed to create .claude directory")?;
        println!("📁 Created .claude directory");
    }

    // Prefer local settings (not committed)
    let local_settings = claude_dir.join("settings.local.json");
    let shared_settings = claude_dir.join("settings.json");

    // If local settings exist, use them
    if local_settings.exists() {
        return Ok(local_settings);
    }

    // If shared settings exist, ask user preference
    if shared_settings.exists() {
        println!("📋 Found existing .claude/settings.json (shared with team)");
        print!("Install hooks to local settings instead? (Y/n): ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;

        if !input.trim().to_lowercase().starts_with('n') {
            return Ok(local_settings);
        }
        return Ok(shared_settings);
    }

    // Default to local settings for new installations
    Ok(local_settings)
}

/// Creates a timestamped backup of the settings file.
fn create_settings_backup(settings_path: &Path) -> Result<()> {
    if !settings_path.exists() {
        println!("📋 No existing settings file to backup");
        return Ok(());
    }

    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
    let backup_name = format!("{}.backup_{}", 
        settings_path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("settings.json"),
        timestamp
    );
    let backup_path = settings_path.parent()
        .unwrap_or_else(|| Path::new("."))
        .join(&backup_name);

    fs::copy(settings_path, &backup_path)
        .with_context(|| format!("Failed to create backup at {}", backup_path.display()))?;

    println!("💾 Created backup: {}", backup_path.display());
    Ok(())
}

/// Loads existing settings file or creates a new empty settings structure.
fn load_or_create_settings(settings_path: &Path) -> Result<Value> {
    if settings_path.exists() {
        let content = fs::read_to_string(settings_path)
            .with_context(|| format!("Failed to read settings file: {}", settings_path.display()))?;
        
        if content.trim().is_empty() {
            return Ok(Value::Object(Map::new()));
        }

        serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse JSON in settings file: {}", settings_path.display()))
    } else {
        Ok(Value::Object(Map::new()))
    }
}

/// Gets the current binary path, preferring debug build for development.
/// 
/// Returns absolute paths for development builds to ensure they work regardless
/// of Claude Code's working directory. Uses simple binary name for production
/// installs when available in PATH.
fn get_current_binary_path() -> Result<String> {
    let current_exe = std::env::current_exe()?;
    let binary_name = env!("CARGO_PKG_NAME");
    
    // For development builds, always use absolute path to avoid working directory issues
    if cfg!(debug_assertions) {
        return Ok(current_exe.to_string_lossy().to_string());
    }
    
    // For production builds, prefer simple binary name if available in PATH
    // Otherwise, fall back to absolute path of current executable
    if which::which(binary_name).is_ok() {
        Ok(binary_name.to_string())
    } else {
        Ok(current_exe.to_string_lossy().to_string())
    }
}

/// Merges Claude Hook Advisor hooks into existing settings, preserving other hooks.
/// 
/// This function is careful to:
/// - Only replace hooks containing "claude-hook-advisor" 
/// - Preserve all other existing hooks
/// - Create proper hook structure if it doesn't exist
/// - Handle both array and object formats for hooks
fn merge_claude_hooks(settings: &mut Value, binary_path: &str) -> Result<()> {
    let settings_obj = settings.as_object_mut()
        .ok_or_else(|| anyhow!("Settings must be a JSON object"))?;

    // Ensure hooks object exists
    if !settings_obj.contains_key("hooks") {
        settings_obj.insert("hooks".to_string(), Value::Object(Map::new()));
    }

    let hooks = settings_obj.get_mut("hooks")
        .and_then(|h| h.as_object_mut())
        .ok_or_else(|| anyhow!("hooks must be an object"))?;

    // Our hook configuration
    let hook_command = format!("{binary_path} --hook");

    // Install PreToolUse hook for Bash commands
    merge_hook_event(hooks, "PreToolUse", "Bash", &hook_command)?;
    
    // Install UserPromptSubmit hook (no matcher needed)
    merge_hook_event(hooks, "UserPromptSubmit", "", &hook_command)?;
    
    // Install PostToolUse hook for Bash commands  
    merge_hook_event(hooks, "PostToolUse", "Bash", &hook_command)?;

    Ok(())
}

/// Merges a single hook event, preserving existing hooks and only replacing claude-hook-advisor ones.
fn merge_hook_event(hooks: &mut Map<String, Value>, event_name: &str, matcher: &str, command: &str) -> Result<()> {
    // Ensure the event exists
    if !hooks.contains_key(event_name) {
        hooks.insert(event_name.to_string(), Value::Array(vec![]));
    }

    let event_hooks = hooks.get_mut(event_name)
        .and_then(|h| h.as_array_mut())
        .ok_or_else(|| anyhow!("{} hooks must be an array", event_name))?;

    // Look for existing claude-hook-advisor hooks to replace
    let mut found_existing = false;

    for hook_group in event_hooks.iter_mut() {
        let hook_obj = hook_group.as_object_mut()
            .ok_or_else(|| anyhow!("Hook group must be an object"))?;

        // Check if this hook group matches our matcher
        let group_matcher = hook_obj.get("matcher")
            .and_then(|m| m.as_str())
            .unwrap_or("");

        if (matcher.is_empty() && group_matcher.is_empty()) || 
           (!matcher.is_empty() && group_matcher == matcher) {
            
            // Check hooks array within this group
            if let Some(hooks_array) = hook_obj.get_mut("hooks")
                .and_then(|h| h.as_array_mut()) {
                
                // Remove existing claude-hook-advisor hooks
                hooks_array.retain(|hook| {
                    if let Some(cmd) = hook.get("command").and_then(|c| c.as_str()) {
                        !cmd.contains("claude-hook-advisor")
                    } else {
                        true
                    }
                });

                // Add our hook
                let new_hook = serde_json::json!({
                    "type": "command",
                    "command": command
                });
                hooks_array.push(new_hook);
                found_existing = true;
                break;
            }
        }
    }

    // If no matching group found, create a new one
    if !found_existing {
        let new_hook_group = if matcher.is_empty() {
            serde_json::json!({
                "hooks": [{
                    "type": "command",
                    "command": command
                }]
            })
        } else {
            serde_json::json!({
                "matcher": matcher,
                "hooks": [{
                    "type": "command", 
                    "command": command
                }]
            })
        };
        
        event_hooks.push(new_hook_group);
    }

    Ok(())
}

/// Writes the updated settings back to the file with pretty formatting.
fn write_settings_file(settings_path: &Path, settings: &Value) -> Result<()> {
    let json_content = serde_json::to_string_pretty(settings)
        .context("Failed to serialize settings to JSON")?;

    fs::write(settings_path, json_content)
        .with_context(|| format!("Failed to write settings file: {}", settings_path.display()))?;

    Ok(())
}

/// Uninstalls Claude Hook Advisor hooks from Claude Code settings.
pub fn uninstall_claude_hooks() -> Result<()> {
    println!("🔧 Claude Hook Advisor - Hooks Uninstallation");
    println!("===============================================");

    let settings_path = find_existing_settings_file()?;
    println!("📁 Using settings file: {}", settings_path.display());

    create_settings_backup(&settings_path)?;
    let mut settings = load_or_create_settings(&settings_path)?;
    let removed_count = remove_claude_hooks(&mut settings)?;

    if removed_count == 0 {
        println!("ℹ️  No Claude Hook Advisor hooks found to remove");
        return Ok(());
    }

    write_settings_file(&settings_path, &settings)?;
    println!("✅ Hooks successfully uninstalled!");
    println!("🗑️  Removed {removed_count} claude-hook-advisor hook(s)");
    
    Ok(())
}

fn find_existing_settings_file() -> Result<PathBuf> {
    let claude_dir = PathBuf::from(".claude");
    let local_settings = claude_dir.join("settings.local.json");
    let shared_settings = claude_dir.join("settings.json");

    if local_settings.exists() {
        return Ok(local_settings);
    }
    if shared_settings.exists() {
        return Ok(shared_settings);
    }
    Err(anyhow!("No Claude Code settings file found. Run 'claude-hook-advisor --install' first."))
}

fn remove_claude_hooks(settings: &mut Value) -> Result<usize> {
    let settings_obj = settings.as_object_mut()
        .ok_or_else(|| anyhow!("Settings must be a JSON object"))?;

    if !settings_obj.contains_key("hooks") {
        return Ok(0);
    }

    let hooks = settings_obj.get_mut("hooks")
        .and_then(|h| h.as_object_mut())
        .ok_or_else(|| anyhow!("hooks must be an object"))?;

    let mut total_removed = 0;
    let event_names: Vec<String> = hooks.keys().cloned().collect();
    
    for event_name in event_names {
        let removed_count = remove_hooks_from_event(hooks, &event_name)?;
        total_removed += removed_count;
    }

    if hooks.is_empty() {
        settings_obj.remove("hooks");
    }

    Ok(total_removed)
}

fn remove_hooks_from_event(hooks: &mut Map<String, Value>, event_name: &str) -> Result<usize> {
    let event_hooks = match hooks.get_mut(event_name) {
        Some(hooks_array) => hooks_array.as_array_mut()
            .ok_or_else(|| anyhow!("{} hooks must be an array", event_name))?,
        None => return Ok(0),
    };

    let mut total_removed = 0;
    let mut i = 0;
    while i < event_hooks.len() {
        let hook_group = &mut event_hooks[i];
        let hook_obj = hook_group.as_object_mut()
            .ok_or_else(|| anyhow!("Hook group must be an object"))?;

        if let Some(hooks_array) = hook_obj.get_mut("hooks")
            .and_then(|h| h.as_array_mut()) {
            
            let initial_count = hooks_array.len();
            hooks_array.retain(|hook| {
                if let Some(cmd) = hook.get("command").and_then(|c| c.as_str()) {
                    !cmd.contains("claude-hook-advisor")
                } else {
                    true
                }
            });

            let removed_from_group = initial_count - hooks_array.len();
            total_removed += removed_from_group;

            if hooks_array.is_empty() {
                event_hooks.remove(i);
            } else {
                i += 1;
            }
        } else {
            i += 1;
        }
    }

    if event_hooks.is_empty() {
        hooks.remove(event_name);
    }

    Ok(total_removed)
}





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


    #[test]
    fn test_merge_hooks_empty_settings() {
        let mut settings = serde_json::json!({});
        let binary_path = "/path/to/claude-hook-advisor";
        
        let result = merge_claude_hooks(&mut settings, binary_path);
        assert!(result.is_ok());

        // Should have created hooks structure
        assert!(settings.get("hooks").is_some());
        let hooks = settings.get("hooks").unwrap().as_object().unwrap();
        
        // Should have our three hook types
        assert!(hooks.contains_key("PreToolUse"));
        assert!(hooks.contains_key("UserPromptSubmit"));
        assert!(hooks.contains_key("PostToolUse"));
    }

    #[test]
    fn test_merge_hooks_preserves_existing() {
        let mut settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Write",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "some-other-tool --check"
                            }
                        ]
                    }
                ]
            }
        });

        let binary_path = "/path/to/claude-hook-advisor";
        let result = merge_claude_hooks(&mut settings, binary_path);
        assert!(result.is_ok());

        let hooks = settings.get("hooks").unwrap().as_object().unwrap();
        let pre_tool_use = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        
        // Should have 2 hook groups now - existing Write matcher and new Bash matcher
        assert_eq!(pre_tool_use.len(), 2);
        
        // Check that existing Write hook is preserved
        let write_hook = pre_tool_use.iter()
            .find(|h| h.get("matcher").and_then(|m| m.as_str()) == Some("Write"))
            .expect("Write hook should be preserved");
            
        let write_commands = write_hook.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(write_commands[0].get("command").unwrap().as_str().unwrap(), "some-other-tool --check");
    }

    #[test]
    fn test_merge_hooks_replaces_existing_claude_advisor() {
        let mut settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Bash",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "old-claude-hook-advisor --hook"
                            },
                            {
                                "type": "command", 
                                "command": "some-other-tool --check"
                            }
                        ]
                    }
                ]
            }
        });

        let binary_path = "/path/to/claude-hook-advisor";
        let result = merge_claude_hooks(&mut settings, binary_path);
        assert!(result.is_ok());

        let hooks = settings.get("hooks").unwrap().as_object().unwrap();
        let pre_tool_use = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        let bash_hooks = &pre_tool_use[0].get("hooks").unwrap().as_array().unwrap();
        
        // Should have 2 hooks - the preserved one and our new one
        assert_eq!(bash_hooks.len(), 2);
        
        // Check that claude-hook-advisor was replaced and other hook preserved
        let commands: Vec<&str> = bash_hooks.iter()
            .filter_map(|h| h.get("command").and_then(|c| c.as_str()))
            .collect();
            
        assert!(commands.contains(&"some-other-tool --check"));
        assert!(commands.contains(&"/path/to/claude-hook-advisor --hook"));
        assert!(!commands.iter().any(|c| c.contains("old-claude-hook-advisor")));
    }

    #[test]
    fn test_install_hooks() {
        // Start with a realistic settings file with existing hooks and permissions
        let mut settings = serde_json::json!({
            "permissions": {
                "allow": ["Bash(git:*)", "Read(*.md)"],
                "deny": ["Bash(rm:*)"]
            },
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Write",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "prettier --write"
                            }
                        ]
                    }
                ],
                "PostToolUse": [
                    {
                        "matcher": "Edit",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "eslint --fix"
                            }
                        ]
                    }
                ]
            }
        });

        let binary_path = "/usr/local/bin/claude-hook-advisor";

        // Install our hooks
        let install_result = merge_claude_hooks(&mut settings, binary_path);
        assert!(install_result.is_ok());

        // Verify installation
        let hooks = settings.get("hooks").unwrap().as_object().unwrap();
        
        // Should have 3 hook event types now (PreToolUse, UserPromptSubmit, PostToolUse)
        // PreToolUse and PostToolUse existed before, UserPromptSubmit is new
        assert_eq!(hooks.len(), 3);
        assert!(hooks.contains_key("PreToolUse"));
        assert!(hooks.contains_key("UserPromptSubmit"));
        assert!(hooks.contains_key("PostToolUse"));
        
        // Check PreToolUse has both Write and Bash matchers
        let pre_tool_use = hooks.get("PreToolUse").unwrap().as_array().unwrap();
        assert_eq!(pre_tool_use.len(), 2);
        
        // Find the Write matcher (existing)
        let write_hook = pre_tool_use.iter()
            .find(|h| h.get("matcher").and_then(|m| m.as_str()) == Some("Write"))
            .expect("Write hook should be preserved");
        let write_commands = write_hook.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(write_commands[0].get("command").unwrap().as_str().unwrap(), "prettier --write");
        
        // Find the Bash matcher (our new one)
        let bash_hook = pre_tool_use.iter()
            .find(|h| h.get("matcher").and_then(|m| m.as_str()) == Some("Bash"))
            .expect("Bash hook should be added");
        let bash_commands = bash_hook.get("hooks").unwrap().as_array().unwrap();
        assert_eq!(bash_commands[0].get("command").unwrap().as_str().unwrap(), 
                   "/usr/local/bin/claude-hook-advisor --hook");

        // Check PostToolUse has both Edit and Bash matchers
        let post_tool_use = hooks.get("PostToolUse").unwrap().as_array().unwrap();
        assert_eq!(post_tool_use.len(), 2);

        // Check UserPromptSubmit was added
        let user_prompt_submit = hooks.get("UserPromptSubmit").unwrap().as_array().unwrap();
        assert_eq!(user_prompt_submit.len(), 1);

        // Verify permissions were preserved
        let permissions = settings.get("permissions").unwrap().as_object().unwrap();
        assert_eq!(permissions.get("allow").unwrap().as_array().unwrap().len(), 2);
        assert_eq!(permissions.get("deny").unwrap().as_array().unwrap().len(), 1);
    }





    #[test]
    fn test_debug_assertions_consistency() {
        // This test validates that we're using the correct build detection method
        // In debug builds (cargo test), debug_assertions should be true
        // In release builds (cargo test --release), debug_assertions should be false
        
        #[cfg(debug_assertions)]
        {
            // We're in a debug build - this should be true
            assert!(cfg!(debug_assertions));
        }
        
        #[cfg(not(debug_assertions))]
        {
            // We're in a release build - this should be false
            assert!(!cfg!(debug_assertions));
        }
    }

    // Note: Testing get_current_binary_path() fully requires mocking std::env::current_exe()
    // and the which crate, which is complex. The core logic is simple enough that the
    // main risk is in the integration, which is tested through end-to-end tests.
    //
    // The build detection now uses cfg!(debug_assertions) which is a compile-time constant,
    // so it's inherently reliable and doesn't need runtime testing.
}