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
# Hooks Guide Analysis: Implemented vs Opportunities

**Date:** November 10, 2025
**Purpose:** Compare claude-hook-advisor implementation against official Claude Code Hooks Guide

## Executive Summary

claude-hook-advisor implements **3 of 9** available hook types with a focused use case: command mapping and directory aliasing. The official hooks guide reveals **6 additional hook types** and **multiple use cases** not yet explored. This analysis identifies concrete opportunities to expand the tool's capabilities.

---

## Hook Types: Coverage Matrix

| Hook Type | Status | Current Use | Opportunity |
|-----------|--------|-------------|-------------|
| **PreToolUse** | ✅ Implemented | Command mapping/blocking | ✓ Expand to other tools beyond Bash |
| **PostToolUse** | ✅ Implemented | Basic execution tracking | ✓ Add code formatting, analytics |
| **UserPromptSubmit** | ✅ Implemented | Directory aliasing | ✓ Add learning from user feedback |
| **Notification** | ❌ Not implemented | N/A | Desktop alerts, custom notifications |
| **Stop** | ❌ Not implemented | N/A | Session cleanup, analytics export |
| **SubagentStop** | ❌ Not implemented | N/A | Subagent task tracking |
| **PreCompact** | ❌ Not implemented | N/A | Conversation history optimization |
| **SessionStart** | ❌ Not implemented | N/A | Environment validation, setup |
| **SessionEnd** | ❌ Not implemented | N/A | Statistics summary, cleanup |

**Coverage:** 3/9 hooks (33%)

---

## Use Cases: Official Guide vs Implementation

### Currently Implemented ✅

#### 1. Command Mapping (PreToolUse)
**Implementation:**
```rust
// src/hooks.rs:69-104
fn handle_pre_tool_use(config: &Config, hook_input: &HookInput, replace_mode: bool)
```
- Maps commands (npm → bun, curl → wget)
- Start-of-line regex matching prevents false positives
- Block or replace mode support
- Cached regex compilation for performance

**Alignment with Guide:** Strong - Matches "Custom permissions" use case

#### 2. Directory Aliasing (UserPromptSubmit)
**Implementation:**
```rust
// src/hooks.rs:118-141
fn handle_user_prompt_submit(config: &Config, hook_input: &HookInput)
```
- Detects semantic directory references in user prompts
- Resolves aliases to canonical paths
- Security: path canonicalization prevents traversal attacks

**Alignment with Guide:** Novel - Not explicitly mentioned in guide (innovation!)

#### 3. Execution Tracking (PostToolUse)
**Implementation:**
```rust
// src/hooks.rs:155-180
fn handle_post_tool_use(_config: &Config, hook_input: &HookInput)
```
- Basic success/failure logging
- Exit code tracking

**Alignment with Guide:** Minimal - Guide suggests richer analytics

---

### Opportunities from Hooks Guide 🎯

#### 1. **Automatic Code Formatting** (PostToolUse)
**Official Guide Example:**
> "Automatically formats TypeScript files using Prettier after file edits"

**Implementation Opportunity:**
```toml
[formatting]
"*.ts" = "prettier --write"
"*.tsx" = "prettier --write"
"*.rs" = "rustfmt"
"*.py" = "black"
"*.go" = "gofmt -w"
"*.md" = "prettier --write"
```

**Value:**
- Zero-effort code consistency
- Follows official guide's primary use case
- Integrates with existing PostToolUse handler

**Implementation Estimate:** Medium (2-3 days)
- Add `[formatting]` section to TOML config
- Detect file edits in PostToolUse via tool_name (Edit, Write, NotebookEdit)
- Execute formatter commands conditionally
- Handle formatter failures gracefully

---

#### 2. **Custom Notifications** (Notification Hook)
**Official Guide Example:**
> "Desktop alerts via notify-send when Claude awaits input"

**Implementation Opportunity:**
```toml
[notifications]
enable_desktop = true
command = "notify-send"
on_user_input_required = true
on_approval_required = true
on_error = true
```

**Value:**
- User attention when Claude needs input
- Follows official guide's notification pattern
- Works for desktop environments (Linux/macOS)

**Implementation Estimate:** Small (1-2 days)
- Add Notification hook handler
- Detect notification types from hook input
- Execute configurable notification commands
- Cross-platform support (notify-send, osascript, toast)

