- JavaScript 100%
chook #
A PreToolUse hook for Claude Code that gives you granular control over what Claude can do, with an interactive review TUI for building rules from real usage.
Zero dependencies. Single JS file. Works with any Claude Code session on your machine.
Install #
ln -s /path/to/chook/chook.mjs /usr/local/bin/chook
cp example.toml ~/.config/chook.toml
Add to ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "node /path/to/chook/chook.mjs run"
}
]
}
],
"Notification": [
{
"matcher": "permission_prompt",
"hooks": [
{
"type": "command",
"command": "node /path/to/chook/chook.mjs notify"
}
]
}
]
}
}
The Notification hook enables macOS notifications when Claude is waiting for your approval.
How it works #
Every time Claude tries to use a tool, the hook checks your rules:
- Deny rules checked first — hard block, Claude sees your
reasonmessage - Ask rules checked next — Claude Code prompts you to confirm
- Allow rules checked next — auto-approved, no prompt
- No match — passthrough to Claude Code's normal permission flow
Claude tries tool → deny? → BLOCKED (with guidance)
→ ask? → PROMPT USER (with reason)
→ allow? → AUTO-APPROVED
→ none? → normal Claude Code prompt
Unattended mode #
Set CHOOK_UNATTENDED=1 when launching Claude for autonomous/overnight runs.
In this mode, [[ask]] rules behave like [[deny]] — Claude gets a clear
"Unattended mode: …" reason and adapts instead of blocking on a prompt no
human will answer. An ask rule can opt out of that deny for a Bash delete
command chook's own delete fence already verified stays inside the session's
tree and loses nothing git can't restore — see allow_if_fenced under Ask
rules.
Config #
Default location: ~/.config/chook.toml (override with --config)
Double-quoted strings take the TOML escapes \b \t \n \f \r \" \\ \uXXXX \UXXXXXXXX;
any other escape is a config error, so a regex backslash is written "\\s" (or
use a single-quoted literal string). A config error is reported as
chook: <path>: <problem>.
Deny rules #
[[deny]]
tool = "Bash"
command_regex = "^rm .*-rf"
reason = "Use rm on specific files, or ask the user to run this manually."
[[deny]]
tool = "Bash"
command_regex = "&|;|\\||`|\\$\\("
reason = "BLOCKED: You MUST run exactly ONE command per Bash call."
[[deny]]
tool = "Read"
file_path_regex = "\\.(env|secret|pem|key)$"
reason = "Ask the user to provide the needed values."
The reason string is shown to Claude, so write it as guidance for what to do instead.
Carving safe idioms out of a one-command-per-call block #
A &|;|\|| metachar block enforces "one command per Bash call", but it also
blocks safe single operations agents waste turns re-discovering — a cd <dir> && <cmd> navigation prefix, a single pipe into a read-only pager, and a lone
redirection (2>&1, >&2, &>file). Carve those out with
command_exclude_regex (paired with strip_quoted, so a quoted
metachar-as-data is already gone before the exclude runs):
[[deny]]
tool = "Bash"
command_regex = "&|;|\\||`|\\$\\("
# Exempt: (A) `cd DIR && cmd`; (B) one pipe into a whitelisted read-only pager; (C) a lone redirection (2>&1, >&2, &>file).
command_exclude_regex = "(?:^cd (?:[^&;|`$]|(?<=>)&|&(?=>))+&&(?:[^&;|`$]|(?<=>)&|&(?=>))+$)|(?:^(?:[^&;|`$]|(?<=>)&|&(?=>))+\\|\\s*(?:head|tail|less|more|cat|wc|sort|uniq|grep|egrep|fgrep|column|nl|rev|tr|cut)(?:\\s(?:[^&;|`$]|(?<=>)&|&(?=>))*)?$)|(?:^(?:[^&;|`$]|(?<=>)&|&(?=>))+$)"
strip_quoted = true
reason = "Run one command per call. Exceptions: a `cd <dir> && <cmd>` prefix, one pipe into a read-only pager (| head, | grep, | wc), or a lone redirection (2>&1, >&2, &>file). Otherwise split into separate calls."
Safety invariant. Exemption (A) lets the post-&& command skip this rule,
so every other Bash deny/ask rule must be anchored (?:^|&&\s*) (not bare ^)
to still fire behind a cd && prefix — otherwise it is bypassable via cd x && <evil>. With that anchoring, cd DIR && B and A | pager grant nothing B/A
couldn't already do standalone. See example.toml for the anchored rm/sudo/sed
rules.
Exemption (C) permits & only when adjacent to a >, which is what makes
2>&1 / >&2 / &>file redirections rather than a second, unreviewed
command — a bare backgrounding cmd & or chaining && has no > neighbour
and stays blocked. That carve-out grants nothing the underlying command
couldn't already do.
Ask rules #
# Recursive rm — review the path before approving (denied in unattended mode),
# unless the delete fence already verified it — see allow_if_fenced
[[ask]]
tool = "Bash"
command_regex = "^rm (.* )?(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)( |$)"
reason = "Recursive rm — review the path before approving."
allow_if_fenced = true
The reason is shown both to Claude and on the prompt, so write it as
context for the human approving the call.
allow_if_fenced = true skips an ask rule when chook's own delete fence
confirmed every delete target in the command is in a temp dir or inside the
session's tree (its checkout, or its cwd when it started outside any repo) and
loses nothing git can't restore: no .git, no primary checkout root, no
directory containing a linked worktree, and no modified, staged or untracked
file under it. Gitignored content such as build output counts as regenerable,
except a gitignored secrets file (.env, .env.*, *.secret, *.pem,
*.key), which blocks verification. When the rule fires because the fence
couldn't verify, the reason says why and points at temp dirs for scratch files.
Attended, such a delete runs without a prompt; unattended, it is allowed
instead of denied. Any other delete — a target outside the tree, a $VAR or
~ path, or one that would lose uncommitted work — still asks (attended) or
is denied (unattended). The older name
unattended_allow_if_fenced is still accepted.
Folders that only ever hold throwaway output can be counted as temp dirs too,
so deletes under them run without review attended or unattended. $HOME
expands; / is ignored.
[delete_fence]
scratch_dirs = ["$HOME/build-scratch", "/var/cache/test-runs"]
Allow rules #
# Auto-allow file ops in the project directory
[[allow]]
tool = "Read"
restrict_to_cwd = true
# Auto-allow /tmp
[[allow]]
tool = "Read"
file_path_regex = "^/tmp/"
# Auto-allow safe bash commands
[[allow]]
tool = "Bash"
command_regex = "^git "
command_exclude_regex = "push.*--force"
# Auto-allow specific subagents
[[allow]]
tool = "Task"
subagent_type = "Explore"
# Auto-allow a tool chook has no dedicated matcher for — bare `tool = "X"`
# matches any call to that tool, since there's no path/command/prompt field
# to check it against.
[[allow]]
tool = "WebSearch"
A rule for Read, Write, Edit, Glob, NotebookEdit, Bash, Monitor,
or Task is checked against that tool's known fields (path, command, prompt,
etc.), as in the field table below. For any other tool name — WebSearch,
WebFetch, Grep, TodoWrite, and so on — chook has no field to check, so
only a bare tool = "X" rule (no file_path_regex, command_regex, or other
matcher set) matches, and it matches every call to that tool. A rule for one
of these tools that also sets a matcher never matches anything — there's no
field on the call for it to check, and matching regardless would be silently
wrong rather than silently inert.
Rule fields #
| Field | Tools | Description |
|---|---|---|
tool |
all | Tool name to match (required) |
reason |
all | Message shown to Claude on deny |
restrict_to_cwd |
file tools | Restrict to the directory where Claude was started. Checked against the path with every symlink followed (including one at the leaf, which usually doesn't exist yet — the nearest existing ancestor is resolved instead and the rest re-appended), so a link inside the tree that points outside it is caught rather than passing on its nominal path. A dangling or self-referential link is treated as pointing wherever its target says, existing or not; a link loop can't be resolved and is denied. |
file_path_regex |
Read, Write, Edit, Glob, NotebookEdit | Regex the file path must match. Tested against the path as the caller wrote it (made absolute, .. collapsed), not the symlink-followed path restrict_to_cwd checks — a pattern aimed at a path shape keeps matching what was actually typed even if a link sits somewhere in it. $HOME stands in for the home directory — see below. |
file_path_exclude_regex |
file tools | Regex that rejects the match. Tested against the same resolved-but-not-symlink-followed absolute path as file_path_regex, so a pattern aimed at catching literal .. in the input (e.g. "\\.\\.") never fires — resolve() has already collapsed every .. segment by the time this runs. restrict_to_cwd is what actually keeps a path from escaping cwd, .. or not. |
command_regex |
Bash | Regex the command must match |
command_exclude_regex |
Bash | Regex that rejects the match |
strip_quoted |
Bash | If true, strip single-quoted segments from the command before matching command_regex / command_exclude_regex. Use on metachar deny rules to permit literal &, ;, | inside '...' (git log --grep 'a|b', grep -E 'a|b', sed patterns) while still blocking real shell composition. |
subagent_type |
Task | Exact match on subagent type |
prompt_regex |
Task | Regex the prompt must match |
prompt_exclude_regex |
Task | Regex that rejects the match |
isolation_regex |
Task | Regex the isolation parameter must match (e.g. "^worktree$" to block git-worktree-isolated agents) |
run_in_background |
Task | Boolean match on the spawn's background flag. An absent flag counts as false, so run_in_background = false matches both an explicit false and an omitted one — use it to deny foreground spawns. |
$HOME in a path pattern #
Path rules match a resolved absolute path, so a rule about the operator's own
files has to spell out a home directory. That ties the config to one machine
and names a person, which is a problem for a config kept in version control and
shared between machines. $HOME in file_path_regex or
file_path_exclude_regex is replaced with the real home directory,
regex-escaped, before the pattern is compiled:
[[allow]]
tool = "Read"
file_path_regex = "^$HOME/\\.claude/docs/"
Only those two fields. command_regex and prompt_regex match text the model
wrote, where a literal $HOME is what the author means, and are left alone.
Suggested rules printed by chook audit fold a leading home directory back to
$HOME for the same reason.
Auditing #
[audit]
audit_file = "/tmp/chook-audit.json"
audit_level = "matched" # off | matched | all
audit_max_bytes = 10485760 # rotate past this size; defaults to 10MB
Audited strings are truncated to 256 characters to keep the log greppable, with
one exception: Task/Agent inputs are truncated at 8000, because a spawn's
prompt is the one audited field whose length and structure are themselves the
data the spawn-brief guard is tuned against.
Once audit_file passes audit_max_bytes, it is rotated: the current file
moves to audit_file + ".1" (overwriting any previous one) and a fresh file
starts collecting new entries. The size is checked once per append with a
single stat() call — cheap enough to run on every hook invocation, unlike
counting rows or parsing timestamps — so rotation itself only happens once the
cap is actually crossed. A rotation failure is logged to stderr and never
changes the permission decision, the same as any other audit write failure.
Commands #
chook run #
Hook handler. Reads tool JSON from stdin, outputs permission decision to stdout. This is what Claude Code calls.
chook notify #
Notification handler. Fires a desktop notification — osascript on macOS,
notify-send on Linux — for the notification types the matcher routes to
it.
chook validate #
Check your config for errors.
$ chook validate
Configuration is valid!
Deny rules: 5
Allow rules: 11
Audit file: /tmp/chook-audit.json
Audit level: matched
Audit max bytes: 10485760
chook review #
Interactive TUI for reviewing denied/passthrough tool uses and adding rules.
Entries are grouped into smart suggestions:
- Bash commands grouped by command name (e.g.
git,npm,cargo) - File operations grouped by project directory with
restrict_to_cwd - Dangerous commands like
rmget automaticcommand_exclude_regexfor dangerous flags
Navigate with j/k, press a to allow, d to deny, s to skip, q to quit.
chook allow-last #
Add an allow rule from the most recent audit entry.
chook deny-last #
Add a deny rule from the most recent audit entry.
chook ask-last #
Add an ask rule from the most recent audit entry.
Workflow #
The fast feedback loop when Claude gets blocked:
- Claude tries something, gets prompted or blocked
Ctrl-Zto background Claudechook allow-lastto allow it (orchook reviewto see all recent entries)fgto resume
Rules are live immediately — the config is read on every hook invocation.
Inline-grind limit #
chook counts consecutive inline exploration calls (Read, Grep, Glob) by the
top-level agent and hard-denies once the streak reaches 4, telling the agent
to delegate the work to a subagent instead. Passive reminders in a system prompt
decay out of context; this is a behavioral trigger that fires exactly when the
grinding is happening.
Bashis deliberately not counted — build, test, and git work must never be blocked.- Flat deny at streak 4, not an escalating nudge: the 4th explore call is denied, and so is every explore call after it until the streak resets.
- A
Taskcall (delegation happened) resets the streak to 0; so does a new user turn (detected via a change inprompt_id). Non-explore tools (Bash, Write, Edit, …) leave the streak unchanged. - The text reaches the model as
permissionDecisionReasonon a deny — the only channel chook has. It emits noadditionalContextanywhere. A deny is also what keeps the agent moving: anaskwould idle it waiting on a human. - Only the top-level agent is ever blocked. Subagent tool calls reach the
hook sharing the parent's
session_idbut carryagent_id+agent_type; the top-level agent's calls omit both, and chook stays silent for anything not positively identified as top-level. A grinding subagent is doing its job — blocking it would push it to spawn a forbidden depth-2 agent.
State lives in /tmp/chook-grind-<session_id> ({streak, promptId}). Set
CHOOK_GRIND_DEBUG=1 to log each transition to /tmp/chook-grind-debug.jsonl.
Worktree guards #
A writing subagent works in a checkout of its own, never in the repo's primary one. Two writing agents in one working tree overwrite each other's files, and either one's commit or checkout moves the HEAD the other is standing on; even a lone one commits onto whatever branch the primary happens to be sitting on. Two guards enforce that from opposite ends, and neither keeps state — the rule is unconditional, so there is nothing to remember between calls and no re-issue that passes.
At spawn time (top-level Task calls only) a writing spawn is denied unless
it hands the agent a checkout:
- Read-only subagents are exempt:
Explore,routine-explorer,Plan, andclaude-code-guidehave noEdit/Writegrant, so they can't write in a checkout at all. An absentsubagent_typecounts as a writer (it defaults togeneral-purpose). - The prompt has to name a
.worktrees/<name>path that already exists on disk — resolved against the session's cwd, absolute or relative. A path that is only mentioned, or one the spawner means to create afterwards, is exactly how agents ended up writing in the primary checkout. - A clone-pool dir (
<name>-clone-<slot>/) is accepted on the prompt text alone: the pool lives outside the session's repo, so unlike a.worktrees/path it can't be resolved from cwd and checked. - Nothing is denied when the session is not in a repo, or is already running inside a worktree — a track's agents inherit its isolation.
At write time (subagent calls only) a Write, Edit, or NotebookEdit is
denied when the file lands in the primary checkout of the repo the session is
working in:
- Primary checkout vs. worktree is read off
.gititself: a directory in a primary checkout, a file holdinggitdir: <path>in a linked worktree. No git binary is involved. A submodule carries a.gitfile too, and it has its own HEAD and working tree, so it isn't the shared tree this protects either. - Symlinks are followed the way the write itself would follow them, so a link inside a worktree pointing back at the primary doesn't slip through.
- From inside a worktree, its
.gitfile names<primary>/.git/worktrees/<name>, which is how a subagent in a track's worktree is stopped from reaching back over the parent repo's files. - Only the session's own repo. A write into some other repo's primary checkout —
~/.claude, a sibling project — is left to the config's path rules. - The top-level session is not blocked. It is the session itself rather than an agent it dispatched, and it is where a worktree gets created.
What this does not cover. The spawn side reads the prompt, so an agent can
be pointed at a worktree and ignore it; that is what the write side is for.
Edits made through Bash (sed -i, a heredoc) reach neither guard — Bash is
deliberately absent from the write side, because half-parsing shell would block
the git and build commands agents legitimately run in any checkout.
All three run after the grind check and before ask rules. Guard state files
from the counting version of this guard (/tmp/chook-writers-<session_id>) are
still swept by the state pruner; nothing writes them any more.
Nested-writer guard #
Subagent nesting is available — the CLI caps it at depth 3 — and the point is
read-only nesting: a track writer sending a long search off to
routine-explorer instead of grinding through it inline. A nested writing
agent is the failure case the spawn-time worktree guard above can't reach,
because that guard only runs for top-level spawns: a subagent's Task call
lands in the same worktree its parent is already editing, and two writers in
one tree overwrite each other.
chook.mjs run denies a Task spawn issued by a subagent when the
subagent_type is not one of the read-only agents (Explore,
routine-explorer, Plan, claude-code-guide) — the same set the spawn-time
worktree guard treats as safe. An absent subagent_type defaults to a writer
and is denied too, matching that guard.
Unlike the spawn-time worktree guard, there is no worktree-of-its-own fix to offer: naming one doesn't help, because creating a worktree is the top-level session's job — the branch it makes has to be merged by whoever owns the task. The deny reason says so, and tells the subagent to do the edit itself or delegate the search read-only, or stop and hand the need back to the top level.
Spec-watch tick exemption #
A spec-watch-tick subagent runs one spec-watch tick with a fresh context
per run, coordinating from the primary checkout by design rather than a
worktree of its own — the fresh context per tick is the point, and creating
a worktree per tick would defeat it. Both worktree guards above carve out a
narrow exception for exactly that agent type:
- Spawn time:
writerWorktreeGuardlets aTask/Agentspawn withsubagent_type: "spec-watch-tick"through with no worktree named, the same way it already lets the read-only agents through. - Write time:
primaryCheckoutGuardlets aspec-watch-ticksubagent'sWrite/Edit/NotebookEditland in the primary checkout only when the path, relative to the checkout root, is exactlyhandoff.md— matched the same repo-relative wayTRACK_ROOT_WRITABLEmatches the roster, so a nestedhandoff.mdstill counts as a write into the checkout rather than the roster. Every other path, and every other agent type, is denied as before.
nestedWriterGuard needs no matching change: the subagent a tick spawns for
its own search is routine-explorer, already on the read-only list.
EnterWorktree allow guard #
Claude Code's own permission check on EnterWorktree asks unconditionally for
any path outside .claude/worktrees/, and this machine lays worktrees out at
<repo>/.worktrees/<name> instead, so every /pickup prompts. A
permissions.allow rule in settings.json can't override that — the tool's
own check wins — but a PreToolUse allow decision from chook can, because the
hook's decision races ahead of the interactive prompt.
chook grants that allow back for the one shape that's safe to grant
unconditionally: path has to resolve, against cwd, to a directory that
already exists on disk, is a genuine linked worktree (a .git file, not a
directory — the same test the write-time worktree guard uses), sits directly
under a .worktrees/ folder, and belongs to a repo whose root declares tracks
in tracks.json. Anything short of all four — a path that doesn't exist,
a directory standing in for a worktree without actually being one, a
.worktrees/.. spelling that collapses back onto the primary checkout, or a
repo that never opted into the track layout — falls through to the normal
prompt rather than being allowed.
EnterWorktree has no dedicated field chook can match a config rule against,
so a bare tool = "EnterWorktree" allow rule in chook.toml would allow
every call unconditionally — that's why this is a guard function rather
than a config rule: only a guard can check that the path exists and that the
repo actually declares tracks. A config ask or deny rule aimed at
EnterWorktree still takes priority over the guard's auto-allow, the same
way the branch guard defers to a config ask rule that also matches.
enterWorktreeGuard() in chook.mjs is the entry point. Run
node test-enterworktree-guard.mjs to exercise it.
Spawn tool name: Agent and Task #
Claude Code renamed the subagent-spawn tool from Task to Agent, and the
tool_name in the hook payload followed. Every spawn rule — the foreground-spawn
deny, the worktree-isolation deny, the Explore/Plan allows, and the spawn
side of the worktree guards — is written against Task, so all of them went
dead at once. The
failure was silent by nature: a rule that stops matching looks exactly like a
rule with nothing to say, and foreground spawns the config explicitly blocks just
ran.
chook.mjs run now folds Agent onto Task before any matching, so write rules
against tool = "Task" and they apply under either name. node test-writer-guard.mjs pins both, so the next rename fails loudly.
Spawn-brief guard #
chook denies the first Task spawn of a turn that either picks a catch-all
agent or carries a multi-phase brief, once, and the reason text carries the
routing table and the brief-sizing rule. The agent reroutes, splits the brief, or
re-issues unchanged and it passes.
Both failures share one tool call and nothing else looked at it. A brief with
four phases becomes a 20–30 minute subagent whose later phases build on earlier
ones nobody reviewed, so a network drop or one wrong turn in phase 1 discards all
of it. And the routing table lived only inside grindDenyReason, which fires
when the agent is being pushed to delegate — not when it is choosing an agent.
Across 29 audited spawns the split was Explore 14, general-purpose 10,
routine-coder 5, routine-explorer 0.
- Catch-all:
general-purpose,claude, or an absentsubagent_type(which defaults togeneral-purpose). - Multi-phase: four or more top-level numbered steps (
1./2)starting a line), or two or more sequencing phrases (and then,after that,once that's done,finally,,next,, …). - Bare
thenis not a sequencing phrase. "If the build fails then report it" is ordinary English, and a guard that fires on single-deliverable briefs is one that gets routed around. - Length is deliberately not a signal. A long brief is usually a well-specified one; denying on word count pushes the spawner toward vaguer prompts, which is the opposite of the goal.
- Both problems are reported in one deny. The guard fires once per turn, so checking routing first and returning early would let a re-issue that fixes only the agent type carry the unchanged multi-phase brief through unexamined.
- Runs after the worktree guards, so a spawn that both lacks a worktree and is oversized reports the missing checkout first — that one stomps a tree, this one only wastes an agent.
- Top-level only, same
agent_id/agent_typetest as the other guards.
routine-coder and routine-explorer are auto-allowed in example.toml
alongside Explore and Plan. Without those rules the cheap specific agents fell
through to the normal permission prompt while the catch-all did too, leaving no
friction gradient toward them. Allow rules run after the guards, so an
auto-allowed agent type with an oversized brief is still denied.
State lives in /tmp/chook-spawnbrief-<session_id> ({fired, promptId}), reset
on each new prompt_id. Run node test-spawn-brief-guard.mjs to exercise it —
most of its cases are false-positive cases, since the guard's value depends
entirely on leaving well-sized briefs alone.
Calibration: the thresholds above were reasoned from the failure mode, not
tuned against real oversized briefs — at the default 256-character audit cap
every stored Task prompt was cut off around 30 words, far too short to tell an
oversized brief from a tight one. Spawn inputs are now audited at 8000
characters, so the log accumulates the briefs the thresholds can be checked
against. Revisit once it has a few dozen real spawns in it.
Retiring guard #
chook denies the first edit of a turn that deletes a declared symbol, once, and the reason text carries the rule: the removed version should be fully gone, not commented out or dual-pathed, and leftover references need a grep before the task is called done. The agent re-issues the identical edit and it passes.
- Fires on
Edit,MultiEdit, andWrite. ForWritethe pre-edit file is read off disk — atPreToolUsetime it is still the old version — so a full-file rewrite that drops a function is caught too. - A symbol counts as removed if it is declared in the old text (
function,class,const/let/var,def,fn,func,type/interface/enum/struct) and appears nowhere in the new text. Names under three characters are ignored — they are noise and ungreppable anyway. - Declarations must start a line (indentation and modifier keywords like
export,pub(crate),async,staticare allowed).type,interface,enumandstructare ordinary English words, so an unanchored match read "then type the command" as declaringthe; six of seven sampled prose edits misfired that way. Real declarations start a line, prose mentions don't. - Prose files (
.md,.mdx,.markdown,.txt,.rst,.adoc,.org) are skipped outright — a deleted code fence is not an unfinished migration, and docs are where those English words are densest. A skipped doc edit leaves the guard armed for a later code edit in the same turn. - Only the turn's first removing edit is blocked; every later one passes
silently. The guard rearms on the next
prompt_id. - Top-level only, same
agent_id/agent_typetest as the other two guards. Runs after the worktree guards and before ask rules.
This replaced a UserPromptSubmit hook that spent ~110 words on every prompt to
reach the minority of turns that remove anything. Since a deny is chook's only
channel to the model, delivering the rule at the moment it applies costs one
round trip — but only in the turns where it applies.
State lives in /tmp/chook-retiring-<session_id> ({fired, promptId}), reset on
each new prompt_id.
Run node test-retiring-guard.mjs to exercise it — the guard is only observable
by feeding crafted PreToolUse payloads to chook.mjs run, so the false-positive
surface needs a suite rather than a live session to stay honest.
Timing-race guard #
chook denies the first edit of a turn that adds a timing-sensitive
mechanism — setTimeout, setInterval, setImmediate, process.nextTick,
waitForTimeout, waitForFunction, time.sleep, await sleep, or a
visibilitychange listener — and the reason asks the question the edit skipped:
what is the deterministic signal that the awaited thing happened? Re-issuing the
identical edit passes.
- Only added mechanisms count. An edit near an existing timer, or one that deletes a timer, has nothing to answer for.
- Deliberately excludes plain
addEventListenerandrequestAnimationFrame. Both are ordinary UI code far more often than they are race patches, and a guard that fires on ordinary code gets routed around. - An edit whose comments name a specific OS/hardware/Chromium boundary passes untouched — it has already done what the deny would ask for. A vague "this is flaky otherwise" does not qualify.
- Prose files are skipped. Top-level only. Runs after the retiring guard, so an edit that both removes a symbol and adds a timer reports the removal first.
This is the mechanizable slice of ~/.claude/skills/fsm-pilled/SKILL.md. The
larger part of that skill — scattered booleans, constructor side effects,
implicit ordering — is a design judgment no pattern match sees, and it stays with
the skill's own catalog matching rather than being faked here.
State lives in /tmp/chook-timing-<session_id> ({fired, promptId}), reset on
each new prompt_id. Run node test-timing-guard.mjs to exercise it.
Branch guard #
chook asks before a protected branch (main, master) moves by hand outside
of a normal commit. git push is not gated at all, in any mode — an ask that
converts to a hard deny under CHOOK_UNATTENDED was stopping unattended
sessions mid-work routinely, and the friction outweighed what it caught.
git branch -f(or--force) naming a protected branch asks, since it repoints the branch without a commit.git reset --hardwhile a protected branch is checked out asks; the same command on a wip branch does not, since that's the branch's own business. The checked-out branch is read from the repo the command actually runs in (which means runninggit rev-parse), following a leadingcdandgit -C.- A safe command produces no reason and falls through to the catch-all Bash
allow, so it never prompts. Config
askrules take priority over the guard. - Stateless and not turn-scoped — unlike the five guards above, it has no state
file and fires on every matching command, since a second hard reset on
mainis as consequential as the first.
gitBranchGuard() in chook.mjs is the entry point. Run
node test-branch-guard.mjs to exercise it — the cases run the real binary
against scratch repos checked out on a wip branch and on main, because the
guard's answers depend on live git output rather than on the command text.
Applications guard #
chook denies, outright and in any mode, a Bash command that runs, opens, or
kills the installed Peek app at /Applications/Peek.app. That copy holds the
real user profile — running its binary, opening it, or killing it by name
has contaminated that profile and killed live sessions, and there's no case
where an ask prompt would do better than a flat refusal, since retrying gets
the same deny.
- Any form that names the installed app's own path — running its binary,
open /Applications/Peek.app,pkill -fagainst the path,ls/catinside it — is denied. open -a Peek(with or without.app) is denied.killall Peekandpkillwith a pattern matchingPeekorPeek.appare denied on macOS only. Both match by substring against every running process's command line, so a pattern naming the installed app can't be aimed at just a dev instance — the deny reason points atyarn killinstead./Applicationsis a macOS location, so on every other platform the only Peek such a pattern can match is a dev or test instance and killing it by name is ordinary work. The path rules above stay in force on every platform, since a command written for the other machine can still name the path.- The local packaged build under a repo (
out/mac-arm64/Peek.app/...,out/linux-unpacked/peek) is a dev instance, not the installed app, and is left alone, as is anything that merely mentions the word "Peek" (git log --grep Peek,~/workspace/peek). Matching is case-sensitive onPeek— the repo directory is lowercase. - Stateless and not turn-scoped, like the branch guard above: it has no state file and fires on every matching command.
applicationsGuard() in chook.mjs is the entry point. Run
node test-applications-guard.mjs to exercise it.
State pruning #
The five stateful guards above each write a per-session state file and none of them
deletes it, so the state directory would otherwise gain one file per session
for as long as the machine lives. chook run sweeps it opportunistically:
- A state file untouched for 24 hours is deleted. Every guard already
resets its own state on the next
prompt_idit sees, so losing a file early just resets that guard to zero — the same state a brand-new session starts from. 24 hours is far longer than any single turn runs in practice, so a file that old belongs to a session that isn't coming back. - The sweep itself runs at most once per hour, gated by a marker file's
mtime, so most calls pay nothing beyond one
stat. - A sweep failure (a full or read-only temp directory) is swallowed silently and never turns into a deny or an ask — pruning is never allowed to affect the permission decision.
State files live directly in /tmp by default; set CHOOK_STATE_DIR to point
every guard (and the sweep) at a different directory, mainly useful for tests.
node test-state-pruning.mjs exercises the sweep against a throwaway
directory: a stale file removed, a fresh one kept, and an unwritable directory
that still leaves the call's decision unchanged.
Notifications #
Claude Code's Notification event fires the moment the session blocks on
something. Wired to permission_prompt, chook notify sends a desktop
notification right then — osascript on macOS, notify-send on Linux — the
title carries the project directory, so with several sessions open you can
tell which one is waiting.
There is no timer and no pending state: the event is the "waiting for you" signal, so a notification can neither arrive late nor arrive for a call that was already answered.
Neither binary is guaranteed present — a headless Linux box with no
notify-send installed is a normal, not exceptional, environment. A missing
notifier or a failed spawn is swallowed rather than surfaced as a hook error —
notification delivery never gets to touch a permission decision — but it does
leave a line on stderr so a delivery failure isn't silently indistinguishable
from a delivered notification.
Other notification types the matcher accepts, if you want them: idle_prompt
(input idle for 60s), agent_needs_input, agent_completed, auth_success.
Claude Code's own built-in notification is a separate setting
(inputNeededNotifEnabled); leave it off to avoid a double buzz.
Why not a timer in PreToolUse #
The earlier version armed a 15-second sleep when a tool passed through to
Claude's permission flow and disarmed it from PostToolUse. Both halves are
wrong:
- PostToolUse fires when a tool finishes, not when it is approved. Approve a 60-second build and the "needs approval" notification still arrives 15 seconds in, for a call already running.
- The pending file was keyed by session, not by call. A timer left over from a quickly-approved call woke up 15 seconds later, found the next call's pending file, fired with the old call's text, and deleted the file the live call needed — so the notification you got named something you had already approved, and the call actually waiting never notified at all.
Also, a [[ask]] rule's prompt never notified under that scheme, since it exits
before the passthrough branch. The Notification event covers it, because it is
the same prompt.
chook post still exists as an accepted no-op so that sessions started against
the old wiring don't error on every tool call; the PostToolUse entry can be
dropped from settings.json.
Inspired by #
claude-code-permissions-hook by Korny Sietsma — a Rust implementation of the same idea. chook is a JS port with added interactive review and notifications.