---
title: "Hooks: What Fires When"
description: "Every Claude Code lifecycle event in order, and the OrchestKit hooks that fire on it: unsafe command blocks, context injection, memory sync and quality gates."
canonical: "https://orchestkit.dev/docs/hooks/overview"
---

# Hooks: What Fires When

Every Claude Code lifecycle event in order, and the OrchestKit hooks that fire on it: unsafe command blocks, context injection, memory sync and quality gates.

import { Callout } from "fumadocs-ui/components/callout";
import { Steps, Step } from "fumadocs-ui/components/steps";
import { Tab, Tabs } from "fumadocs-ui/components/tabs";
import { Count } from "@/components/count";

## What Is a Hook?

A hook is a TypeScript function that runs automatically at specific moments in a Claude Code session. Hooks receive a JSON payload on stdin describing the event (which tool, what input, which session) and return a JSON response on stdout that either allows the operation, blocks it, or injects additional context.

You never call hooks yourself. Claude Code calls them for you: on every tool use, every prompt, every session start and stop. They are the invisible guardians of your development workflow.

```typescript
// The fundamental hook contract
type HookFn = (input: HookInput) => HookResult | Promise<HookResult>;

// Allow the operation silently
{ continue: true, suppressOutput: true }

// Block the operation with a reason
{ continue: false, stopReason: "Direct commits to main are not allowed." }

// Allow but inject guidance for Claude
{ continue: true, hookSpecificOutput: { additionalContext: "Consider using cursor-based pagination." } }
```

## By the Numbers

Every number on this page is computed from the source tree at build time, so it cannot drift from what ships.

| Category | Count | Description |
|----------|-------|-------------|
| **Global hooks** | <Count k="hooks.global" /> | Fire on every matching event regardless of agent |
| **Agent-scoped hooks** | <Count k="hooks.agent" /> | Fire only when a specific agent is active |
| **Skill-scoped hooks** | <Count k="hooks.skill" /> | Fire only during specific skill operations |
| **Total** | **<Count k="hooks.total" />** hooks | Global ones registered in `hooks.json`, skill-scoped ones in `SKILL.md` frontmatter |
| **Lifecycle events used** | <Count k="hooks.events" /> | Distinct Claude Code events with at least one global hook |

Three words mean three different things on these pages:

- **Hook entry (source)**: one handler object in `src/hooks/hooks.json`. The global count above counts these.
- **Hook entry (shipped)**: one handler object in the `hooks.json` the plugin actually installs (`plugins/ork/hooks/hooks.json`). The build drops some source entries, so <Count k="hooks.shipped" /> entries ship, on <Count k="hooks.shippedEvents" /> events.
- **Logical hook**: one TypeScript function. A single entry can be a dispatcher that runs several logical hooks in order, which is why the per-event descriptions below name hooks rather than count them.

Every hook is written in TypeScript, compiled via esbuild into ESM bundles, and executed by Node.js. Zero external dependencies in production.

## Hook Events: The Full Timeline

Every Claude Code session follows the same lifecycle. Here is every event in the order it fires, and what OrchestKit does at each stage.

<Steps>
<Step>
### Setup

**When:** Plugin installation or first run.

Setup hooks handle first-run setup, maintenance checks, monorepo detection, and configuration repair.
</Step>

<Step>
### SessionStart

**When:** A new Claude Code session begins.

Entries registered: <Count k="hooks.byEvent.SessionStart" />. Among them: a unified dispatcher (fire-and-forget) launches background tasks (pattern sync, coordination init), the session context loader reads prior state, the analytics consent checker runs, the PR status enricher loads context for `--from-pr` sessions, and the prefill guard scans for deprecated API patterns.
</Step>

<Step>
### UserPromptSubmit

**When:** The user types a message and presses Enter.

Entries registered: <Count k="hooks.byEvent.UserPromptSubmit" />, mostly dispatchers. The profile injector and memory context loader fire once (first prompt only). The context injector, todo enforcer, memory context searcher, satisfaction detector, communication style tracker, antipattern detector, antipattern warning, context pruning advisor, pipeline detector, intent capturer, and queue recovery handler run on each prompt.
</Step>

<Step>
### PermissionRequest

**When:** Claude requests permission to use a tool.

Entries registered: <Count k="hooks.byEvent.PermissionRequest" />. Read/Glob/Grep operations are auto-approved (empty hook array; Claude Code allows them). Safe bash commands (git status, npm test, ls) are auto-approved. Writes within the project directory are auto-approved, excluding `node_modules`, `.git`, and `dist`.
</Step>

<Step>
### PreToolUse

**When:** After permission is granted, before the tool executes.

Entries registered: <Count k="hooks.byEvent.PreToolUse" />, selected by the tool matcher.