---

#### 3. **Session Lifecycle Management** (SessionStart/SessionEnd)
**Official Guide Coverage:**
> "SessionStart: Activates when sessions begin or resume"
> "SessionEnd: Executes when sessions terminate"

**Implementation Opportunity:**

**SessionStart:**
```toml
[session_start]
validate_environment = true
check_git_status = true
load_project_context = true
commands = [
    "git fetch --quiet",
    "echo 'Session started at $(date)'",
]
```

**SessionEnd:**
```toml
[session_end]
export_analytics = true
cleanup_temp_files = true
commands = [
    "echo 'Session ended at $(date)'",
    "echo 'Commands executed: {command_count}'",
]
```

**Value:**
- Environment validation before Claude starts
- Session statistics and cleanup
- Project context loading

**Implementation Estimate:** Medium (3-4 days)
- Add SessionStart handler for environment checks
- Add SessionEnd handler for analytics export
- Track session-level metrics (command counts, suggestions)
- Implement statistics summary formatting

---

#### 4. **Enhanced Command Logging** (PostToolUse)
**Official Guide Example:**
> "Uses jq to extract and log bash commands to a text file"

**Current Gap:** Basic console output only

**Implementation Opportunity:**
```toml
[logging]
enabled = true
log_file = "~/.claude-hook-advisor/command-history.jsonl"
include_exit_codes = true
include_timestamps = true
include_session_id = true
```

**Value:**
- Audit trail for compliance
- Debugging command issues
- Analytics for command success rates
- Follows official guide pattern

**Implementation Estimate:** Small (1-2 days)
- Add structured logging to PostToolUse
- JSONL format for easy parsing
- Optional log rotation
- Privacy controls (filter sensitive commands)

---

#### 5. **File Protection** (PreToolUse)
**Official Guide Example:**
> "Blocks edits to sensitive files like .env and .git/"

**Current Gap:** Only handles Bash commands

**Implementation Opportunity:**
```toml
[file_protection]
enabled = true
protected_paths = [
    ".env",
    ".env.*",
    ".git/**",
    "secrets/**",
    "credentials.json",
]
block_message = "This file is protected. Use --force-edit to override."
```

**Value:**
- Prevents accidental credential leaks
- Follows official guide's security pattern
- Extends PreToolUse to Edit/Write tools

**Implementation Estimate:** Medium (2-3 days)
- Extend PreToolUse to handle Edit/Write/NotebookEdit tools
- Pattern matching for protected paths
- Override mechanism for intentional edits
- Audit logging of protection violations

---

#### 6. **Markdown Code Block Enhancement** (PostToolUse)
**Official Guide Example:**
> "Python script detects programming languages in code blocks and adds appropriate tags"

**Implementation Opportunity:**
```toml
[markdown_enhancement]
enabled = true
auto_detect_language = true
add_syntax_highlighting = true
```

**Value:**
- Automatic language detection in code blocks
- Improves markdown documentation quality
- Follows official guide pattern

**Implementation Estimate:** Medium (2-3 days)
- Detect markdown file edits in PostToolUse
- Use language detection library (linguist, tree-sitter)
- Update code blocks with language tags
- Handle edge cases (already-tagged blocks)

---

#### 7. **Subagent Task Tracking** (SubagentStop)
**Official Guide Coverage:**
> "Executes when subagent tasks complete"

**Implementation Opportunity:**
```toml
[subagent_tracking]
enabled = true
log_completion = true
track_success_rate = true
notify_on_failure = true
```

**Value:**
- Track subagent effectiveness
- Debug complex multi-agent tasks
- Analytics for agent performance

**Implementation Estimate:** Medium (2-3 days)
- Add SubagentStop hook handler
- Track subagent task metadata
- Success rate analytics
- Optional notifications on failures

---

#### 8. **Pre-Compact Optimization** (PreCompact)
**Official Guide Coverage:**
> "Runs before compact operations"

**Implementation Opportunity:**
```toml
[compact_optimization]
enabled = true
preserve_important_context = true
mark_key_decisions = true
```

**Value:**
- Preserve critical context during compaction
- Optimize conversation history
- Reduce token waste

