agentleFS
mboss37mboss37/claude-launchpad/.cursor/rules/hooks.mdc

claude-launchpad / rules

Cursor rule8 starsChanged 5 months agoMITView on GitHub

Hook authoring rules

  • Reads credentials
  • Deletes or force-pushes
  • Installs packages
  • Commits and pushes

The file

We split this hooks.mdc into the rules it gives an agent

12 rules. About 0 are common, 6 are distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈6

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    If two top-level entries share the same matcher (e.g.

    line 101
  2. Distinctive:

    When fixing or adding a hook:

    line 130
  3. Distinctive:

    Test the hook command in isolation (see "Testing" below)

    line 133
  4. Distinctive:

    Verify the hook fires by triggering the conditions it watches

    line 135
  5. Distinctive:

    Before installing or restarting, verify the command works by piping a fake JSON payload to it:

    line 141
  6. Very specific:

    Don't reference $TOOL_INPUT_COMMAND, $TOOL_INPUT_FILE_PATH, $TOOL_INPUT_NEW_TEXT, or any other TOOL_INPUT_* env var.

    line 201
  7. Very specific:

    Don't exit 1 to block. It is silently non-blocking.

    line 202
  8. Distinctive:

    Don't echo the block reason to stdout when exiting 2.

    line 203
  9. Very specific:

    Don't create a second top-level entry with a matcher that already has an entry.

    line 204
  10. Very specific:

    Don't expect mid-session settings.json edits to take effect.

    line 205
  11. Distinctive:

    Don't ship a hook without isolation-testing the command first.

    line 206
  12. Very specific:

    Don't put long debug logging into a production hook.

    line 207

≈ “Common” is an estimate: at least 1 in 5 of the 7,324 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
hooks.mdc
---
description: Hook authoring rules
globs: {.cursor/hooks.json,.cursor/hooks/**}
alwaysApply: false
---

<!-- lp-cursor-hooks-version: 1 -->
# Cursor Hook Authoring Rules

Applies to every hook entry in `.cursor/hooks.json` and `.cursor/hooks.json`. Hooks are the project's automated safety net. Getting the API wrong silently disables the protection without any error. **A broken hook is worse than no hook because it gives false confidence.**

Reference: https://code.claude.com/docs/en/hooks

## Anatomy of a hook entry

```json
{
  "hooks": {
    "<EventName>": [
      {
        "matcher": "<ToolMatcher>",
        "hooks": [
          { "type": "command", "command": "<shell-string>" }
        ]
      }
    ]
  }
}
```

- `EventName`: `sessionStart`, `SessionEnd`, `beforeShellExecution`, `afterFileEdit`, `afterFileEditFailure`, `UserPromptSubmit`, `Stop`, `PermissionRequest`, `PreCompact`, `PostCompact`. PostCompact is side-effect-only (stdout is never injected) — to re-inject context after compaction, use sessionStart with matcher `compact`.
- `matcher`: a regex-style string matching tool names (e.g. `Bash`, `Read|Write|Edit`). Empty string matches all tools for the event. For sessionStart use `startup`, `resume`, `clear`, or `compact`.
- `hooks` array: every entry runs in parallel when the matcher fires. Identical command strings are deduplicated automatically.

## The `if` field — when to use it

- `if` (beforeShellExecution/afterFileEdit/afterFileEditFailure/PermissionRequest) filters a hook with a SINGLE permission rule (e.g. `"if": "Bash(terraform *)"`) before your command ever spawns — cheaper than jq+grep for hooks targeting one narrow rule.
- The generated guards intentionally do NOT use it: they match multiple patterns in one hook (rm -rf, DROP TABLE, force-push) and need exclusions (.env but not .env.example) that permission-rule syntax cannot express. Splitting them into per-rule entries would grow the config without changing behavior — the jq+stdin grep stays the single source of truth.
- For your own single-pattern hooks, prefer `if` over an inline grep.

## Long-running SessionEnd work — use `async: true`

- Plain SessionEnd hooks are killed when Cursor Agent exits — a ~3s network push never completes (verified empirically). Mark the hook `{"type": "command", "command": "...", "async": true}` and it survives; output is logged without touching the conversation.
- The old workaround was a `nohup ... & exit 0` wrapper — still works, but the native field is canonical now.

## Input — JSON on stdin, NOT env vars

The hook receives a JSON payload on stdin. **There are no `TOOL_INPUT_*` environment variables in current Cursor Agent.** A hook that does `cmd="$TOOL_INPUT_COMMAND"` reads an empty string and silently no-ops. This is the single most common authoring bug.

Canonical extraction:

```bash
fp=$(jq -r '.tool_input.file_path // empty' 2>/dev/null)   # beforeShellExecution Read|Write|Edit
cmd=$(jq -r '.tool_input.command // empty' 2>/dev/null)    # beforeShellExecution Bash
new=$(jq -r '.tool_input.new_string // .tool_input.content // empty' 2>/dev/null)  # afterFileEdit Edit|Write
```

Top-level keys you can read: `session_id`, `transcript_path`, `cwd`, `permission_mode`, `hook_event_name`, `tool_name`, `tool_input`, `tool_use_id`. `afterFileEdit` adds `tool_response`.

`jq` is a project-level requirement. Install via `brew install jq` (macOS) or your distro's package manager.

## Exit codes — 2 blocks, 1 does not

| Exit code | Effect |
|---|---|
| `0` | Allow the action. Hook stdout becomes context (sessionStart) or is informational (afterFileEdit). |
| `2` | Block the action. Hook stderr is fed back to Claude as the error reason. |
| any other non-zero (`1`, `127`, …) | Treated as a non-blocking hook error. **The action proceeds anyway.** |

`exit 1` does NOT block. If the hook is meant to enforce a policy, it must end in `exit 2`.

Block reasons go to **stderr** (`echo '...' >&2`), not stdout. Stdout is ignored when exit code is 2 unless the hook returns the JSON envelope (see "Richer control" below).

## Output — stderr for blocks, stdout for warnings

```bash
# Blocking: stderr + exit 2
echo 'BLOCKED: <reason shown to Claude>' >&2
exit 2

# Informational warning that does not block: stdout + exit 0
echo 'WARNING: <message printed to user>'
exit 0
```

Richer control (only use when the simple form is insufficient):

```bash
jq -n '{
  hookSpecificOutput: {
    hookEventName: "beforeShellExecution",
    permissionDecision: "deny",
    permissionDecisionReason: "<reason>"
  }
}'
exit 0
```

## Multi-hook same matcher — combine into ONE entry

If two top-level entries share the same matcher (e.g. two `beforeShellExecution` entries both with `matcher: "Bash"`), behavior is undefined: in practice the second entry can fail to fire. **Always combine commands for the same matcher into a single entry's `hooks` array.**

Wrong:

```jsonc
"beforeShellExecution": [
  { "matcher": "Bash", "hooks": [{ "type": "command", "command": "<destructive-guard>" }] },
  { "matcher": "Bash", "hooks": [{ "type": "command", "command": "<sprint-open-check>" }] }
]
```

Right:

```jsonc
"beforeShellExecution": [
  {
    "matcher": "Bash",
    "hooks": [
      { "type": "command", "command": "<destructive-guard>" },
      { "type": "command", "command": "<sprint-open-check>" }
    ]
  }
]
```

## Hot-reload — there is none

Edits to `.cursor/hooks.json` or `.cursor/hooks.json` only take effect after a Cursor Agent session restart. Mid-session edits parse fine and persist to disk, but the running session keeps the hooks it loaded at start.

When fixing or adding a hook:

1. Edit settings.json
2. Test the hook command in isolation (see "Testing" below)
3. Restart Cursor Agent
4. Verify the hook fires by triggering the conditions it watches

Skipping step 3 means the new hook does not exist yet, no matter what the file says.

## Testing a hook command in isolation

Before installing or restarting, verify the command works by piping a fake JSON payload to it:

```bash
HOOK=$(jq -r '.hooks.beforeShellExecution[<index>].hooks[<index>].command' .cursor/hooks.json)
echo '{"tool_input":{"command":"git push --force"}}' | bash -c "$HOOK"
echo "exit=$?"
```

Expected for a correctly-blocking hook: stderr contains the BLOCKED reason, `exit=2`. If you see `exit=0` here, the hook will not block in production either.

For afterFileEdit hooks that read file paths or content, build the JSON to mirror the tool you're matching:

```bash
echo '{"tool_input":{"file_path":"docs/architecture.md","new_string":"..."}}' | bash -c "$HOOK"
```

## Canonical templates

### beforeShellExecution Bash gate (block on regex match)

```bash
cmd=$(jq -r '.tool_input.command // empty' 2>/dev/null); echo "$cmd" | grep -qE '<your-pattern>' || exit 0; echo 'BLOCKED: <reason>' >&2; exit 2
```

**Do not anchor the pattern with `^[[:space:]]*`** when you want to catch chained commands. The hook receives the entire shell command string verbatim, so an anchored pattern silently misses commands like `git status && git push`. Use `(^|[^[:alnum:]])<token>([[:space:]]|$)` to match the token at start-of-line OR after a non-alphanumeric separator.

### beforeShellExecution Read|Write|Edit gate (block on file-path match)

```bash
fp=$(jq -r '.tool_input.file_path // empty' 2>/dev/null); echo "$fp" | grep -qE '<your-pattern>' || exit 0; echo 'BLOCKED: <reason>' >&2; exit 2
```

### afterFileEdit informational warner (never blocks; just prints)

```bash
fp=$(jq -r '.tool_input.file_path // empty' 2>/dev/null); echo "$fp" | grep -qE '<your-pattern>' || exit 0; echo '<warning text>'; exit 0
```

afterFileEdit blocking (exit 2) is supported but rare. By the time afterFileEdit fires, the file write has already happened. Almost always you want exit 0 with a stdout message.

### sessionStart context injection

```bash
cat <some-file> 2>/dev/null; exit 0
```

Output goes into the session's context. Always exit 0; sessionStart blocking is not a thing.

## Adding a new hook — checklist

- [ ] Identify the event and matcher you actually need (`beforeShellExecution` for blocking before, `afterFileEdit` for after-the-fact warnings).
- [ ] Read the input via stdin JSON with `jq`, **not env vars**.
- [ ] If it blocks: send reason to stderr, end with `exit 2`. If it warns: stdout, end with `exit 0`.
- [ ] If a hook for the same matcher already exists, add your command to its existing `hooks` array — do NOT create a second entry with the same matcher.
- [ ] Test the command in isolation by piping a fake JSON payload (see "Testing" above) — verify the exit code matches your intent.
- [ ] Restart Cursor Agent.
- [ ] Verify the hook fires under the conditions it watches and does not fire under benign conditions.

## Do not

- Don't reference `$TOOL_INPUT_COMMAND`, `$TOOL_INPUT_FILE_PATH`, `$TOOL_INPUT_NEW_TEXT`, or any other `TOOL_INPUT_*` env var. They do not exist; the hook silently no-ops.
- Don't `exit 1` to block. It is silently non-blocking. Use `exit 2`.
- Don't echo the block reason to stdout when exiting 2. Stdout is ignored in that case; only stderr reaches Claude.
- Don't create a second top-level entry with a matcher that already has an entry. Combine commands in the existing entry's `hooks` array.
- Don't expect mid-session settings.json edits to take effect. Restart is required.
- Don't ship a hook without isolation-testing the command first. A silent no-op is worse than no hook.
- Don't put long debug logging into a production hook. If you need diagnostics during development, write to `/tmp/<name>.log` and remove the line before commit.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.