- **Bash**: one synchronous entry, `pretool/bash/sync-bash-dispatcher`, runs the checks in order: headless defer, network egress guard (DENY tier for executing fetched content), the issue reference, label and milestone enforcers, display lint, the advisory dispatcher (SDLC skill nudge, error pattern warner, affected tests finder), the pre-commit test gate, the worktree merge verifier, the playground presence warner and the stacked-PR branch delete guard. Destructive commands such as `rm -rf /` are refused by your own `permissions.deny` rules, not by a hook (see [Safety hooks](/docs/hooks/safety-hooks)).
- **Write|Edit**: one synchronous entry, `pretool/write-edit/sync-write-edit-dispatcher`, runs the content secret scanner, the context file budget guard, the dependency confusion scanner, the write headers injector and the quality dispatcher (security pattern validator, then architecture change detector). Protected files such as `.env` and private keys are refused by your own `permissions.deny` rules, not by a hook.
- **Skill**: Skill usage tracker.
- **MCP**: Context7 tracker, memory fabric initializer (once), memory validator.
- **Agent**: Sync task dispatcher, route observer, webhook forwarder. The sync task dispatcher still runs the security command audit; the other four agent safety checks were retired in #3835.
</Step>

<Step>
### PostToolUse

**When:** After a tool completes successfully.

Entries registered: <Count k="hooks.byEvent.PostToolUse" />. The main matchers:

- **Bash|Write|Edit|Task|Skill|NotebookEdit**: Unified dispatcher (fire-and-forget, runs the analytics hooks), context budget monitor, unified error handler.
- **Write|Edit**: File lock release, auto-lint, README sync, merge conflict predictor, coverage predictor, release lock on commit.
- **Bash**: Secret redactor.
</Step>

<Step>
### PostToolUseFailure

**When:** A tool fails (nonzero exit code, write error, etc.).

Entries registered: <Count k="hooks.byEvent.PostToolUseFailure" />. The failure handler logs the error, categorizes it, and provides recovery suggestions.
</Step>

<Step>
### SubagentStart / SubagentStop

**When:** A subagent (Task) is spawned or completes.

- **SubagentStart** (<Count k="hooks.byEvent.SubagentStart" /> entries): Context stager, graph memory inject, subagent validator, context gate, task linker, model cost advisor.
- **SubagentStop** (<Count k="hooks.byEvent.SubagentStop" /> entries): Unified dispatcher (fire-and-forget), output validator, auto-spawn quality gate, multi-claude verifier, subagent quality gate, task completer, retry handler.
</Step>

<Step>
### Notification

**When:** Claude Code emits a notification (permission prompt, idle, auth success).

Entries registered: <Count k="hooks.byEvent.Notification" />. Among them: a unified dispatcher for notification analytics, and a sound hook that plays audio alerts for permission prompts and idle notifications.
</Step>

<Step>
### PreCompact

**When:** Context window is about to be compacted.

Entries registered: <Count k="hooks.byEvent.PreCompact" />. The pre-compact saver preserves critical context (decisions, file list, key findings) before compaction discards conversation history.
</Step>

<Step>
### ConfigChange

**When:** `.claude/settings.json` or project config changes mid-session (CC 2.1.50+).

Allows hooks to react to configuration updates without restarting the session: for example, reloading permission rules or refreshing cached settings.
</Step>

<Step>
### InstructionsLoaded

**When:** `CLAUDE.md` and `.claude/rules/*.md` files are loaded (CC 2.1.69+).

Fires after all project instructions have been parsed. Useful for hooks that need to validate or augment loaded instructions: for example, checking for conflicting rules or injecting dynamic context based on instruction content.
</Step>

<Step>
### TeammateIdle / TaskCompleted

**When:** Multi-agent coordination events fire (CC 2.1.33+).

- **TeammateIdle** (<Count k="hooks.byEvent.TeammateIdle" /> entries): Progress reporter checks on idle teammates.
- **TaskCompleted** (<Count k="hooks.byEvent.TaskCompleted" /> entries): Completion tracker records task outcomes.
</Step>

<Step>
### WorktreeCreate / WorktreeRemove

**When:** A git worktree is created or removed (CC 2.1.50+).

These events fire on worktree lifecycle changes, enabling hooks to initialize or clean up worktree-specific state (coordination files, per-worktree caches, instance registration).
</Step>

<Step>
### Stop

**When:** The user ends the session (`/exit`, Ctrl+C, or session timeout).

Entries registered: <Count k="hooks.byEvent.Stop" />. The fire-and-forget entry starts a detached background worker that runs the cleanup hooks in parallel, so the session exits instantly. These cover context saving, memory sync, instance cleanup, security aggregation, and skill validation. See [Lifecycle Hooks](/docs/hooks/lifecycle-hooks) for the full breakdown.
</Step>

<Step>
### SessionEnd

**When:** The session is formally ending (after Stop).

