Skip to main content

What Are Hooks?

Hooks are event-driven automation points that run at specific moments in your Claude Code workflow. Pro Workflow provides 18 hook events that enable quality gates, learning capture, drift detection, and workflow orchestration. Think of hooks as the nervous system of your AI workflow—they observe, react, and adapt based on what’s happening in your coding session.
Hooks run automatically in the background. They don’t interrupt Claude’s work, but they surface helpful reminders and capture metadata for continuous improvement.

Why Hooks Matter

The self-correction loop depends on hooks to:

Track Patterns

Monitor edit counts, correction rates, and quality metrics across sessions

Enforce Quality Gates

Remind to run lint, typecheck, and tests at optimal checkpoints

Capture Learnings

Auto-extract [LEARN] blocks from responses into SQLite database

Detect Drift

Alert when work diverges from the original task intent

The 18 Hook Events

Session Lifecycle

1

SessionStart

Loads learned patterns from database, displays recent session stats, checks for parallel worktreesWhen: New session begins
Script: session-start.js
Use Case: Context restoration, learning replay
2

SessionEnd

Saves session stats to database, reminds about wrap-up, warns about uncommitted changesWhen: Session closes
Script: session-end.js
Use Case: Session archival, final reminders

Tool Execution

HookTriggerPurposeScript
PreToolUseBefore Edit/WriteTrack edit count, quality gate remindersquality-gate.js
PreToolUseBefore git commitRemind to run quality gates (lint, typecheck)Inline script
PreToolUseBefore git pushSuggest /wrap-up to capture learningsInline script
PostToolUseAfter code editsCheck for console.log, TODOs, secretspost-edit-check.js
PostToolUseAfter testsSuggest [LEARN] blocks from test failuresInline script
PostToolUseFailureTool execution failsTrack failures, suggest debugging learningsInline script

User Interaction

UserPromptSubmit

When: Each user prompt
Scripts:
  • prompt-submit.js - Tracks prompts and correction patterns
  • drift-detector.js - Detects task drift from original intent
Use Case: Detect when work diverges from the original goal after 6+ edits

Stop

When: Each response completes
Scripts:
  • session-check.js - Context-aware reminders
  • learn-capture.js - Auto-capture [LEARN] blocks to database
Use Case: Passive learning extraction without user action

Agent Orchestration

1

SubagentStart

Logs when a subagent spawns for observabilityWhen: Agent teams launch background agents
Use Case: Track parallel agent execution in /develop workflows
2

SubagentStop

Logs agent completion and captures resultsWhen: Subagent finishes work
Use Case: Collect outputs from planner, reviewer, scout agents
3

TeammateIdle

Detects idle teammates in agent teamsWhen: Teammate has no pending work
Use Case: Identify blockers, reassign work dynamically

Advanced Events

TaskCompleted

Trigger: Task marked complete
Action: Remind to run quality gates before marking done
Use Case: Ensure validation before closing tasks

PermissionRequest

Trigger: Permission dialog appears
Action: Flag dangerous operations (rm -rf, deploy, force push)
Use Case: Security gate for destructive commands

PreCompact

Trigger: Before context compaction
Script: pre-compact.js
Use Case: Save context state before compression

ConfigChange

Trigger: Settings modified mid-session
Script: config-watcher.js
Use Case: Detect when quality gates or hooks are changed

Notification

Trigger: System events
Action: Log permission requests
Use Case: Observability for system-level events

Hook Configuration

Hooks are defined in hooks/hooks.json with this structure:
{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "tool == \"Edit\" || tool == \"Write\"",
        "hooks": [
          {
            "type": "command",
            "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/quality-gate.js\""
          }
        ],
        "description": "Track edits for quality gate checks"
      }
    ]
  }
}

Matcher Syntax

tool == "Edit" || tool == "Write"

Adaptive Quality Gates

The PreToolUse hook for edits implements adaptive thresholds based on your correction history:
1

High Correction Rate (>25%)

  • First checkpoint: 3 edits
  • Second checkpoint: 6 edits
  • Repeat every: 6 edits
2

Medium Correction Rate (15-25%)

  • First checkpoint: 5 edits
  • Second checkpoint: 10 edits
  • Repeat every: 10 edits
3

Low Correction Rate (5-15%)

  • First checkpoint: 8 edits
  • Second checkpoint: 15 edits
  • Repeat every: 15 edits
4

Very Low Correction Rate (<5%)

  • First checkpoint: 10 edits
  • Second checkpoint: 20 edits
  • Repeat every: 20 edits
Correction rates are calculated from the last 10 sessions in your SQLite database. The system learns when to remind you based on your actual mistake frequency.

Database Integration

All hook scripts integrate with the SQLite database at ~/.pro-workflow/data.db:
function getStore() {
  const distPath = path.join(__dirname, '..', 'dist', 'db', 'store.js');
  if (fs.existsSync(distPath)) {
    const { createStore } = require(distPath);
    return createStore();
  }
  return null;
}

Tracked Metrics

  • Session stats: edit count, correction count, prompt count, duration
  • Learnings: category, rule, mistake, correction, project context
  • Correction rates: used for adaptive quality gates
  • Session history: previous session stats for context restoration
If the database is unavailable, hooks fall back to temp file storage in /tmp/pro-workflow/. The system is resilient but database mode provides richer analytics.

Hook Output Format

Hooks output to stderr with the [ProWorkflow] prefix:
[ProWorkflow] 5 edits — checkpoint for review
[ProWorkflow] Run: git diff --stat | to see changes
[ProWorkflow] Loaded 3 learnings from database:
  - [Testing] Always run tests before committing
  - [TypeScript] Check for any types in strict mode
  - [Git] Use conventional commit format
This format ensures hooks don’t interfere with tool output (which uses stdout).

Next Steps

Hook Lifecycle

Visual guide to hook execution flow and event sequencing

Custom Hooks

Write your own hooks with matchers, scripts, and database integration

Available But Not Configured

These hooks are supported but not included in the default hooks.json:
  • Setup - One-time initialization
  • WorktreeCreate - Set up worktree config
  • WorktreeRemove - Cleanup on worktree deletion
Add them to hooks.json if you need custom worktree or setup automation.
Hooks are the foundation of the self-correction loop. The more sessions you complete, the smarter the system becomes at knowing when to remind you.

Build docs developers (and LLMs) love