hook-optimization
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.
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 [[ "$fiRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.