Entries registered: <Count k="hooks.byEvent.SessionEnd" />. Among them: coordination cleanup (unregister instance, release locks), session metrics summary, session cleanup (temp files), and pattern sync push (upload learned patterns).
</Step>
</Steps>

## Architecture: Split Bundles

OrchestKit does not load all hooks into memory for every event. Instead, esbuild builds one bundle per event family (the table below lists them) and a unified bundle for CLI tools.

| Bundle | Size | Loaded When |
|--------|------|-------------|
| `permission.mjs` | 8 KB | PermissionRequest |
| `pretool.mjs` | 48 KB | PreToolUse |
| `posttool.mjs` | 58 KB | PostToolUse |
| `prompt.mjs` | 57 KB | UserPromptSubmit |
| `lifecycle.mjs` | 31 KB | SessionStart / SessionEnd |
| `stop.mjs` | 33 KB | Stop |
| `subagent.mjs` | 56 KB | SubagentStart / SubagentStop |
| `notification.mjs` | 5 KB | Notification |
| `setup.mjs` | 24 KB | Setup |
| `skill.mjs` | 52 KB | Skill operations |
| `hooks.mjs` (unified) | 324 KB | CLI tools only |

**Result:** ~89% per-load savings. A typical hook invocation loads ~35 KB instead of 324 KB.

The CLI runner (`bin/run-hook.mjs`) maps hook name prefixes to bundles automatically:

```javascript
const bundleMap = {
  permission: 'permission',
  pretool: 'pretool',
  posttool: 'posttool',
  prompt: 'prompt',
  lifecycle: 'lifecycle',
  stop: 'stop',
  'subagent-start': 'subagent',
  'subagent-stop': 'subagent',
  notification: 'notification',
  setup: 'setup',
  skill: 'skill',
};
```

## How a Hook Executes

Every hook registration in `hooks.json` follows this pattern:

```json
{
  "type": "command",
  "command": "node",
  "args": [
    "${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs",
    "pretool/bash/sync-bash-dispatcher"
  ]
}
```

Claude Code pipes the event payload to stdin, and the runner:

1. Parses the hook name from `process.argv[2]`
2. Maps the prefix (`pretool`) to the correct bundle (`pretool.mjs`)
3. Dynamic-imports the bundle
4. Looks up the hook function by its full name
5. Calls the function with the parsed input
6. Writes the `HookResult` JSON to stdout

For fire-and-forget hooks, a separate silent runner (`run-hook-silent.mjs`) is used, and for Stop events, `stop-fire-and-forget.mjs` spawns a detached background worker.

## Hook Types

Most hooks use `"type": "command"` to spawn a shell command. Two additional types exist:

| Type | Behavior | Example |
|------|----------|---------|
| `"command"` | Spawn a shell command, pipe JSON via stdin/stdout | All blocking and fire-and-forget hooks |
| `"http"` | POST JSON to a URL instead of spawning a process (CC 2.1.69+) | Supported; `hooks.json` registers <Count k="hooks.http" /> entries of this type today |

Native HTTP hooks (`"type": "http"`) send the hook input as a JSON POST body to the configured URL. They avoid the overhead of spawning a Node.js process, making them ideal for lightweight telemetry and webhook integrations.

## Special Hook Flags

Some hooks in `hooks.json` have additional flags:

| Flag | Meaning | Example |
|------|---------|---------|
| `"once": true` | Run only on the first matching event, then auto-remove (CC 2.1.69+) | <Count k="hooks.once" /> entries in `hooks.json` today; first-prompt-only hooks guard themselves instead |
| `"async": true` | Run in background without blocking | Analytics dispatchers (<Count k="hooks.async" /> entries) |
| `"timeout": 30` | Maximum execution time in seconds | Network I/O hooks |

## Mental Model: Invisible Guardians

Think of hooks as a security and productivity layer that wraps every action Claude takes:

- **Before** a bash command runs, your `permissions.deny` rules refuse commands such as `rm -rf /` and a force push to main, and the network egress guard blocks pipe-to-shell commands such as `curl url | sh`.
- **Before** a file is written, your `permissions.deny` rules refuse edits to `.env`, `.pem` and credential files, and the content secret scanner checks what is being written.
- **On every prompt**, the memory context hook searches the knowledge graph for relevant past decisions.
- **When a session ends**, background hooks save context, sync memory, and clean up coordination state, without making the user wait.

You get all of this automatically. No configuration required. The hooks are registered in `hooks.json` and fire based on matcher patterns that Claude Code evaluates against the current tool name.

<Callout type="info">
To learn about individual hook categories in depth, continue to [Lifecycle Hooks](/docs/hooks/lifecycle-hooks), [Safety Hooks](/docs/hooks/safety-hooks), and [Memory Hooks](/docs/hooks/memory-hooks). To build your own hook, see [Writing Hooks](/docs/hooks/writing-hooks).
</Callout>