**Implementation Estimate:** Small-Medium (2-3 days)
- Add PreCompact hook handler
- Identify important context markers
- Suggest preservation strategies to Claude
- Track compaction statistics

---

## Priority Recommendations

### High Priority (Immediate Value)

1. **Automatic Code Formatting** (PostToolUse)
   - Aligns with primary guide use case
   - High user value
   - Leverages existing PostToolUse infrastructure
   - **Effort:** Medium | **Impact:** High

2. **Custom Notifications** (Notification Hook)
   - Explicit guide example
   - Improves user experience
   - Low implementation complexity
   - **Effort:** Small | **Impact:** Medium

3. **Enhanced Command Logging** (PostToolUse)
   - Explicit guide example
   - Compliance/debugging value
   - Extends existing functionality
   - **Effort:** Small | **Impact:** Medium

### Medium Priority (Workflow Enhancement)

4. **Session Lifecycle Management** (SessionStart/SessionEnd)
   - Official guide coverage
   - Professional workflow benefits
   - Foundation for analytics
   - **Effort:** Medium | **Impact:** Medium

5. **File Protection** (PreToolUse Extension)
   - Explicit guide example
   - Security value
   - Natural PreToolUse extension
   - **Effort:** Medium | **Impact:** Medium

### Lower Priority (Advanced Features)

6. **Markdown Code Block Enhancement** (PostToolUse)
   - Guide example
   - Niche use case
   - Requires external dependencies
   - **Effort:** Medium | **Impact:** Low-Medium

7. **Subagent Task Tracking** (SubagentStop)
   - New hook type
   - Advanced use case
   - Less common workflow
   - **Effort:** Medium | **Impact:** Low

8. **Pre-Compact Optimization** (PreCompact)
   - Experimental/advanced
   - Unclear value proposition
   - Complex implementation
   - **Effort:** Medium | **Impact:** Low

---

## Implementation Roadmap

### Phase 1: Core Use Cases (Weeks 1-2)
- [ ] Automatic code formatting (PostToolUse)
- [ ] Custom notifications (Notification hook)
- [ ] Enhanced command logging (PostToolUse)

**Deliverable:** v0.3.0 with official guide alignment

### Phase 2: Lifecycle & Security (Weeks 3-4)
- [ ] Session lifecycle management (SessionStart/SessionEnd)
- [ ] File protection (PreToolUse extension)

**Deliverable:** v0.4.0 with professional workflow features

### Phase 3: Advanced Features (Weeks 5-6)
- [ ] Markdown enhancement (PostToolUse)
- [ ] Subagent tracking (SubagentStop)
- [ ] Pre-compact optimization (PreCompact)

**Deliverable:** v0.5.0 with full hook coverage

---

## Technical Considerations

### Architecture Impact

**Current Structure:**
```rust
pub fn run_as_hook(config_path: &str, replace_mode: bool) -> Result<()> {
    match hook_input.hook_event_name.as_str() {
        "PreToolUse" => handle_pre_tool_use(...),
        "UserPromptSubmit" => handle_user_prompt_submit(...),
        "PostToolUse" => handle_post_tool_use(...),
        _ => eprintln!("Warning: Unknown hook event type"),
    }
}
```

**Needed Additions:**
```rust
match hook_input.hook_event_name.as_str() {
    "PreToolUse" => handle_pre_tool_use(...),
    "PostToolUse" => handle_post_tool_use(...),
    "UserPromptSubmit" => handle_user_prompt_submit(...),
    "Notification" => handle_notification(...),        // NEW
    "Stop" => handle_stop(...),                        // NEW
    "SubagentStop" => handle_subagent_stop(...),       // NEW
    "PreCompact" => handle_pre_compact(...),           // NEW
    "SessionStart" => handle_session_start(...),       // NEW
    "SessionEnd" => handle_session_end(...),           // NEW
    _ => eprintln!("Warning: Unknown hook event type"),
}
```

### Configuration Schema Evolution

**Current:**
```toml
[commands]
npm = "bun"

[semantic_directories]
docs = "~/Documents/Documentation"
```

