---
title: "Hook Architecture"
description: "How OrchestKit's hook registration system works: bundles, runners, execution modes, and the stop pipeline."
canonical: "https://orchestkit.dev/docs/hooks/architecture"
---

# Hook Architecture

How OrchestKit's hook registration system works: bundles, runners, execution modes, and the stop pipeline.

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

This page is for plugin developers who want to understand how the hook system works under the hood. If you are looking for what fires when, start with the [Overview](/docs/hooks/overview).

## The Bundle System

OrchestKit compiles its hooks into **11 event-specific bundles** using esbuild (`hooks.json` registers **151** hook entries across events: 149 routed through `run-hook.mjs`, 1 through `stop-uncommitted-check.mjs`, and 1 through `telemetry-sync.mjs`). When Claude Code fires a hook, only the bundle for that event type is loaded, not the entire codebase.

```
hooks.json entry
    |  "command": "node", "args": [".../hooks/bin/run-hook.mjs", "pretool/bash/sync-bash-dispatcher"]
    v
run-hook.mjs parses prefix "pretool"
    |
    v
bundleMap["pretool"] -> "pretool.mjs" (48 KB)
    |
    v
dynamic import("../dist/pretool.mjs")
    |
    v
hooks["pretool/bash/sync-bash-dispatcher"](input) -> HookResult
```

### Bundle Map

The `run-hook.mjs` CLI runner maps hook name prefixes to bundles:

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

Note that `subagent-start` and `subagent-stop` share the `subagent.mjs` bundle. Similarly, `teammate-idle` and `task-completed` hooks are bundled into `lifecycle.mjs`.

### Bundle Inventory

| Bundle | Size | Hook Count | Events | Key Contents |
|--------|------|------------|--------|--------------|
| `permission.mjs` | 8 KB | 3 | PermissionRequest | auto-approve-safe-bash, auto-approve-project-writes, learning-tracker |
| `pretool.mjs` | 48 KB | 33 | PreToolUse | sync-bash-dispatcher, sync-write-edit-dispatcher, sync-task-dispatcher, network-egress-guard |
| `posttool.mjs` | 58 KB | 23 | PostToolUse, PostToolUseFailure | metrics-dispatcher, tool-dispatcher, commit-nudge |
| `prompt.mjs` | 57 KB | 13 | UserPromptSubmit | unified-dispatcher (9 consolidated hooks), profile-injector |
| `lifecycle.mjs` | 31 KB | 17 | SessionStart, SessionEnd, PreCompact, TeammateIdle, TaskCompleted | context-loader, metrics-summary, progress-reporter |
| `stop.mjs` | 33 KB | 12 | Stop | handoff-writer, session-summary, task-completion-check, security-scan-aggregator, ledger-cleanup, goal-tracker |
| `subagent.mjs` | 56 KB | 18 | SubagentStart, SubagentStop | context-stager, output-validator, retry-handler |
| `notification.mjs` | 5 KB | 3 | Notification | desktop, sound, message-display-observer |
| `setup.mjs` | 24 KB | 6 | Setup | first-run-setup, monorepo-detector, setup-repair |
| `skill.mjs` | 52 KB | 22 | Skill operations, Stop | coverage-check, test-runner, redact-secrets |
| `hooks.mjs` | 324 KB | all | CLI tools only | Unified bundle, never loaded at runtime |

**Result:** A typical hook invocation loads 5--58 KB instead of 324 KB. That is an **89% per-load reduction**.

### Entry Points

Each bundle has a corresponding entry point at `src/hooks/src/entries/<bundle>.ts`. The entry point imports all hooks for that event type and exports a `hooks` registry:

```typescript
// src/entries/pretool.ts (simplified)
import { syncBashDispatcher } from '../pretool/bash/sync-bash-dispatcher.js';
import { syncTaskDispatcher } from '../pretool/task/sync-task-dispatcher.js';
// ... 31 more imports

export const hooks: Record<string, HookFn> = {
  'pretool/bash/sync-bash-dispatcher': syncBashDispatcher,
  'pretool/task/sync-task-dispatcher': syncTaskDispatcher,
  // ... all hooks for this event
};
```

esbuild tree-shakes each entry point into a self-contained `.mjs` file with zero external dependencies.

## Execution Modes

