> For the complete documentation index, see [llms.txt](https://docs.codna.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.codna.ai/guides/hooks.md). Agents can also search and read this documentation through its [MCP server](https://docs.codna.ai/~gitbook/mcp).

# Hooks

Hooks — lifecycle scripts that observe, block or annotate an agent turn, in .codna/hooks.json or a Cursor .cursor/hooks.json, which events run, and what an unsupported event does.

A hook is a program Codna runs at a named moment in a turn: before a shell command, after a file edit, when a session starts. It reads one JSON object on **stdin**, decides, and answers one JSON object on **stdout**. It can observe, annotate, or **refuse** the action it guards.

Codna reads Cursor's `hooks.json` format, so a repository that already has `.cursor/hooks.json` works by copying it — no Codna-specific key is needed.

## Where the file lives

| Path                 | Runs from           | Precedence          |
| -------------------- | ------------------- | ------------------- |
| `.codna/hooks.json`  | the repository root | first (Codna's own) |
| `.cursor/hooks.json` | the repository root | second (migration)  |

Both are read. If both exist, **every matching hook from both runs** — the lists are merged, not overridden, which is Cursor's own rule. The order is `.codna` first, then `.cursor`, and it decides which hook's answer is consulted first when several answer for one call.

```json
{
  "version": 1,
  "hooks": {
    "beforeShellExecution": [
      { "command": ".codna/hooks/block-git-push.sh", "matcher": "git push" }
    ],
    "afterFileEdit": [
      { "command": ".codna/hooks/format.sh" }
    ]
  }
}
```

A `matcher` is a regular expression over a per-event value (the shell command text, the tool name, `Write`, …). An empty string or `"*"` matches everything. A hook whose matcher does not match is **skipped**, not failed.

## Which events run

These events fire. Everything else is either reported as unsupported or refused — see below.

| Event                  | When                                                                             | Can block | Matcher is tested against                                     |
| ---------------------- | -------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------- |
| `workspaceOpen`        | when the session binds its working directory (first turn, before `sessionStart`) | no        | the working directory                                         |
| `sessionStart`         | the first turn of a session                                                      | no        | —                                                             |
| `beforeSubmitPrompt`   | every turn, before the prompt is sent                                            | **yes**   | `UserPromptSubmit`                                            |
| `beforeReadFile`       | before a file is read (path), then before its content enters the conversation    | **yes**   | `Read`                                                        |
| `preToolUse`           | before any tool call                                                             | **yes**   | the tool name (`Shell`, `Read`, …)                            |
| `beforeMCPExecution`   | before an MCP tool runs                                                          | **yes**   | the tool's own name (`echo`)                                  |
| `afterMCPExecution`    | after an MCP tool answers                                                        | no        | the tool's own name                                           |
| `beforeShellExecution` | before a shell command                                                           | **yes**   | the command text                                              |
| `subagentStart`        | before a delegation's child agent runs                                           | no        | the teammate (`reviewer`, or a `team_*` call's `agentId`)     |
| `postToolUse`          | after a tool succeeds                                                            | no        | the tool name                                                 |
| `postToolUseFailure`   | after a tool fails                                                               | no        | the tool name                                                 |
| `afterShellExecution`  | after a shell command runs                                                       | no        | the command text                                              |
| `afterFileEdit`        | after an `editor`/`apply_patch` write                                            | no        | `Write`                                                       |
| `subagentStop`         | after a delegation's child agent ends, succeeded **or** failed                   | no        | the agent name                                                |
| `afterAgentThought`    | when the model's message carries a reasoning block                               | no        | —                                                             |
| `afterAgentResponse`   | when the model's message carries reply text                                      | no        | —                                                             |
| `preCompact`           | before context compaction                                                        | no        | the compaction reason (`auto_compaction`/`manual_compaction`) |
| `sessionEnd`           | when the session ends: deleted, evicted, stopped, or aborted                     | no        | the reason (`deleted`/`stopped`/`aborted`)                    |
| `stop`                 | when the turn ends                                                               | no        | `Stop`                                                        |
| `beforeTabFileRead`    | before an inline (Tab) completion asks the model, for one file                   | **yes**   | the **file path**                                             |
| `afterTabFileEdit`     | after the editor applied an accepted Tab completion                              | no        | `Write`                                                       |

Every event in this table fires. There is no longer a "recognized but cannot fire" category.

For a shell call, **both** `preToolUse` and `beforeShellExecution` fire. That is deliberate: a repository may scope one hook to the tool name and another to the command text, and collapsing them would make one of the two silently do nothing. `preToolUse` also fires for a file read and for an MCP call, beside their own events.

### `beforeReadFile` — the read gate

Fires inside the `read_files` executor. Payload: `file_path`, `content`, `attachments` (always `[]`). Output: `{ "permission": "allow" | "deny", "user_message": "…" }`.

**It is decided in two phases, and the first one is the gate.**

1. **Path, before any I/O.** The event fires with `file_path`, `content: ""` and **`content_available: false`** before the file is opened. A hook that refuses on path — an access-control rule, a `.env`/`secrets.*` deny list — refuses here, and **the file is never read**: nothing is opened, nothing is materialised, and no file bytes are written to the hook's stdin.
2. **Content, after the read and before the model.** If phase 1 allowed, the file is read and the same event fires again with the real `content` and `content_available: true`, so a secret-scanning hook still gets its look before the model does.

`content_available` is what makes phase 1 honest: an empty `content` alone cannot be told apart from an empty file, and a hook that scanned it would answer "no secret" about a file it was never shown. `content_length` is `null` before the read and the real length after it.

Both phases are the same event with the same fields, so a Cursor-written hook runs unmodified: a path-matching hook simply answers the same thing twice, and a content-scanning hook sees `content_available: false` in phase 1 and decides in phase 2. A read is therefore one subprocess launch when the path is denied, and two when it is allowed.

**What a deny prevents, exactly.** A deny on **path** means the read never happened. A deny on **content** cannot say that — its verdict is what needs the bytes, so the file was read before phase 2 asked. No ordering can ask "what is inside this file?" before opening it. Either way the content never enters the conversation, never reaches the model, and is not re-sent on every later request. If you need a guarantee that a file is never opened at all, deny it by path (or make it unreadable) rather than by its contents.

**What `content` carries, and why it is bounded.** A redaction hook has to *see* the file, so phase 2 sends the content. It is capped at **48 000 characters, the runtime's own per-read window**: the largest thing the model can receive from one read is the largest thing the hook is asked to judge, so nothing the model could see is withheld from the hook. Over that, `content_truncated: true` and the real `content_length` travel beside the (cut) content, so a hook that must scan a whole file can see it only saw a prefix and deny rather than allow. Nothing is cut, or withheld, without saying so.

**No redaction by rewriting.** Cursor's contract for this event is `allow`/`deny` only — there is **no field for returning edited content**. So an allowed read is returned byte-identically, and Codna does not invent a rewriting path a migrated hook could not use. To redact, deny the file (or deny the ones that matter) rather than expecting edited content back.

An image read is gated by path only, once: a base64 blob is neither size-bounded nor judgeable as text, and sending `content: ""` for a non-empty image would be a false claim.

### `beforeMCPExecution` / `afterMCPExecution` — the external-tool gate

Fires at the MCP provider's `callTool` — the one place an external tool actually runs. The server identity comes from the **validated configuration**, never the call, so a matcher on it matches what the operator wrote.

* `beforeMCPExecution` payload: `tool_name` (the tool's **own** name, e.g. `echo`), `tool_input` (a **JSON string**, as Cursor documents it), `mcp_server_name`, and then either `url` + `mcp_server_url` (HTTP/SSE) or `command` (the stdio launch line). Output: `{ "permission": "allow" | "deny" | "ask", "user_message", "agent_message" }`. `ask` defers to the normal approval gate, exactly as it does elsewhere.
* `afterMCPExecution` payload: the same fields plus `result_json` and `duration`. It has **no output fields** — it observes, and cannot change the result.

Because `tool_name` is the tool's own name, match the **pair** (`tool_name` + `mcp_server_name`) to scope a rule to one server. A hook that allows anything it does not recognise should treat a missing or unexpected `mcp_server_name` as a deny.

### `subagentStart` / `subagentStop` — a delegation's boundaries

Fires at the tool boundary for **every** delegation family this build has, and the matcher is the **teammate's name**:

| Tool                                       | `subagentStart` | `subagentStop` |
| ------------------------------------------ | --------------- | -------------- |
| `subagent_<name>` (a file-defined agent)   | yes             | yes            |
| `spawn_agent` (the builtin)                | yes             | yes            |
| `team_run_task` (run a task on a teammate) | yes             | yes            |
| `team_spawn_teammate` (create a teammate)  | yes             | **no**         |
| `team_shutdown_teammate` (end a teammate)  | **no**          | yes            |

`subagentStart` runs before the child agent executes; `subagentStop` runs after it ends, **on success and on failure**, with `status` of `completed` or `error`. A spawn does not report an end — the teammate is alive and idle, so releasing a lock on it would be wrong — and a shutdown does not report a start. `team_task`, `team_list_runs`, `team_status` and the outcome tools are bookkeeping and fire neither.

For a `team_*` call the payload's `subagent_name` is the call's `agentId`, **not** the tool name: the tool name is the operation, so a hook scoped to one teammate matching every run would be a false gate. `tool_name` still names the operation, so a hook can scope to "a teammate was created" (`team_spawn_teammate`) versus "a teammate ran a task" (`team_run_task`).

**The one limitation, stated.** `team_run_task` with `runMode: "async"` returns as soon as the run is **queued**, so its pair brackets the *dispatch*, not the later execution — the run ends after the tool call returned, inside the SDK's queue, where this engine has no seam. A hook that needs the run itself should watch `team_progress`. The default `sync` mode brackets the real run.

**Neither can block.** Cursor's `subagentStart` is documented as blockable, but this runtime's SDK invokes its own start callback after the child has been constructed and swallows any throw from it — so there is no seam at which a refusal could stop the delegation. Refusing a delegation is `preToolUse`'s job, and it fires for the same call: a `preToolUse` hook matching `^subagent_` (or `^team_` for the team roster) is the way to deny one.

```json
{
  "hooks": {
    "preToolUse": [{ "command": ".codna/hooks/no-delegation.sh", "matcher": "^(subagent_|spawn_agent|team_)" }],
    "subagentStop": [{ "command": ".codna/hooks/audit-delegation.sh", "matcher": "reviewer" }]
  }
}
```

### `afterAgentThought` / `afterAgentResponse` — the model's message

Both fire once per model call, on the completed assistant message: `afterAgentThought` when the message carries a reasoning block, `afterAgentResponse` when it carries reply text. A reply with both fires both, in that order. A tool-only reply fires neither — there is nothing to observe.

They are **not** per-token: `afterAgentResponse` carries the whole reply in `response`, because a hook per streamed delta would spawn a subprocess per token.

### `workspaceOpen` and `sessionEnd` — the session's life

`workspaceOpen` fires once, at the first turn, **before** `sessionStart`, so a hook that prepares the root runs before a `sessionStart` hook that reads what it prepared. Payload: `workspace_roots` and `cwd`.

`sessionEnd` fires from teardown, with `reason` naming which: `deleted` when a chat is deleted **or evicted** (the idle/capacity sweep drops it), `stopped` when it is stopped or the engine process shuts down in a controlled way, `aborted` when the turn was aborted. It is not `stop`: `stop` is the end of a **turn**, and a `sessionEnd` hook wired to it would run once per turn.

**Every way a session ends fires it**, including the ones that are not a request from a client: a session that ages out of the engine's idle horizon, is trimmed for capacity, or is resident when the process is told to shut down all dispatch `sessionEnd`. A "release the lock" or "upload the transcript" hook therefore runs whether the chat was deleted by the user or simply forgotten by the engine. If the process is killed (SIGKILL), no hook can run — that is a property of being killed, not a gap here.

### `beforeTabFileRead` / `afterTabFileEdit` — inline (Tab) completion

These fire from the IDE's Tab-completion pipeline, not from an agent turn. A completion request carries no session, so `file_path` and `workspace_dir` come from the editor: they are the only facts there are.

**`beforeTabFileRead` is a real gate, and it is a PATH gate.** It fires *before* the model is called. A deny returns a coded refusal (`inline_completion_tab_hook_denied`) and **no request is made**: no token is spent, and the file's context never leaves the process. That is what the event is named for — keeping a file out of Tab context:

```json
{
  "hooks": {
    "beforeTabFileRead": [{ "command": ".codna/hooks/no-env-in-tab.sh", "matcher": "\\.env$" }]
  }
}
```

* The **matcher** is tested against the **file path**, so a path-scoped guard is expressible. (This differs from `beforeReadFile`, whose matcher is the tool name.)
* The payload carries `file_path`, `content: ""` and **`content_available: false`**. There are no bytes to send: the editor builds the prompt from its own buffer and posts the text, so the engine never reads the file. **A hook cannot scan content here** — judge the path. Claiming otherwise would be a gate that does not gate.
* **A request that names no file is refused** while this event is armed. A guard must not be bypassable by omitting a field.
* A hook that crashes **blocks** (fail closed), like every other blocking event.
* **`workspaceDir` and `filePath` are confined to the folders the launcher declared**, and a path outside them is refused with `inline_completion_workspace_denied`. See below — this is the boundary that decides which hooks file the engine will even read.

**`afterTabFileEdit` observes an acceptance.** It fires when the editor *applied* a completion — not when ghost text appeared, and not when one was rejected. The engine answers with a string and never learns what Monaco did with it, so the IDE reports the acceptance:

* Payload: `file_path`, `completion` (the accepted text), `inserted_characters` (the **editor's** count — a partial accept applies a prefix), and `provider`/`model` when known.
* **It cannot block**, and cannot fail the insert: a crash is a report. An observer must not change what it observed.
* With no hook armed, the report answers `{ "reported": false }` — the ordinary case, not an error.

Completions arm these hooks by default in an interactive window. A deployment nobody is watching sets **`CODNA_TAB_HOOKS=0`**, which disarms both — the same reasoning that keeps an unattended run from arming any hook.

### Which directories a Tab completion may load hooks from

A Tab completion carries no session, so the engine cannot ask "which workspace is this?". The request names one, but **the request is not the authority**: these fields decide which `hooks.json` is read and whose commands run, so a caller that could name any directory could have the engine execute a hook from it.

The authority is the **launcher**. The host that spawns the engine declares the folders it may serve Tab completions for:

```bash
CODNA_WORKSPACE_ROOTS='["/home/me/proj-a","/home/me/proj-b"]'
```

* `workspaceDir` must be one of those folders or a directory under one. Anything else is refused with `inline_completion_workspace_denied`, and **no hook is read and no provider call is made**.
* `filePath` is confined by the same rule, because it is handed to a hook as `file_path`. It is compared against **all** declared roots, so a multi-folder window can complete a file in its second folder.
* Comparison is on **real paths** (`realpath`), so `..`, symlinks and case differences cannot escape. `..` is refused outright rather than resolved: collapsing `link/..` is unsafe once `link` is a symlink.
* **An absent or empty declaration authorizes nothing.** The engine does not fall back to its working directory, to `$HOME`, or to "the one folder it found" — a fallback is the same bypass under another name, since a caller would only have to name the directory the engine defaulted to.
* A declared root that is not an existing directory is ignored, so nothing that is later created at that name becomes a hooks source without a new declaration.

The engine's own folder list is never consulted here: a deployment that serves completions must state what it serves.

## What an unsupported event does

There is exactly one case, and it is never silent.

**An event name this build does not fire** — a typo, or a Cursor version newer than Codna — is reported as `hook_event_unknown` and its entry is refused. Guessing what a name means is how a typo becomes a hook at the wrong moment. Its neighbours still arm: one bad key must not disable a repository's other hooks.

There used to be a second case — "recognized but cannot fire", with a per-event reason string. It is **gone**, because every name Codna recognizes now has a real moment, and a reason string that outlives its fact is the same defect as a hook that never runs. `preCompact` was in that list's shadow too: it was in the catalogue with no dispatch site, and now fires from the compaction notice.

```
codna: warning: [hooks] hook_event_unknown: .codna/hooks.json: 'beforeShellExection' is not a
Cursor hook event this build recognizes. Its 1 hook(s) will NOT run.
```

Every warning also appears on the session itself (`hooks.warnings` in the create-session reply) and in a `session.hooks_loaded` event, so a script can check what was armed without reading logs.

**A `prompt`-type hook** (Cursor's LLM-evaluated kind) is **refused**. Codna has no classifier, and a "probably allow" machine should not decide whether code runs. Only `command` hooks execute.

## Exit codes and blocking

| Exit           | Meaning                                                                               |
| -------------- | ------------------------------------------------------------------------------------- |
| `0`            | The hook succeeded. Its JSON is read as its answer.                                   |
| `2`            | **Block** the guarded action (equivalent to `permission: "deny"`).                    |
| other non-zero | The hook failed. It blocks if `failClosed` resolves true, and is reported either way. |
| timeout        | Same as a failure.                                                                    |

A hook can also block by answering JSON. Both Cursor's spellings are read:

```json
{ "permission": "deny", "user_message": "shown to you", "agent_message": "shown to the model" }
{ "continue": false, "user_message": "shown to you" }
```

`permission: "ask"` is **not** a block: it defers to the normal approval gate (#716), so a hook cannot use `ask` to bypass a parked tool or to approve one.

Answers are merged across hooks: **deny wins** over allow, and `user_message`/`agent_message` are concatenated.

### Fail closed by default

Cursor's default is fail-open — a crashed hook lets the action through. Codna's default is **fail closed for the events that can block** (`beforeSubmitPrompt`, `beforeReadFile`, `preToolUse`, `beforeMCPExecution`, `beforeShellExecution`, `beforeTabFileRead`). An audit hook that fails should not stop work; a hook whose whole purpose is to refuse something must not become a no-op because it crashed.

An observer (`postToolUse`, `afterFileEdit`, …) has nothing to close, so a failure there is a report.

To get Cursor's behaviour on a specific hook, say so explicitly:

```json
{ "command": ".codna/hooks/audit.sh", "failClosed": false }
```

## Security

A hook is arbitrary code execution, so it is treated exactly as strictly as a shell command.

* **Hooks are off unless the file arms them.** The only thing that enables hooks is a `hooks.json` on disk in an open, trusted workspace. A **create-session request body cannot enable hooks** — a body carrying `hooks` or `hooks_enabled` is ignored, because a request is logged, captured and replayed, while a committed file is something you wrote and reviewed.
* **`permissions.json` applies.** A hook's command line is judged by the same allowlist your shell commands are. A hook that is not a listed program does not run, and the refusal names it.
* **An unattended run arms nothing.** Nobody is watching and the run may be started by a webhook, so every hook is skipped and each one is reported as not armed. This is the same reasoning that sandboxes an unattended shell.
* **Hooks run with a stripped environment.** The credential variables the shell sandbox removes (`*_API_KEY`, `*_TOKEN`, `SSH_AUTH_SOCK`, cloud keys, …) are removed here too. A hook that needs a credential should get it from the platform, not from the agent's process.
* **No shell interpretation.** A `command` is split into an argv and spawned directly. `$VAR`, `$(…)`, `|`, `;`, `<`, `>` are **refused** — put that logic in a script and name the script, so the command that runs is the one that was read.

A malformed `hooks.json` **refuses the session create** rather than producing a session you believe is guarded. A file that cannot be read is not a file that configures nothing.

## Hooks and rules are different things

|               | Rules (`AGENTS.md`, `.cursor/rules/*.mdc`) | Hooks (`hooks.json`) |
| ------------- | ------------------------------------------ | -------------------- |
| What it is    | text added to the prompt                   | a program that runs  |
| Can it block? | no — it can only instruct                  | **yes**              |
| Reviewed as   | content                                    | **code execution**   |

## Limitations

* `prompt`-type hooks are refused (no classifier).
* `beforeTabFileRead` gates by **path only**: there is no file content at that seam, because the editor sends the text and the engine never reads the file. Judge the path rather than the bytes.
* `afterTabFileEdit` observes an accepted completion and cannot refuse one; it cannot change an insert that already happened.
* `subagentStart` observes a delegation but cannot refuse one; use `preToolUse` with a `^subagent_` / `^team_` matcher for that.
* `preCompact` observes a compaction and cannot refuse one: the strategy runs inside the SDK and there is no seam to stop it.
* Hook scripts must be named by a command that `permissions.json` allows, if you have a `permissions.json`.
