Claude
Skills
Sign in
Back

hook-optimization

Included with Lifetime
$97 forever

Provides guidance on optimizing CCPM hooks for performance and token efficiency. Auto-activates when developing, debugging, or benchmarking hooks. Includes caching strategies, token budgets, performance benchmarking, and best practices for maintaining sub-5-second hook execution times.

General

What this skill does


# CCPM Hook Optimization Skill

This skill provides comprehensive guidance for optimizing Claude Code hooks used in CCPM (Claude Code Project Management) to ensure high performance, minimal token usage, and reliable execution.

## Table of Contents

1. [Hook System Overview](#hook-system-overview)
2. [Performance Requirements](#performance-requirements)
3. [The Three Main Hooks](#the-three-main-hooks)
4. [Optimization Strategies](#optimization-strategies)
5. [Cached Agent Discovery](#cached-agent-discovery)
6. [Token Optimization Techniques](#token-optimization-techniques)
7. [Benchmarking & Profiling](#benchmarking--profiling)
8. [Hook Development Workflow](#hook-development-workflow)
9. [Best Practices](#best-practices)
10. [Examples & Case Studies](#examples--case-studies)

---

## Hook System Overview

### What are Claude Code Hooks?

Claude Code hooks are event-based automation points that trigger Claude to perform intelligent actions at specific moments in the development workflow:

- **UserPromptSubmit**: Triggered when user sends a message
- **PreToolUse**: Triggered before file write/edit operations
- **Stop**: Triggered after Claude completes a response

### CCPM's Three Main Hooks

| Hook | Trigger | Purpose | Target Time |
|------|---------|---------|-------------|
| **smart-agent-selector-optimized.prompt** | UserPromptSubmit | Intelligent agent selection & invocation | <5s |
| **tdd-enforcer-optimized.prompt** | PreToolUse | Ensure tests exist before code | <1s |
| **quality-gate-optimized.prompt** | Stop | Automatic code review & security audit | <5s |

### Hook Execution Flow

```
User Message
    ↓
[UserPromptSubmit Hook]
    ↓ smart-agent-selector analyzes request
    ↓ Selects best agents (with caching)
    ↓ Injects agent invocation instructions
    ↓
Claude Executes (Agents run in parallel/sequence)
    ↓
File Write/Edit Request
    ↓
[PreToolUse Hook]
    ↓ tdd-enforcer checks for tests
    ↓ Blocks if missing (invokes tdd-orchestrator)
    ↓
File Created/Modified
    ↓
Response Complete
    ↓
[Stop Hook]
    ↓ quality-gate analyzes changes
    ↓ Invokes code-reviewer, security-auditor
    ↓
Complete
```

---

## Performance Requirements

### Target Metrics

**Execution Time:**
- UserPromptSubmit hook: <5 seconds (with caching: <2 seconds)
- PreToolUse hook: <1 second
- Stop hook: <5 seconds

**Token Budget:**
- Per hook: <5,000 tokens
- Combined overhead: <10,000 tokens per user message

**Cache Performance:**
- Cache hit rate: 85-95%
- Cached execution: <100ms (vs ~2,000ms uncached)
- Cache invalidation: 5 minutes TTL

### Why These Targets Matter

```
User Experience Impact:
- <1s → Feels instant, no latency
- 1-5s → Acceptable delay
- >5s → Noticeable lag, frustrating

Token Budget Impact:
- <5,000 tokens per hook → Minimal overhead
- <10,000 tokens total → <5% of typical context window
- Well-optimized hooks → Enable more complex agent selection
```

---

## The Three Main Hooks

### 1. Smart Agent Selector (UserPromptSubmit)

**Purpose**: Analyze user request and automatically invoke best agents

**Original Version**: 19,307 lines, ~4,826 tokens
**Optimized Version**: 3,538 lines, ~884 tokens
**Improvement**: 82% token reduction

**Key Optimizations**:
- Removed verbose explanations (inline comments instead)
- Simplified response format (JSON without markdown)
- Cached agent discovery
- Conditional logic (skip for simple docs questions)

**Execution Flow**:
```
User: "Add authentication with JWT"
    ↓
[smart-agent-selector]
    ↓ Task: Implementation
    ↓ Keywords: auth, jwt, security
    ↓ Tech Stack: backend (detected)
    ↓ Score: tdd-orchestrator (85), backend-architect (95), security-auditor (90)
    ↓ Decision: Sequential execution
    ↓
Result: {
  "shouldInvokeAgents": true,
  "selectedAgents": [...],
  "execution": "sequential",
  "injectedInstructions": "..."
}
```

### 2. TDD Enforcer (PreToolUse)

**Purpose**: Ensure test files exist before writing production code

**Original Version**: 4,853 lines, ~1,213 tokens
**Optimized Version**: 2,477 lines, ~619 tokens
**Improvement**: 49% token reduction

**Key Optimizations**:
- Hardcoded test file patterns (no dynamic detection)
- Single-pass file existence check
- Simplified JSON response
- Skip expensive type inference

**Decision Matrix**:
```
Is test file?              → APPROVE (writing tests first)
Tests exist for module?    → APPROVE (tests are ready)
Config/docs file?         → APPROVE (no TDD needed)
Production code no tests? → BLOCK (invoke tdd-orchestrator)
User bypass?              → APPROVE (with warning)
```

### 3. Quality Gate (Stop Hook)

**Purpose**: Automatically invoke code review and security audit

**Original Version**: 4,482 lines, ~1,120 tokens
**Optimized Version**: 2,747 lines, ~687 tokens
**Improvement**: 39% token reduction

**Key Optimizations**:
- Reduced scoring complexity
- Fixed agent list (not dynamic)
- Simplified file type detection
- Removed verbose explanations

**Decision Rules**:
```
Code files modified?      → Invoke code-reviewer
API/auth code?            → Invoke security-auditor (blocking)
3+ files changed?         → Invoke code-reviewer
Only docs/tests?          → SKIP (no review needed)
```

---

## Optimization Strategies

### 1. Use Cached Agent Discovery

**Problem**: Full agent discovery takes ~2,000ms

**Solution**: Cache agent list with 5-minute TTL

**Implementation**:
```bash
# Original: Slow discovery
agents=$(jq -r '.plugins | keys[]' ~/.claude/plugins/installed_plugins.json)
# Result: ~2,000ms per execution

# Optimized: Cached discovery
CACHE_FILE="${TMPDIR:-/tmp}/claude-agents-cache-$(id -u).json"
CACHE_MAX_AGE=300  # 5 minutes

if [ -f "$CACHE_FILE" ]; then
  if [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE"))) -lt 300 ]; then
    cat "$CACHE_FILE"  # <100ms hit
    exit 0
  fi
fi
# Result: <100ms for cache hits, 96% faster
```

**Cache Performance**:
```
First run:     2,000ms (cache miss)
Subsequent:       20ms (cache hit)
After 5 min:   2,000ms (cache expired)

Expected hit rate: 85-95% (5-minute window typical)
Expected savings: 1,900ms per cached call
```

### 2. Minimize Context Injection

**Problem**: Injecting entire codebase context bloats tokens

**Solution**: Inline only critical information

**Before** (Verbose):
```
Available agents include:
- tdd-orchestrator: This agent is responsible for writing tests following the Red-Green-Refactor workflow. It can handle unit tests, integration tests, and end-to-end tests...
- backend-architect: The backend architect provides guidance on API design, database schemas, microservices patterns...
[continues for 50 agents]
```

**After** (Concise):
```json
{
  "availableAgents": [
    {"name": "tdd-orchestrator", "score": 85, "reason": "TDD workflow"},
    {"name": "backend-architect", "score": 95, "reason": "API design"}
  ]
}
```

**Token Savings**: 60-70% reduction

### 3. Progressive Disclosure

**Concept**: Only show information when needed

**Example - Agent Selection**:
```
Level 1 (Default): Show top 3 agents with scores
Level 2 (If needed): Show all 10 agents with reasoning
Level 3 (Debugging): Show full scoring breakdown
```

**Implementation**:
```bash
# Don't include full descriptions
"availableAgents": [
  {"name": "agent-1", "score": 85}
  # Skip: "description": "Long description..."
]

# Only explain top choice
"reasoning": "Selected top 3 agents by score"
# Skip detailed reasoning for each
```

### 4. Conditional Logic (Skip Unnecessary Work)

**Problem**: Hooks run on every message, even simple ones

**Solution**: Fast-path for low-complexity requests

**Smart Agent Selector Example**:
```javascript
// Fast path: Simple docs question
if (message.includes("how to") && !message.includes("code")) {
  return {
    "shouldInvokeAgents": false,
    "reasoning": "Documentation question, skip agents"
  }
}

// Normal path: Requires agent selection
// ... full scoring algorithm
```

**TDD Enforcer Example**:
```bash
# Fast path: Test file
if [[ "$fi
Files: 1
Size: 22.9 KB
Complexity: 33/100
Category: General

Related in General