`src/hooks/bin/` ships two primary hook runners invoked by `hooks.json` (`run-hook.mjs` for 149 entries and `stop-uncommitted-check.mjs` for 1 entry, plus `telemetry-sync.mjs` for 1 SessionEnd entry). Rather than spawning custom detached wrapper scripts, OrchestKit uses Claude Code's native `async` and `asyncRewake` flags in `hooks.json` alongside `run-hook.mjs`.

<Tabs items={["Blocking", "Async", "Async with Rewake"]}>
<Tab value="Blocking">

### Blocking (`run-hook.mjs` / `stop-uncommitted-check.mjs`)

The synchronous mode (41 entries in `hooks.json`, where `async` is omitted). Claude Code pipes the event payload to stdin, waits for stdout, and acts on the result before proceeding.

```
Claude Code                          run-hook.mjs
    |                                     |
    |--- stdin: HookInput JSON ---------> |
    |                                     | parse prefix -> load bundle
    |                                     | call hookFn(input)
    |                                     |
    | <-- stdout: HookResult JSON ------- |
    |                                     |
    | act on result (allow/block/inject)  |
```

**Used by:** Security/safety gates in `PreToolUse`, synchronous `PermissionRequest` hooks, `UserPromptSubmit` context injectors, and `stop-uncommitted-check.mjs` on `Stop`.

**Can block operations:** Yes. Returning `{ continue: false }` stops the tool from executing.

**Can inject context:** Yes. Returning `additionalContext` in `hookSpecificOutput` adds guidance for Claude.

</Tab>
<Tab value="Async">

### Async (`run-hook.mjs` with `"async": true`)

Registered in `hooks.json` with `"async": true` (109 of the 151 entries). Claude Code invokes `node ${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs <hook-name>` asynchronously without blocking the active turn or tool call.

```json
{
  "type": "command",
  "command": "node",
  "async": true,
  "timeout": 10,
  "args": [
    "${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs",
    "posttool/commit-nudge"
  ]
}
```

**Used by:** Analytics, audit logging, session metrics, notification dispatchers, lifecycle trackers, and 11 of the 12 `Stop` hooks.

**Can block operations:** No. Runs non-blocking alongside the session.

</Tab>
<Tab value="Async with Rewake">

### Async with Rewake (`"async": true`, `"asyncRewake": true`, `"--rewake"`)

Used when an asynchronous validation hook should re-wake Claude Code if a check fails. The `hooks.json` entry sets both `"async": true` and `"asyncRewake": true` and passes `"--rewake"` to `run-hook.mjs`.

```json
{
  "type": "command",
  "command": "node",
  "async": true,
  "timeout": 10,
  "args": [
    "${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs",
    "skill/coverage-threshold-gate",
    "--rewake"
  ],
  "asyncRewake": true
}
```

**Used by:** Stop-time skill validation gates (`skill/coverage-threshold-gate` and `skill/cross-instance-test-validator`) and the `PostToolUse` hook `posttool/write/stale-import-detector`.

</Tab>
</Tabs>

## The Stop Pipeline

The `Stop` event in `hooks.json` registers **12 hooks**: 1 synchronous check (`stop-uncommitted-check.mjs`) and 11 asynchronous `run-hook.mjs` entries (`"async": true`).

<Steps>
<Step>
### Claude finishes responding (`Stop`)

Claude Code fires the `Stop` event once per turn when Claude finishes responding (session termination is a separate `SessionEnd` event).
</Step>

<Step>
### stop-uncommitted-check.mjs runs synchronously

`node ${CLAUDE_PLUGIN_ROOT}/hooks/bin/stop-uncommitted-check.mjs` runs as a blocking hook (`"statusMessage": "Checking uncommitted changes..."`) to check for uncommitted git changes and emit a `systemMessage` warning at the end of the turn if any exist.
</Step>

<Step>
### 11 async Stop hooks run via run-hook.mjs

In parallel, Claude Code invokes 11 `"async": true` hooks through `run-hook.mjs`:

- **Stop bundle (6):** `stop/handoff-writer`, `stop/session-summary`, `stop/task-completion-check`, `stop/security-scan-aggregator`, `stop/ledger-cleanup`, `stop/goal-tracker`
- **Skill bundle (4):** `skill/coverage-check`, `skill/evidence-collector`, `skill/coverage-threshold-gate` (`--rewake`), `skill/cross-instance-test-validator` (`--rewake`)
- **Lifecycle bundle (1):** `lifecycle/webhook-forwarder`
</Step>
</Steps>

