# Hooks

Run deterministic shell commands at Droid lifecycle events for validation, policy, context injection, and automation.

Hooks are shell commands that run at defined points in a Droid
session. Use them for deterministic behavior that should happen every time, such as
validating tool calls, formatting changed files, injecting local context, logging activity,
or enforcing team policy.

<Warning>
  Hooks run automatically with your local environment and credentials. Review every hook command before registering it, use absolute script paths, and test in a safe environment first.
</Warning>

## Configuration

Hooks live alongside settings at each scope:

| Scope | File | Notes |
| :---- | :--- | :---- |
| User | `~/.factory/hooks.json` | Applies across your projects. |
| Project | `.factory/hooks.json` | Commit to share with teammates. |
| Enterprise | Org-managed settings | Loaded from Enterprise Controls and managed settings. |
| Legacy | `.factory/hooks/hooks.json` | Still loads. The next save writes `.factory/hooks.json` and archives the old file as `hooks/hooks.migrated.json`. |

If `hooks.json` is absent, Droid also reads hook declarations from the `hooks` key in the matching `settings.json`.

<Note>
  Always use absolute paths in hook commands. Hooks execute from Droid's current working directory, which can differ from your repository root. Use `"$FACTORY_PROJECT_DIR"/path/to/script.sh` for project scripts or a full path such as `/usr/local/bin/script.sh` for global scripts.
</Note>

### Structure

Standalone `hooks.json` files are keyed directly by event name. Each event contains matcher groups, and each group contains one or more shell commands.

```json title="~/.factory/hooks.json"
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "commandRegex": "^git ",
      "hooks": [
        {
          "type": "command",
          "command": "/usr/local/bin/audit-git-command.sh",
          "timeout": 30
        }
      ]
    }
  ]
}
```

When you declare hooks inside `settings.json` instead, wrap the same event map in a
top-level `hooks` key:

```json title="~/.factory/settings.json"
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Execute",
        "commandRegex": "^git ",
        "hooks": [
          {
            "type": "command",
            "command": "/usr/local/bin/audit-git-command.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
```

