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
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
//! CLI interface and main entry point

use crate::hooks::run_as_hook;
use crate::Config;
use anyhow::{Context, Result};
use clap::{Arg, Command};
use std::fs;
use std::path::Path;

/// Main entry point for the Claude Hook Advisor application.
/// 
/// Parses command-line arguments and dispatches to the appropriate mode:
/// - `--hook`: Run as a Claude Code PreToolUse hook (reads JSON from stdin)
/// - `--install`: Interactive installer to set up project configuration
/// - Default: Show usage information
pub fn run_cli() -> Result<()> {
    let matches = Command::new("claude-hook-advisor")
        .version(env!("CARGO_PKG_VERSION"))
        .about("Advises Claude Code on better command alternatives based on project preferences")
        .arg(
            Arg::new("config")
                .short('c')
                .long("config")
                .value_name("FILE")
                .help("Path to configuration file")
                .default_value(".claude-hook-advisor.toml"),
        )
        .arg(
            Arg::new("hook")
                .long("hook")
                .help("Run as a Claude Code hook (reads JSON from stdin)")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("replace")
                .long("replace")
                .help("Replace commands instead of blocking (experimental, not yet supported by Claude Code)")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("install")
                .long("install")
                .help("Install Claude Hook Advisor: configure hooks and create/update config file")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("uninstall")
                .long("uninstall")
                .help("Remove Claude Hook Advisor hooks from Claude Code settings")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("history")
                .long("history")
                .help("View command history")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("limit")
                .long("limit")
                .value_name("N")
                .help("Limit number of history results (default: 20)")
                .value_parser(clap::value_parser!(usize)),
        )
        .arg(
            Arg::new("session")
                .long("session")
                .value_name("ID")
                .help("Filter history by session ID"),
        )
        .arg(
            Arg::new("failures")
                .long("failures")
                .help("Show only failed commands (non-zero exit codes)")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("pattern")
                .long("pattern")
                .value_name("PATTERN")
                .help("Filter commands by pattern (e.g., 'git', 'npm')"),
        )
        .get_matches();

    let config_path = matches.get_one::<String>("config")
        .expect("config argument has default value");
    let replace_mode = matches.get_flag("replace");

    if matches.get_flag("hook") {
        run_as_hook(config_path, replace_mode)
    } else if matches.get_flag("install") {
        run_smart_installation(config_path)
    } else if matches.get_flag("uninstall") {
        crate::installer::uninstall_claude_hooks()
    } else if matches.get_flag("history") {
        let limit = matches.get_one::<usize>("limit").copied();
        let session_id = matches.get_one::<String>("session").map(|s| s.to_string());
        let failures_only = matches.get_flag("failures");
        let pattern = matches.get_one::<String>("pattern").map(|s| s.to_string());

        show_command_history(config_path, limit, session_id, failures_only, pattern)
    } else {
        println!("Claude Hook Advisor v{}", env!("CARGO_PKG_VERSION"));
        println!();
        println!("Installation:");
        println!("  --install                 Install Claude Hook Advisor: configure hooks and create/update config file");
        println!();
        println!("Command Mapping:");
        println!("  --hook                    Run as a Claude Code hook");
        println!();
        println!("Command History:");
        println!("  --history                 View command history");
        println!("  --limit <N>               Limit number of results (default: 20)");
        println!("  --session <ID>            Filter by session ID");
        println!("  --failures                Show only failed commands");
        println!("  --pattern <PATTERN>       Filter by command pattern");
        println!();
        println!("Configuration:");
        println!("  -c, --config <FILE>       Path to config file [default: .claude-hook-advisor.toml]");
        println!();
        println!("To configure directory aliases and command mappings, edit .claude-hook-advisor.toml directly.");
        Ok(())
    }
}