## Scope Types

Hooks are registered at three levels. Scope determines which sessions a hook fires in.

<Tabs items={["Global (151)", "Agent-Scoped (0)", "Skill-Scoped (12)"]}>
<Tab value="Global (151)">

### Global Hooks

Defined in `hooks.json` at the top level. Fire on every matching event in every session.

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

Global hooks cover the core safety layer (the synchronous Bash, Write/Edit and Task dispatchers), analytics (audit logger, session metrics), and lifecycle management (context loader, cleanup).

</Tab>
<Tab value="Agent-Scoped (0)">

### Agent-Scoped Hooks

Defined in agent `.md` files under the `hooks:` frontmatter key. Fire only when that agent is active (spawned as a subagent via the Task tool).

```yaml
---
name: security-auditor
hooks:
  PostToolUse:
    - matcher: "Bash"
      command: "${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs agent/security-command-audit"
---
```

Agent-scoped hooks implement agent-specific safety constraints. For example:

| Agent | Hook | Purpose |
|-------|------|---------|
| `security-auditor` | `agent/security-command-audit` | Audit every bash command for security implications |
| `deployment-manager` | `agent/deployment-safety-check` | Gate deployments with pre-flight checks |
| `ci-cd-engineer` | `agent/ci-safety-check` | Prevent CI config changes without review |
| `database-engineer` | `agent/migration-safety-check` | Validate migration scripts before execution |

No agent ships an agent-scoped hook today: #3461 removed all of them from agent frontmatter. The table above shows the pattern, not live registrations.

</Tab>
<Tab value="Skill-Scoped (12)">

### Skill-Scoped Hooks

Defined in a SKILL.md file's frontmatter. Fire only when that skill is active. Currently, one skill-scoped hook exists: `skill/redact-secrets`, which is registered in hooks.json under `PostToolUse > Bash` and `PostToolUse > Write|Edit` and runs after every Bash command and file write to warn about leaked secrets in the output.

Skill-scoped hooks are the narrowest scope: they activate only when the associated skill is loaded into the session.

</Tab>
</Tabs>

## Hook I/O Contract

Every hook follows the same JSON-in, JSON-out contract over stdin/stdout.

### Input (stdin)

Claude Code pipes a JSON payload to the hook's stdin:

```typescript
interface HookInput {
  hook_event: string;        // "PreToolUse", "PostToolUse", "PermissionRequest", ...
  tool_name: string;         // "Bash", "Write", "Read", "Edit", "Skill", ...
  session_id: string;        // Unique session identifier (guaranteed since CC 2.1.9)
  tool_input: {              // Tool-specific parameters
    command?: string;        //   Bash: the command string
    file_path?: string;      //   Write/Edit/Read: target file
    content?: string;        //   Write: file content
    old_string?: string;     //   Edit: string to replace
    new_string?: string;     //   Edit: replacement string
  };
  tool_output?: unknown;     // PostToolUse only: the tool's result
  tool_error?: string;       // If the tool errored
  exit_code?: number;        // Bash exit code
  prompt?: string;           // UserPromptSubmit only: the user's message
  project_dir?: string;      // Project root directory
  subagent_type?: string;    // SubagentStart/Stop: which agent type
  agent_output?: string;     // SubagentStop: the agent's output
}
```

`run-hook.mjs` normalizes the input for backward compatibility (handling both `tool_input` and legacy `toolInput` field names) and caps stdin at 512 KB to prevent OOM from large payloads (e.g., base64-encoded image pastes).

### Output (stdout)

The hook writes a single JSON object to stdout:

<Tabs items={["Allow (silent)", "Block", "Inject Context", "Allow Permission"]}>
<Tab value="Allow (silent)">

```json
{
  "continue": true,
  "suppressOutput": true
}
```

The most common response. The operation proceeds and nothing is shown to the user.

</Tab>
<Tab value="Block">

```json
{
  "continue": false,
  "stopReason": "Direct commits to 'main' branch are not allowed.\n\nFix: git checkout -b feature/my-feature"
}
```

The tool invocation is cancelled. The `stopReason` is shown to Claude as context for why the operation was blocked.

</Tab>
<Tab value="Inject Context">