| Field | Required | Source-validated behavior |
| :---- | :------- | :------------------------ |
| `matcher` | No | Empty, omitted, or `*` matches everything. Exact strings match one tool or lifecycle matcher. Regex patterns are supported and are case-sensitive. |
| `commandRegex` | No | Additional regex filter for Execute commands. It matches the actual shell command string when Droid has one. Invalid regex values are skipped. |
| `hooks` | Yes | Array of hook commands for the matcher group. |
| `type` | Yes | Currently only `"command"` is supported. |
| `command` | Yes | Shell command executed with JSON hook input on stdin. |
| `timeout` | No | Per-command timeout in seconds. Defaults to `60`. |
| `preserveRiskLevel` | No | `PreToolUse` only. When this hook rewrites an `Execute` command through `updatedInput`, keep the model's `riskLevel`; with several hooks, every hook that returns `updatedInput` must set it. See [PreToolUse control](#pretooluse-control). |
| `onFailure` | No | `"continue"` (default) or `"block"`. With `"block"`, a failure of this hook blocks the event the way exit `2` would, except on `Stop`, `SubagentStop`, and events that cannot block. See [Block when a hook fails](#block-when-a-hook-fails). |

Common tool matchers include `Execute`, `Read`, `Edit`, `Create`, `ApplyPatch`, `LS`, `Glob`, `Grep`, `Task`, `FetchUrl`, and `WebSearch`. MCP tools use the `mcp__<server>__<tool>` naming pattern, so `mcp__.*` matches all MCP tools.

## Quickstart

This example logs every shell command Droid runs.

<Steps>
  <Step title="Open the hooks manager">
    In Droid, run:

    ```text
    /hooks
    ```

    The manager opens with **User**, **Project**, **Plugins**, and **Effective** tabs.
  </Step>
  <Step title="Choose a scope">
    Select **User** to save the hook in `~/.factory/hooks.json`, or **Project** to save it
    in `.factory/hooks.json`. The **Plugins** and **Effective** tabs are read-only.
  </Step>
  <Step title="Add the hook">
    Select **Add hook command**, choose the `PreToolUse` event, and set the matcher to
    `Execute`. Enter this command:

    ```bash
    jq -r '.tool_input.command' >> ~/.factory/bash-command-log.txt
    ```
  </Step>
  <Step title="Save and verify">
    Save the hook, ask Droid to run a simple command, then inspect the log:

    ```bash
    cat ~/.factory/bash-command-log.txt
    ```
  </Step>
</Steps>

The saved configuration looks like this:

```json title="~/.factory/hooks.json"
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "hooks": [
        {
          "type": "command",
          "command": "jq -r '.tool_input.command' >> ~/.factory/bash-command-log.txt"
        }
      ]
    }
  ]
}
```

If you chose the **Project** tab, the same unwrapped structure is saved to
`.factory/hooks.json`.

<LabeledDivider label='Event reference' />

## Hook events

| Event | Runs when | Matcher or key fields | Common use |
| :---- | :-------- | :-------------------- | :--------- |
| `PreToolUse` | After Droid builds tool parameters and before the tool runs. | `tool_name`, `tool_input`; matcher usually targets a tool such as `Execute` or `Edit`. | Block risky operations, approve safe tools, rewrite tool input. |
| `PostToolUse` | Immediately after a tool completes. | `tool_name`, `tool_input`, `tool_response`; same tool matchers as `PreToolUse`. | Format files, run validation, add feedback after an edit. |
| `UserPromptSubmit` | Before Droid processes a submitted user prompt. | `prompt`, `has_images`. | Validate prompts or inject extra context. |
| `Notification` | When Droid sends a notification. | `message`, `notification_type` (`permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`). | Desktop alerts or compliance logging. |
| `Stop` | When the main Droid is about to finish responding. | `stop_hook_active`, `tool_execution_count`, `elapsed_time`. | Require final checks or continue with follow-up instructions. |
| `SubagentStop` | When a Task-launched sub-droid finishes. | `task_name`, `task_result`, `task_error`, `stop_hook_active`. | Validate or log subagent output. |
| `PreCompact` | Before manual or automatic compaction. | `trigger` (`manual` or `auto`), `custom_instructions`, `message_count`, `estimated_tokens`. | Save context or add compaction guidance. |
| `SessionStart` | When Droid starts, resumes, clears, or starts after compaction. | `source` (`startup`, `resume`, `clear`, `compact`), plus optional prior session IDs. | Load local context at session start. |
| `SessionEnd` | When a Droid session ends. | `reason` (`clear`, `logout`, `prompt_input_exit`, `other`), `session_duration_ms`, `message_count`. | Cleanup, audit logs, session summaries. |

### Notification types

| Type | Sent when |
| :--- | :-------- |
| `permission_prompt` | Droid is waiting for permission to run an action. |
| `idle_prompt` | Droid is waiting for user input, including immediately after the user cancels a turn. |
| `auth_success` | An authentication flow succeeds. |
| `elicitation_dialog` | Droid needs structured input in an elicitation dialog. |

Cancellation emits the informational `Notification` hook instead of `Stop`, so a hook
cannot override the user's decision to stop the turn.

## Hook input

Every hook receives JSON on stdin. Common fields are also exposed as environment variables when their values are strings, booleans, or numbers.

```typescript
{
  session_id: string
  transcript_path: string
  cwd: string
  permission_mode: "off" | "spec" | "auto-low" | "auto-medium" | "auto-high"
  hook_event_name: string
  message_id?: string
}
```

Tool hooks add tool-specific fields:

```json
{
  "session_id": "abc123",
  "transcript_path": "/Users/.../.factory/projects/.../session.jsonl",
  "cwd": "/Users/me/project",
  "permission_mode": "off",
  "hook_event_name": "PreToolUse",
  "tool_name": "Create",
  "tool_input": {
    "file_path": "/Users/me/project/file.txt",
    "content": "file content"
  }
}
```

`PostToolUse` includes `tool_response` as well. The exact shape of `tool_input` and `tool_response` depends on the tool.

## Hook output

Hooks communicate through exit codes, stderr, stdout, and optional JSON emitted on stdout.
Exit code `2` always blocks where the event can block. On any other exit code, valid JSON on
stdout decides the result. Output that looks like JSON but cannot be applied is a non-blocking
error on any exit code but `2`. With plain-text stdout, exit `0` is a success and any code other
than `0` or `2` is a non-blocking error. A hook that sets `onFailure: "block"` on `PreToolUse`, `PostToolUse`,
`UserPromptSubmit`, or `PreCompact` blocks instead of each of those non-blocking errors, and on
a non-zero exit with valid JSON as well (see [Block when a hook fails](#block-when-a-hook-fails)).

| Output | Effect |
| :----- | :----- |
| Exit code `0` | Success, unless stdout looks like JSON that cannot be applied (see [How Droid reads stdout](#how-droid-reads-stdout)). JSON on stdout applies its fields. Plain stdout is added as context for `UserPromptSubmit` and `SessionStart`; for other events, it is visible in transcript views. |
| Exit code `2` | Blocks, whatever stdout contains. The reason is stderr, unless the hook's JSON also blocks and gives its own reason. `PreToolUse` blocks the tool call, `PostToolUse` and `Stop` feed the reason back to Droid, `UserPromptSubmit` blocks the prompt, and a manual `PreCompact` is blocked. `SubagentStop` and automatic `PreCompact` cannot be blocked, so Droid shows the reason to the user. On `Notification`, `SessionStart`, and `SessionEnd`, exit `2` is a non-blocking error and none of the hook's JSON applies, `continue: false` included: Droid shows stderr; if stderr is empty, the plain text the hook printed to stdout; if there is neither, `Hook exited with code 2`. |
| Any other non-zero exit | If stdout is valid JSON, its fields apply exactly as on exit `0` and the hook counts as succeeded, unless the hook sets `onFailure: "block"` on `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, or `PreCompact` (see [Block when a hook fails](#block-when-a-hook-fails)). With plain-text or empty stdout, the hook is a non-blocking error: Droid shows the user stderr; if stderr is empty, the plain text the hook printed to stdout; if there is neither, `Hook exited with code N`. Droid then continues. Plain stdout is not added as context. |
| Timeout | Non-blocking error, shown as `Hook timed out after Ns`, unless the hook sets `onFailure: "block"` on `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, or `PreCompact`. Anything the hook printed before the timeout is discarded, so a decision it printed does not count. |
| JSON `continue: false` | Droid shows `stopReason` to the user. What stops, if anything, depends on the event: see [Control by event](#control-by-event). In `droid exec`, a stop from a hook on a tool call the model made directly ends the turn as an error whose message is the `stopReason`. |
| JSON `systemMessage` | Shown to the user as a hook warning. |
| JSON `suppressOutput: true` | Hides successful hook output from the main chat view while preserving it in the detailed transcript. |

### How Droid reads stdout

Droid treats stdout as JSON only when the trimmed text starts with `{`, ends with `}`, and is
either the empty object `{}` or an object that sets at least one output field: `continue`,
`stopReason`, `suppressOutput`, `systemMessage`, `decision`, `reason`, or `hookSpecificOutput`.
A leading byte-order mark is trimmed like whitespace. `{}` is valid JSON output that changes
nothing.

Plain text is text that does not start with `{` and end with `}`, a single nonempty JSON object
that sets none of those fields, such as the log line `{"message": "done"}`, or several JSON
objects on separate lines, none of which sets one of those fields (blank lines between them
are ignored). Text in braces that is neither JSON output nor plain text by these rules fails
the hook, as described next.

Output that looks like JSON but cannot be applied makes the hook fail, even on exit `0`, and
none of its fields apply: the failure is a non-blocking error, or a block when the hook sets
`onFailure: "block"` on an event where that blocks. Droid shows the parse or validation message
to the user and on the hook's row. This covers:

- Text that starts with `{` and ends with `}` but does not parse, unless each of its lines is a
  JSON object that sets no output field, which is plain text as above.
- A field with the wrong type or an unknown value, such as `"permissionDecision": "defer"`.
- `hookSpecificOutput.hookEventName` naming a different event from the one that ran.

A field set to `null` counts as absent, so `"reason": null` next to a deny still denies.

<Warning>
  By default, invalid JSON fails open: a policy hook whose output fails validation does not block the tool call. To make a policy hook fail closed, set `onFailure: "block"` on it (see [Block when a hook fails](#block-when-a-hook-fails)), or exit `2` and write the reason to stderr.
</Warning>

### Block when a hook fails

Set `onFailure: "block"` on a hook command to make its failures block instead of being
non-blocking errors. A hook fails when:

- It cannot start.
- It times out.
- It exits with a code other than `0` or `2` and its stdout is plain text or empty. On an event
  where `"block"` applies, any stdout fails it: valid JSON that allows the action, or `{}`, still
  counts as a failure. A hook that returns a JSON decision exits `0`.
- Its stdout looks like JSON but cannot be applied (see [How Droid reads stdout](#how-droid-reads-stdout)).

A hook cancelled because you stopped Droid has not failed.

A failure under `"block"` acts as exit `2` on that event: `PreToolUse` denies the tool call,
`PostToolUse` feeds the reason back to Droid, `UserPromptSubmit` blocks the prompt, and a
manual `PreCompact` is blocked. The reason names the event and the failure, for example
`PreToolUse hook failed (onFailure: "block"): <error>`, or after a timeout
`PreToolUse hook timed out after 60s (onFailure: "block")`.
`onFailure` has no effect on `Stop`, where a block would keep Droid running, on `SubagentStop`,
or on events that cannot block; there a failure stays a non-blocking error.

```json title=".factory/hooks.json"
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "hooks": [
        {
          "type": "command",
          "command": "\"$FACTORY_PROJECT_DIR\"/.factory/hooks/check-command.sh",
          "onFailure": "block"
        }
      ]
    }
  ]
}
```

A value other than `"continue"` or `"block"` is reported when Droid loads the settings (in
`/diagnostics`, in the footer's configuration issue count, and on `droid exec`'s stderr), and
the hook runs with `"continue"`.

### Multiple hooks

When several hooks match one event, they run in parallel. Droid reads each hook's result as
described above, then combines the results in configuration order:

- The strongest result wins: `continue: false`, then a block or deny, then `ask`, then
  `allow`, then no decision. One deny blocks a tool call even when another hook allowed it.
- For a block or a stop, the reason is every distinct reason from the hooks that reached that
  result, one per line.
- Every hook's `additionalContext`, `systemMessage`, and error is kept.
- For `PreToolUse`, unless the batch blocks or stops, every hook's `updatedInput` applies in
  configuration order, whatever the decision. When two hooks set the same field, the later
  one wins. When the combined `updatedInput` changes an `Execute` command, the model's
  `riskLevel` is kept only when every hook that returned `updatedInput` sets `preserveRiskLevel`.

### PreToolUse control

Use `hookSpecificOutput.permissionDecision` for tool-call control:

```json
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "Documentation reads are safe",
    "updatedInput": {
      "file_path": "/Users/me/project/README.md"
    }
  }
}
```

| Decision | Effect |
| :------- | :----- |
| `allow` | Allows the tool call and can bypass the normal permission prompt. |
| `deny` | Blocks the tool call and sends the reason to Droid. Without `permissionDecisionReason` or `reason`, the reason is `Tool execution blocked by hook`. |
| `ask` | Does not allow the call: normal permissions apply, at every autonomy level, so a call they would run without asking runs without a prompt. One `ask` overrides another hook's `allow`. A hook that wants the call stopped returns `deny` with a reason. |

Droid also reads the older top-level `decision` field: `decision: "approve"` acts like
`allow`, and `decision: "block"` acts like `deny`. When both are set, `permissionDecision`
wins.

`updatedInput` sets the tool parameters it names before the tool runs; parameters it leaves
out keep the values Droid chose. A rewrite that makes the input invalid denies the tool call.
When a hook changes an `Execute` command, Droid drops the model's `riskLevel`, unless the hook
command sets `preserveRiskLevel: true`. Where permission checking depends on the risk level, a
command without one counts as high risk. With several
hooks, every hook that returned `updatedInput` must set it, as above. Set it only
when the rewrite does not change what the command does, such as prepending environment setup.

### Control by event

| Event | Effect |
| :---- | :----- |
| `PreToolUse` | `continue: false` ends the turn before the tool runs. For a tool call made from inside the `Script` tool, it fails that one call instead, and the script can catch the error. For permission decisions and `updatedInput`, see [PreToolUse control](#pretooluse-control). |
| `PostToolUse` | `decision: "block"` sends `reason` back to Droid after the tool ran. Without a reason, Droid receives `PostToolUse hook reported an issue`. `hookSpecificOutput.additionalContext` adds more context. `continue: false` ends the turn and keeps the tool's result. |
| `UserPromptSubmit` | `decision: "block"` or `continue: false` prevents the prompt from being processed: Droid shows `Hook blocked submission: <reason>` and hands the prompt back unsent. `additionalContext` is appended when not blocked. A hook cannot rewrite the prompt: `hookSpecificOutput.updatedInput` blocks it with `UserPromptSubmit hooks cannot rewrite the prompt; return decision: "block" instead`. |
| `Notification` | Results are informational: `continue: false` stops nothing. |
| `Stop` | `decision: "block"` prevents stopping, and `reason` becomes Droid's next instruction. Without a reason, Droid continues with `Stop hook requested continuation`. When another hook returns `continue: false`, the turn stops; a `Stop` hook that exits `2` continues the turn even if its own JSON sets `continue: false`. |
| `SubagentStop` | Neither a block nor `continue: false` keeps the subagent running or changes its result. Droid shows the reason to the user as a hook warning. |
| `PreCompact` | `decision: "block"`, `continue: false`, or exit `2` blocks a manual compaction. Automatic compaction always runs. Droid shows the reason to the user. |
| `SessionStart` | `hookSpecificOutput.additionalContext` is appended to the new session context. `continue: false` stops nothing. |
| `SessionEnd` | Cannot block session termination, and `continue: false` stops nothing. Use it for cleanup and logging. |

<LabeledDivider label='Plugins and policy' />

## Plugin hooks

Installed plugins can provide hooks. Droid loads hooks from `hooks/hooks.json` in the plugin root and merges them with user, project, and managed hooks when the plugin is enabled.

```text
my-plugin/
├── .factory-plugin/
│   └── plugin.json
├── hooks/
│   ├── hooks.json
│   └── format.sh
└── ...
```

```json
{
  "PostToolUse": [
    {
      "matcher": "Create|Edit|ApplyPatch",
      "hooks": [
        {
          "type": "command",
          "command": "${DROID_PLUGIN_ROOT}/hooks/format.sh",
          "timeout": 30
        }
      ]
    }
  ]
}
```

Plugin hook commands may use `${DROID_PLUGIN_ROOT}`, `$DROID_PLUGIN_ROOT`, `${CLAUDE_PLUGIN_ROOT}`, or `$CLAUDE_PLUGIN_ROOT`. Droid expands those variables to the installed plugin cache path when loading plugin hooks. Outside plugins, use `$FACTORY_PROJECT_DIR` or an absolute path.

## Org-managed hooks

Organizations can define authoritative hooks in Enterprise Controls through managed settings. Org hooks always load unless hooks are globally disabled, and lower levels cannot remove them.

| Field | Description |
| :---- | :---------- |
| `hooks` | Org-defined hook settings keyed by event name, using the same structure as `hooks.json`. |
| `allowManagedHooksOnly` | When `true`, only org-managed hooks and hooks from org-enabled plugins load. User and project hooks are ignored. |

```json
{
  "allowManagedHooksOnly": true,
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Execute",
        "hooks": [
          {
            "type": "command",
            "command": "/usr/local/bin/audit-command.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
```

See [Enterprise Controls & Managed Settings](/enterprise/hierarchical-settings-and-org-control) for how org, project, folder, and user settings merge.

<LabeledDivider label='In practice' />

## Examples

### Format changed TypeScript files

```json
{
  "PostToolUse": [
    {
      "matcher": "Create|Edit|ApplyPatch",
      "hooks": [
        {
          "type": "command",
          "command": "python3 \"$FACTORY_PROJECT_DIR\"/.factory/hooks/format_changed_file.py"
        }
      ]
    }
  ]
}
```

### Block edits to sensitive files

```json
{
  "PreToolUse": [
    {
      "matcher": "Create|Edit|ApplyPatch",
      "hooks": [
        {
          "type": "command",
          "command": "python3 \"$FACTORY_PROJECT_DIR\"/.factory/hooks/protect_paths.py"
        }
      ]
    }
  ]
}
```

A blocking script exits `2` and writes the reason to stderr.

### Add context before each prompt

```json
{
  "UserPromptSubmit": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "python3 \"$FACTORY_PROJECT_DIR\"/.factory/hooks/add_ticket_context.py"
        }
      ]
    }
  ]
}
```

## Security considerations

- Treat hook input as untrusted JSON. Validate and sanitize paths, prompts, and command strings.
- Quote shell variables, for example `"$FACTORY_PROJECT_DIR"`, to avoid word splitting.
- Block path traversal and sensitive paths such as `.env`, `.git/`, credentials, and deployment secrets.
- Prefer small scripts checked into `.factory/hooks/` over long inline one-liners.
- Test hooks manually before enabling them for a team or organization.
- Remember that hooks inherit your local environment. Avoid commands that exfiltrate data or mutate systems unexpectedly.

Droid snapshots hooks at startup and warns when hooks are modified externally. Review changes in the `/hooks` UI before relying on them in the current session.

## Debugging

| Symptom | What to check |
| :------ | :------------ |
| Hook does not run | Confirm the event key, matcher casing, and that hooks are not disabled. Use `/hooks` to inspect the active configuration. |
| Hook runs for the wrong tool | Matchers are case-sensitive and can be regexes. Use exact names like `Execute`, or a narrow regex. |
| Script cannot be found | Use an absolute path or `"$FACTORY_PROJECT_DIR"/relative/path`. Do not rely on the shell's current directory. |
| JSON parsing fails | Remember that hook input arrives on stdin. Test with sample JSON before registering the command. |
| Hook output has no effect | Check the hook's row for `Hook output is not valid JSON` or `Hook JSON output failed validation`. See [How Droid reads stdout](#how-droid-reads-stdout). |
| Hook hangs | Set a shorter `timeout`, inspect external network or process calls, and test the script outside Droid. |

Run `droid --debug` to inspect hook matching and execution details.

<RelatedLinks>
  <RelatedLink href='/harness/subagents' title='Custom droids (subagents)'>
    Fire hooks on Task-launched subagent lifecycle events.
  </RelatedLink>
  <RelatedLink href='/autonomy-and-safety/auto-run' title='Autonomy Level'>
    Combine hooks with autonomy levels for layered safety controls.
  </RelatedLink>
</RelatedLinks>