**Proposed Extensions:**
```toml
[commands]
npm = "bun"

[semantic_directories]
docs = "~/Documents/Documentation"

[formatting]
"*.rs" = "rustfmt"

[notifications]
enable_desktop = true

[logging]
log_file = "~/.claude-hook-advisor/command-history.jsonl"

[file_protection]
protected_paths = [".env", ".git/**"]

[session_start]
validate_environment = true

[session_end]
export_analytics = true

[subagent_tracking]
enabled = true

[compact_optimization]
enabled = true

[markdown_enhancement]
enabled = true
```

### Backward Compatibility

**Strategy:**
- All new sections optional (use `#[serde(default)]`)
- Existing configs continue working unchanged
- Feature flags for gradual rollout
- Comprehensive migration guide

---

## Security Considerations

From the official guide:
> "You must consider the security implication of hooks as you add them, because hooks run automatically during the agent loop with your current environment's credentials."

**For New Features:**

1. **File Protection:**
   - Prevent credential leakage
   - Audit all protection overrides
   - Default to paranoid security

2. **Command Logging:**
   - Sanitize sensitive data (passwords, tokens)
   - Configurable filtering
   - Secure log file permissions (0600)

3. **Notifications:**
   - Avoid exposing sensitive content in notifications
   - User control over notification verbosity
   - Respect privacy preferences

4. **Session Lifecycle:**
   - Validate environment safely
   - No automatic credential access
   - User approval for sensitive operations

---

## Documentation Gaps

### What the Guide Covers Well:
- Hook event types and timing
- Primary use cases with examples
- Security warnings
- Configuration structure

### What the Guide Could Expand:
- Detailed JSON schema for each hook type
- Tool name enumeration (Bash, Edit, Write, etc.)
- Cross-platform considerations
- Performance best practices
- Error handling patterns

### Opportunities for claude-hook-advisor Docs:
- Become reference implementation
- Provide comprehensive examples
- Document hook interaction patterns
- Share performance benchmarks

---

## Competitive Analysis

**Similar Tools:**
- Shell aliases (static, no AI integration)
- Git hooks (narrow scope)
- Package manager configs (tool-specific)

**claude-hook-advisor Advantages:**
- Dynamic, AI-aware command mapping
- Multi-hook integration
- Natural language directory references
- Extensible architecture

**Differentiation Opportunities:**
1. **Only tool with full 9-hook coverage** (after implementation)
2. **Reference implementation** for Claude Code hooks guide
3. **Comprehensive example collection** for hook patterns
4. **Production-ready** with security, performance, testing

---

## Community & Contribution

### Potential Contributions:

1. **Hook Pattern Library:**
   - Community-contributed hook configurations
   - Best practices collection
   - Domain-specific profiles (web dev, ML, DevOps)

2. **Integration Examples:**
   - CI/CD pipeline hooks
   - Team collaboration patterns
   - Security compliance templates

3. **Educational Content:**
   - Tutorial series for each hook type
   - Video demonstrations
   - Conference talks/blog posts

---

## Success Metrics

### Quantitative:
- Hook coverage: 33% → 100% (9/9 hooks)
- Use case coverage: 2 → 7 (guide-aligned features)
- GitHub stars: Track adoption
- crates.io downloads: Track usage

### Qualitative:
- User testimonials
- Feature requests (guide vs custom)
- Documentation clarity feedback
- Community contributions

---

## Conclusion

claude-hook-advisor has a **strong foundation** with 3/9 hooks implemented for a focused use case. The official hooks guide reveals **significant expansion opportunities** across 6 additional hook types and 5 primary use cases.

**Key Takeaways:**

1. **Strong Current Implementation:** Command mapping and directory aliasing are well-executed with proper security and performance considerations.

2. **Clear Roadmap:** Official guide provides explicit examples (code formatting, notifications, logging, file protection) ready for implementation.

3. **Innovation Potential:** Directory aliasing demonstrates innovation beyond the guide—continue exploring unique use cases.

4. **Strategic Position:** Could become **the reference implementation** for Claude Code hooks if expanded to full coverage.

**Recommended Next Step:** Implement **Automatic Code Formatting** (PostToolUse) as it aligns with the guide's primary use case, provides immediate user value, and leverages existing infrastructure.

---

**Generated by:** Claude Code Hooks Guide Analysis
**Repository:** https://github.com/sirmews/claude-hook-advisor
**Documentation:** https://code.claude.com/docs/en/hooks-guide.md