```json
{
  "continue": true,
  "hookSpecificOutput": {
    "additionalContext": "Consider using cursor-based pagination for large datasets.",
    "hookEventName": "PreToolUse"
  }
}
```

The operation proceeds, but Claude receives the `additionalContext` as additional guidance. Requires CC 2.1.9+.

</Tab>
<Tab value="Allow Permission">

```json
{
  "continue": true,
  "suppressOutput": true,
  "hookSpecificOutput": {
    "permissionDecision": "allow",
    "permissionDecisionReason": "Safe read-only operation"
  }
}
```

For PermissionRequest events only. Auto-approves the tool use without prompting the user.

</Tab>
</Tabs>

### Output Builders

The `lib/common.ts` module provides type-safe builder functions so hooks never construct raw JSON:

```typescript
import {
  outputSilentSuccess,      // { continue: true, suppressOutput: true }
  outputBlock,               // { continue: false, stopReason: "..." }
  outputWithContext,         // inject additionalContext (PostToolUse)
  outputAllowWithContext,    // allow + inject context (PreToolUse)
  outputPromptContext,       // inject context (UserPromptSubmit)
  outputSilentAllow,         // silent permission allow
  outputDeny,                // deny permission with reason
  outputError,               // show error message
  outputWarning,             // show warning message
} from '../lib/common.js';
```

## Native HTTP Hooks (CC 2.1.69+)

Claude Code also supports `"type": "http"` hooks beside `"type": "command"` hooks that spawn a shell process. OrchestKit ships none as http today (every entry in `hooks.json` is `"type": "command"`); the JSON below shows the pattern. These hooks POST the hook input as JSON directly to a URL, bypassing the Node.js process spawn entirely.

```json
{
  "type": "http",
  "url": "http://localhost:${ORCHESTKIT_PORT}/hooks/analytics/session-event",
  "statusMessage": "Syncing analytics..."
}
```

HTTP hooks are used for analytics, webhook integrations, and external service notifications where the overhead of spawning a Node.js process is unnecessary. They follow the same input/output contract: the URL receives a JSON POST body matching `HookInput` and returns a JSON response matching `HookResult`.

## The once:true Pattern (CC 2.1.69+)

Hooks registered with `"once": true` auto-remove after their first successful fire in a session. `hooks.json` registers no `once` hook today, so this example is a shape, not a shipped hook.

```json
{
  "type": "command",
  "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs prompt/your-init-hook",
  "once": true
}
```

This pattern is ideal for one-time initialization: context injection, environment detection, or consent checks that only need to run once per session.

## statusMessage for Spinner UX (CC 2.1.69+)

Hooks can declare a `"statusMessage"` string in their `hooks.json` registration. When present, Claude Code displays the message as a spinner label while the hook executes, giving the user feedback that work is happening.

```json
{
  "type": "command",
  "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/bin/run-hook.mjs lifecycle/session-context-loader",
  "statusMessage": "Loading session context..."
}
```

OrchestKit uses `statusMessage` on 15 hooks, primarily context loaders, PR enrichers, and setup hooks where execution takes more than a few hundred milliseconds. For fast hooks (under 50ms), omit `statusMessage` to avoid spinner flicker.

## Hook Overrides

Hooks can be disabled only at user scope by creating `~/.claude/hook-overrides.json` (a project `.claude/hook-overrides.json` is ignored; AF-12 / #4220):

```json
{
  "disabled": [
    "pretool/bash/license-compliance",
    "posttool/write/readme-sync"
  ]
}
```

`run-hook.mjs` reads this file from the user home before executing any hook. If the hook name appears in the `disabled` array, it returns silent success without loading the bundle. Security hooks in `SECURITY_HOOKS` cannot be disabled this way.

## Execution Tracking

Every hook invocation is tracked for profiling (Issue #245). After a hook completes, `run-hook.mjs` writes a timing event to two locations:

1. **Session events**: `.claude/memory/sessions/{session_id}/events.jsonl`
2. **Cross-project analytics**: `~/.claude/analytics/hook-timing.jsonl`

Each event records the hook name, duration in milliseconds, success/failure, and a hashed project identifier. Session IDs are validated against `/^[a-zA-Z0-9_-]{1,128}$/` to prevent path traversal (SEC-001).

<Callout type="info">
To learn about individual hook categories, 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>