/// Shows command history from the SQLite database.
///
/// # Arguments
/// * `config_path` - Path to configuration file (to get history DB path)
/// * `limit` - Maximum number of records to show
/// * `session_id` - Optional session ID filter
/// * `failures_only` - Whether to show only failed commands
/// * `pattern` - Optional command pattern filter
///
/// # Returns
/// * `Ok(())` - History displayed successfully
/// * `Err` - If database query fails
fn show_command_history(
    config_path: &str,
    limit: Option<usize>,
    session_id: Option<String>,
    failures_only: bool,
    pattern: Option<String>,
) -> Result<()> {
    use crate::history;

    // Load config to get history database path
    let config = crate::config::load_config(config_path)
        .context("Failed to load configuration")?;

    // Get history configuration
    let history_config = match config.command_history {
        Some(ref cfg) if cfg.enabled => cfg,
        Some(_) => {
            println!("Command history is disabled in configuration.");
            return Ok(());
        }
        None => {
            println!("Command history is not configured.");
            println!("Add a [command_history] section to your .claude-hook-advisor.toml:");
            println!();
            println!("[command_history]");
            println!("enabled = true");
            println!("log_file = \"~/.claude-hook-advisor/bash-history.db\"");
            return Ok(());
        }
    };

    // Expand tilde in log file path
    let log_path = expand_tilde_path(&history_config.log_file)?;

    // Check if database file exists
    if !log_path.exists() {
        println!("No command history found at: {}", log_path.display());
        println!("Commands will be logged once you start using Claude Code with hooks enabled.");
        return Ok(());
    }

    // Open database connection
    let conn = history::init_database(&log_path)
        .context("Failed to open command history database")?;

    // Build query
    let query = history::HistoryQuery {
        limit: Some(limit.unwrap_or(20)),
        session_id,
        failures_only,
        command_pattern: pattern,
    };

    // Execute query
    let records = history::query_history(&conn, &query)
        .context("Failed to query command history")?;

    if records.is_empty() {
        println!("No commands found matching the specified criteria.");
        return Ok(());
    }

    // Display results
    println!("Command History ({} records)", records.len());
    println!("{}", "=".repeat(80));
    println!();

    for record in records {
        let timestamp = record.timestamp;
        let exit_code_str = match record.exit_code {
            Some(0) => "".to_string(),
            Some(code) => format!("✗ (exit: {})", code),
            None => "?".to_string(),
        };

        println!("{}  {}", timestamp, exit_code_str);
        println!("  Command: {}", record.command);

        if let Some(cwd) = record.cwd {
            println!("  CWD:     {}", cwd);
        }

        if record.was_replaced {
            if let Some(original) = record.original_command {
                println!("  Original: {}", original);
            }
        }

        println!("  Session: {}", record.session_id);
        println!();
    }

    Ok(())
}

/// Expands tilde (~) in file paths to the user's home directory
fn expand_tilde_path(path: &str) -> Result<std::path::PathBuf> {
    if path.starts_with("~/") {
        let home = std::env::var("HOME")
            .context("HOME environment variable not set")?;
        Ok(std::path::PathBuf::from(path.replacen("~", &home, 1)))
    } else {
        Ok(std::path::PathBuf::from(path))
    }
}

/// Smart installation that checks existing state and only makes necessary changes.
/// 
/// This function:
/// 1. Checks if hooks already exist - if so, skips hook installation
/// 2. Checks if config file exists - if not, creates it with examples
/// 3. If config exists, ensures required sections exist with commented examples
/// 
/// # Arguments
/// * `config_path` - Path to the configuration file
/// 
/// # Returns
/// * `Ok(())` - Installation completed successfully
/// * `Err` - If any installation step fails
fn run_smart_installation(config_path: &str) -> Result<()> {
    println!("🚀 Claude Hook Advisor Installation");
    println!("===================================\n");
    
    // Step 1: Check and install hooks if needed
    if hooks_already_exist()? {
        println!("✅ Hooks already installed in Claude Code settings");
    } else {
        println!("📋 Installing hooks into Claude Code settings...");
        crate::installer::install_claude_hooks()?;
        println!("✅ Hooks installed successfully");
    }
    
    // Step 2: Handle config file
    println!("\n📄 Checking configuration file...");
    if Path::new(config_path).exists() {
        println!("✅ Config file exists: {config_path}");
        ensure_config_sections(config_path)?;
    } else {
        println!("📝 Creating new config file: {config_path}");
        create_smart_config(config_path)?;
    }
    
    println!("\n🎉 Installation complete! Claude Hook Advisor is ready to use.");
    println!("💡 You can now use semantic directory references in Claude Code conversations.");
    
    Ok(())
}

/// Checks if Claude Hook Advisor hooks are already installed in Claude Code settings.
/// 
/// # Returns
/// * `Ok(true)` - Hooks are already installed
/// * `Ok(false)` - Hooks are not installed
/// * `Err` - If settings file cannot be read or parsed
fn hooks_already_exist() -> Result<bool> {
    // Check for settings files in order of preference
    let local_settings = Path::new(".claude/settings.local.json");
    let shared_settings = Path::new(".claude/settings.json");
    
    let settings_path = if local_settings.exists() {
        local_settings
    } else if shared_settings.exists() {
        shared_settings
    } else {
        return Ok(false); // No settings file means no hooks
    };
    
    // Read and parse settings file
    let settings_content = fs::read_to_string(settings_path)
        .with_context(|| format!("Failed to read {}", settings_path.display()))?;
    
    let settings: serde_json::Value = serde_json::from_str(&settings_content)
        .with_context(|| "Failed to parse Claude settings JSON")?;
    
    // Check if our hooks exist
    if let Some(hooks) = settings.get("hooks").and_then(|h| h.as_object()) {
        // Check PreToolUse and UserPromptSubmit hooks
        for event_name in &["PreToolUse", "UserPromptSubmit"] {
            if let Some(event_hooks) = hooks.get(*event_name).and_then(|h| h.as_array()) {
                for hook_group in event_hooks {
                    if let Some(hooks_array) = hook_group.get("hooks").and_then(|h| h.as_array()) {
                        for hook in hooks_array {
                            if let Some(command) = hook.get("command").and_then(|c| c.as_str()) {
                                if command.contains("claude-hook-advisor") {
                                    return Ok(true);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    Ok(false)
}

/// Creates a smart configuration file with project-specific command mappings.
/// Detects the project type and generates appropriate command mappings.
/// Directory aliases are provided as commented examples only.
/// 
/// # Arguments
/// * `config_path` - Path where to create the configuration file
/// 
/// # Returns
/// * `Ok(())` - Configuration created successfully
/// * `Err` - If file writing fails
fn create_smart_config(config_path: &str) -> Result<()> {
    // Detect project type
    let project_type = detect_project_type()?;
    println!("🔍 Detected project type: {project_type}");
    
    // Get project-specific command mappings
    let commands = get_commands_for_project_type(&project_type);
    
    // Create config structure with actual commands but empty directories
    let config = Config {
        commands,
        semantic_directories: std::collections::HashMap::new(), // Empty - will be comments only
        command_history: None, // Will be added as commented example
    };
    
    // Generate TOML content
    let toml_content = toml::to_string_pretty(&config)
        .with_context(|| "Failed to serialize configuration to TOML")?;
    
    // Build the complete config with header and directory examples as comments
    let _project_name = get_project_name();
    let final_content = format!(r#"# Claude Hook Advisor Configuration
# Auto-generated for {project_type} project
# This file configures command mappings and semantic directory aliases
# for use with Claude Code integration.

{toml_content}
# Semantic directory aliases - natural language directory references
# Uncomment and customize these examples:
# docs = "~/Documents/Documentation"
# central_docs = "~/Documents/Documentation"
# project_docs = "~/Documents/Documentation/my-project"
# claude_docs = "~/Documents/Documentation/claude"

# Command history tracking - logs all Bash commands Claude runs
# Uncomment to enable:
# [command_history]
# enabled = true
# log_file = "~/.claude-hook-advisor/bash-history.db"
"#);
    
    fs::write(config_path, final_content)
        .with_context(|| format!("Failed to write config file: {config_path}"))?;
    
    println!("✅ Created smart configuration for {project_type} project");
    
    // Show what was configured
    if !config.commands.is_empty() {
        println!("📝 Command mappings configured:");
        for (from, to) in &config.commands {
            println!("   {from}{to}");
        }
    } else {
        println!("📝 No specific command mappings for {project_type} - using general alternatives");
    }
    
    Ok(())
}

/// Detects the project type by examining files in the current directory.
/// 
/// # Returns
/// * `Ok(String)` - Detected project type ("Node.js", "Python", "Rust", etc.)
/// * `Err` - If current directory cannot be accessed
fn detect_project_type() -> Result<String> {
    let current_dir = std::env::current_dir()?;

    // Check for various project indicators
    if current_dir.join("package.json").exists() {
        return Ok("Node.js".to_string());
    }

    if current_dir.join("requirements.txt").exists()
        || current_dir.join("pyproject.toml").exists()
        || current_dir.join("setup.py").exists()
    {
        return Ok("Python".to_string());
    }

    if current_dir.join("Cargo.toml").exists() {
        return Ok("Rust".to_string());
    }

    if current_dir.join("go.mod").exists() {
        return Ok("Go".to_string());
    }

    if current_dir.join("pom.xml").exists() || current_dir.join("build.gradle").exists() {
        return Ok("Java".to_string());
    }

    if current_dir.join("Dockerfile").exists() {
        return Ok("Docker".to_string());
    }

    Ok("General".to_string())
}

/// Creates project-specific command mappings based on detected project type.
/// 
/// # Arguments
/// * `project_type` - The detected project type
/// 
/// # Returns
/// * `HashMap<String, String>` - Command mappings for the project
fn get_commands_for_project_type(project_type: &str) -> std::collections::HashMap<String, String> {
    let mut commands = std::collections::HashMap::new();
    
    match project_type {
        "Node.js" => {
            commands.insert("npm".to_string(), "bun".to_string());
            commands.insert("yarn".to_string(), "bun".to_string());
            commands.insert("pnpm".to_string(), "bun".to_string());
            commands.insert("npx".to_string(), "bunx".to_string());
            commands.insert("npm start".to_string(), "bun dev".to_string());
            commands.insert("npm test".to_string(), "bun test".to_string());
            commands.insert("npm run build".to_string(), "bun run build".to_string());
        }
        "Python" => {
            commands.insert("pip".to_string(), "uv pip".to_string());
            commands.insert("pip install".to_string(), "uv add".to_string());
            commands.insert("pip uninstall".to_string(), "uv remove".to_string());
            commands.insert("python".to_string(), "uv run python".to_string());
            commands.insert("python -m".to_string(), "uv run python -m".to_string());
        }
        "Rust" => {
            commands.insert("cargo check".to_string(), "cargo clippy".to_string());
            commands.insert("cargo test".to_string(), "cargo test -- --nocapture".to_string());
        }
        "Go" => {
            commands.insert("go run".to_string(), "go run -race".to_string());
            commands.insert("go test".to_string(), "go test -v".to_string());
        }
        "Java" => {
            commands.insert("mvn".to_string(), "./mvnw".to_string());
            commands.insert("gradle".to_string(), "./gradlew".to_string());
        }
        "Docker" => {
            commands.insert("docker".to_string(), "podman".to_string());
            commands.insert("docker-compose".to_string(), "podman-compose".to_string());
        }
        _ => {
            // General project - modern CLI alternatives
            commands.insert("cat".to_string(), "bat".to_string());
            commands.insert("ls".to_string(), "eza".to_string());
            commands.insert("grep".to_string(), "rg".to_string());
            commands.insert("find".to_string(), "fd".to_string());
        }
    }
    
    // Add common safety and modern tool mappings for all project types
    commands.insert("curl".to_string(), "curl -L".to_string());
    commands.insert("rm".to_string(), "trash".to_string());
    commands.insert("rm -rf".to_string(), "echo 'Use trash command for safety'".to_string());
    
    commands
}

/// Gets the current project name for variable substitution.
fn get_project_name() -> String {
    std::env::current_dir()
        .ok()
        .and_then(|dir| dir.file_name().map(|name| name.to_string_lossy().to_string()))
        .unwrap_or_else(|| "project".to_string())
}


/// Ensures required sections exist in an existing config file.
/// 
/// # Arguments
/// * `config_path` - Path to the configuration file
/// 
/// # Returns
/// * `Ok(())` - Configuration updated successfully
/// * `Err` - If file operations fail
fn ensure_config_sections(config_path: &str) -> Result<()> {
    let mut config_content = fs::read_to_string(config_path)
        .with_context(|| format!("Failed to read config file: {config_path}"))?;
    
    let mut needs_update = false;
    
    // Check and add missing sections
    if !config_content.contains("[commands]") {
        config_content.push_str("\n# Command mappings - suggest alternatives when Claude Code runs these commands\n");
        config_content.push_str("[commands]\n");
        config_content.push_str("# npm = \"bun\"          # Suggest 'bun' instead of 'npm'\n");
        config_content.push_str("# yarn = \"bun\"         # Suggest 'bun' instead of 'yarn'\n");
        config_content.push_str("# npx = \"bunx\"         # Suggest 'bunx' instead of 'npx'\n");
        config_content.push_str("# grep = \"rg\"          # Suggest 'rg' (ripgrep) instead of 'grep'\n\n");
        needs_update = true;
        println!("✅ Added [commands] section with examples");
    }
    
    if !config_content.contains("[semantic_directories]") {
        config_content.push_str("# Semantic directory aliases - natural language directory references\n");
        config_content.push_str("[semantic_directories]\n");
        config_content.push_str("docs = \"~/Documents/Documentation\"\n");
        config_content.push_str("central_docs = \"~/Documents/Documentation\"\n");
        config_content.push_str("project_docs = \"~/Documents/Documentation/my-project\"\n");
        config_content.push_str("claude_docs = \"~/Documents/Documentation/claude\"\n\n");
        needs_update = true;
        println!("✅ Added [semantic_directories] section with default aliases");
    }
    
    
    if needs_update {
        fs::write(config_path, config_content)
            .with_context(|| format!("Failed to update config file: {config_path}"))?;
        println!("💾 Configuration file updated");
    } else {
        println!("✅ All required sections already present");
    }
    
    Ok(())
}


#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;
    use serde_json::json;
    
    // Helper function to run a test in a temporary directory
    fn with_temp_dir<F>(test: F) 
    where 
        F: FnOnce(),
    {
        let temp_dir = tempdir().unwrap();
        let original_dir = std::env::current_dir().unwrap();
        
        // Change to temp directory
        std::env::set_current_dir(temp_dir.path()).unwrap();
        
        // Run test with proper cleanup
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            test();
        }));
        
        // Always restore original directory
        std::env::set_current_dir(&original_dir).unwrap();
        
        // Re-panic if test panicked
        if let Err(err) = result {
            std::panic::resume_unwind(err);
        }
    }
    
    #[test]
    fn test_hooks_already_exist_no_settings_file() {
        with_temp_dir(|| {
            let result = hooks_already_exist().unwrap();
            assert!(!result, "Should return false when no settings files exist");
        });
    }
    
    #[test]
    fn test_hooks_already_exist_empty_settings() {
        with_temp_dir(|| {
            // Create .claude directory and empty settings file
            fs::create_dir_all(".claude").unwrap();
            let settings_content = json!({});
            fs::write(".claude/settings.local.json", serde_json::to_string_pretty(&settings_content).unwrap()).unwrap();
            
            let result = hooks_already_exist().unwrap();
            assert!(!result, "Should return false when settings file has no hooks");
        });
    }
    
    #[test]
    fn test_hooks_already_exist_with_our_hooks() {
        with_temp_dir(|| {
            // Create .claude directory and settings file with our hooks
            fs::create_dir_all(".claude").unwrap();
            let settings_content = json!({
                "hooks": {
                    "PreToolUse": [
                        {
                            "matcher": "Bash",
                            "hooks": [
                                {
                                    "type": "command",
                                    "command": "claude-hook-advisor --hook"
                                }
                            ]
                        }
                    ]
                }
            });
            fs::write(".claude/settings.local.json", serde_json::to_string_pretty(&settings_content).unwrap()).unwrap();
            
            let result = hooks_already_exist().unwrap();
            assert!(result, "Should return true when our hooks are present");
        });
    }
    
    #[test]
    fn test_hooks_already_exist_with_other_hooks() {
        with_temp_dir(|| {
            // Create .claude directory and settings file with other hooks
            fs::create_dir_all(".claude").unwrap();
            let settings_content = json!({
                "hooks": {
                    "PreToolUse": [
                        {
                            "matcher": "Bash",
                            "hooks": [
                                {
                                    "type": "command",
                                    "command": "some-other-tool --hook"
                                }
                            ]
                        }
                    ]
                }
            });
            fs::write(".claude/settings.local.json", serde_json::to_string_pretty(&settings_content).unwrap()).unwrap();
            
            let result = hooks_already_exist().unwrap();
            assert!(!result, "Should return false when only other hooks are present");
        });
    }
    
    #[test]
    fn test_hooks_already_exist_userprompsubmit_hooks() {
        with_temp_dir(|| {
            // Create .claude directory and settings file with UserPromptSubmit hooks
            fs::create_dir_all(".claude").unwrap();
            let settings_content = json!({
                "hooks": {
                    "UserPromptSubmit": [
                        {
                            "hooks": [
                                {
                                    "type": "command",
                                    "command": "/path/to/claude-hook-advisor --hook"
                                }
                            ]
                        }
                    ]
                }
            });
            fs::write(".claude/settings.local.json", serde_json::to_string_pretty(&settings_content).unwrap()).unwrap();
            
            let result = hooks_already_exist().unwrap();
            assert!(result, "Should return true when UserPromptSubmit hooks are present");
        });
    }
    
    #[test]
    fn test_hooks_already_exist_prefers_local_settings() {
        with_temp_dir(|| {
            // Create .claude directory
            fs::create_dir_all(".claude").unwrap();
            
            // Create shared settings with our hooks
            let shared_settings = json!({
                "hooks": {
                    "PreToolUse": [
                        {
                            "matcher": "Bash",
                            "hooks": [
                                {
                                    "type": "command",
                                    "command": "claude-hook-advisor --hook"
                                }
                            ]
                        }
                    ]
                }
            });
            fs::write(".claude/settings.json", serde_json::to_string_pretty(&shared_settings).unwrap()).unwrap();
            
            // Create local settings without our hooks
            let local_settings = json!({});
            fs::write(".claude/settings.local.json", serde_json::to_string_pretty(&local_settings).unwrap()).unwrap();
            
            let result = hooks_already_exist().unwrap();
            assert!(!result, "Should check local settings first and return false when they don't have our hooks");
        });
    }
    
    #[test] 
    fn test_create_example_config() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("test-config.toml");
        
        create_smart_config(config_path.to_str().unwrap()).unwrap();
        
        let content = fs::read_to_string(&config_path).unwrap();
        
        // Check that all required sections are present
        assert!(content.contains("[commands]"));
        assert!(content.contains("[semantic_directories]"));
        
        // Check that default aliases are present
        assert!(content.contains("docs = \"~/Documents/Documentation\""));
        assert!(content.contains("docs = \"~/Documents/Documentation\""));
        
        // Check that comments are present
        assert!(content.contains("# Claude Hook Advisor Configuration"));
        assert!(content.contains("# Uncomment and customize these examples:"));
    }
    
    #[test]
    fn test_ensure_config_sections_missing_sections() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("test-config.toml");
        
        // Create minimal config missing sections
        fs::write(&config_path, "# Minimal config\n").unwrap();
        
        ensure_config_sections(config_path.to_str().unwrap()).unwrap();
        
        let content = fs::read_to_string(&config_path).unwrap();
        
        // Check that all sections were added
        assert!(content.contains("[commands]"));
        assert!(content.contains("[semantic_directories]"));
        
        // Check that examples were added
        assert!(content.contains("docs = \"~/Documents/Documentation\""));
        assert!(content.contains("# npm = \"bun\""));
    }
    
    #[test]
    fn test_ensure_config_sections_all_sections_present() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("test-config.toml");
        
        let existing_config = r#"# Existing config
[commands]
npm = "bun"

[semantic_directories]
docs = "~/Documents"
"#;
        fs::write(&config_path, existing_config).unwrap();
        
        ensure_config_sections(config_path.to_str().unwrap()).unwrap();
        
        let content = fs::read_to_string(&config_path).unwrap();
        
        // Should be unchanged since all sections already exist
        assert_eq!(content, existing_config);
    }
}