A hook is a shell command CandyCode runs at a lifecycle point, whose exit
code is a verdict. It is the escape hatch for a rule a permission mode cannot
express: "ask me before anything touches production", "block any Edit under
vendor/", "rewrite this tool's arguments".
Hooks come from your hooks.yaml files and from the hooks block of Claude
Code settings files. The files in your home directory are loaded on trust; the
ones that arrive with a repository are not.
| File | Loaded |
|---|---|
~/.candy-code/hooks.yaml |
always |
~/.claude/settings.json |
always — the hooks block only (see below) |
<root>/.candy-code/hooks.yaml |
only if this root is listed under trustedProjectHooks |
<root>/.claude/settings.json and <root>/.claude/settings.local.json |
only if this root is listed under trustedProjectHooks, and the hooks block only |
Honouring a project hook file means running shell this repository's author wrote, every time you open it. So it is opt-in per project root:
{ "trustedProjectHooks": ["/home/you/src/myproject"] }The refusal is not a silent drop — it prints one stderr line naming the
canonical path to add, at most once per path per process. (Once, because an
interactive launch builds two hook managers: Chat's own chain and the engine
backend's. A notice you meet twice a run for doing nothing wrong is a notice you
learn to scroll past.)
The candidates are de-duplicated by real path, because they are not
always distinct files: run candy-code in your own home directory and both
hook tiers name ~/.candy-code/hooks.yaml. Loading it twice would trip the
already-registered guard and kill the launch over a collision that does not
exist. See PERMISSIONS.md for
the properties this trust key shares with the other three.
The .claude sources are read for one key: hooks. Those files also carry
permissions, env and model — none of it is looked at. candy-code's
layered settings authority owns those surfaces, and a second loader reading
them from a different file would fork that authority into two precedences over
one config. Everything outside hooks is simply not this loader's subject.
Inside hooks, Claude Code's shape is nested where hooks.yaml is flat:
{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":60}]}]}}Each inner hook flattens into one hooks.yaml-shaped entry and runs through
the SAME validator — event-name check, matcher compilation, positive-finite
timeout — so the file format section below applies to it, with the one
exception that this format's two extra keys are stamped onto the row only
after that validator has passed it. Names are
generated as cc:{scope}:{event}:{index} (CC entries carry no name), where
the scope says which tier the file was loaded from: user for
~/.claude/settings.json, project for a trusted project's
.claude/settings.json, local for its .claude/settings.local.json. The
cc: prefix means these entries can never claim a hooks.yaml guard's name,
and the scope segment means two files in DIFFERENT tiers that name the same
event at the same index no longer collide; a hand-written hooks.yaml entry
that claims one of these generated names still does, and that collision
refuses the launch exactly as a native name collision
does. Differences that are this loader's own:
typerunscommand,httpandprompt. CC's neweragentandmcp_tooltypes have no verdict shape for this chain to read — a script answers with an exit code, an HTTP hook answers with a status and a JSON envelope, a prompt hook answers with the model's own singleok/reasonJSON object, and those two answer with neither; an entry with such a stringtypeis SKIPPED and RECORDED — it contributes no guard, and the launch notice names the type, so nothing is skipped quietly. Atypethat is missing or not a string is not a dialect this loader recognises at all and still refuses the launch by name. Anhttpentry carries the SAME trust as acommandentry from the same file, and itsurlis refused at load when this host will not dial it — see "HTTP hooks" below. So does apromptentry, and what the model is shown beside the hook's own prompt is fenced as untrusted data before the call — see "Prompt hooks" below.- An entry may carry ten keys:
type,command,timeout,statusMessage,async,url,headers,allowedEnvVars,promptandmodel. An entry carrying any other key — CC grows them,ifandonceare real today — is skipped whole and every off-dialect key is named on the same launch notice, never run silently. The two beyond the native three have nohooks.yamlequivalent to refuse them, so each lands on a native slot rather than being dropped:statusMessagebecomes the entry'sdescription— the same text/hooksshows for ahooks.yamlguard, which is what a spinner label is for. AstatusMessagethat is not text is refused by the same validator that refuses a non-textdescription.async: truemakes the entry advisory. Claude Code runs such a hook beside the tool call, so its verdict never gates anything. candy-code has no detached hook runner, so the script still runs inline and still inside itstimeout— what it gives up is the power to stop the call, including at exit2. A non-booleanasyncrefuses the launch: this flag decides whether a hook may block, so it is not a value to guess at.
- And an entry from this file format is read through Claude Code's exit-code
dialect, not the table below — see "Claude Code's two codes" there. Each
flattened row carries a
dialectstamp for exactly that reason; ahooks.yamlentry cannot spell the key, so the stamp is also the proof of which file a row came from. matcheris taken as a regular expression, exactly ashooks.yamltakes it (CC's own*/empty spelling means "every tool" and flattens to.*).- Relative commands are NOT anchored to the settings file's directory: Claude Code runs hooks with the project as cwd, and candy-code's script hooks already spawn there.
- Events candy-code has no case for are recognised and SKIPPED —
Notificationand every other unknown name alike. The hook chain has no such event, and widening it is a separate decision; refusing a whole launch over one unmappable name in a foreign vendor's file gave that file the blast radius of an outage. Each skip is recorded, and one aggregate launch notice names the skipped events, entry types and off-dialect keys together with the number of distinct hook groups they came from (a group carrying two different skips is one group that contributed no guard) and the files those groups belong to.
hooks:
PreToolUse:
- name: confirm-deploy # optional; defaults to `command`
type: command # optional; `command` is the default
matcher: '^Bash$'
command: ./hooks/confirm-deploy.sh
description: Ask before anything touches production
disabled: false # optional; true keeps it out of the chain
timeout: 30 # optional seconds; default 60 (hooksDefaultTimeoutSeconds)
unattendedAsk: false # optional; true keeps this ASK live under bypass-permissions
- name: ask-the-gate
type: http # the second kind; `command` is the default above
matcher: '^Bash$'
url: https://gate.example/api/candy-code-hook
headers: # field names, values may read $VAR from
x-trace-id: $HOOK_TRACE # allowedEnvVars only (8-space children
allowedEnvVars: [HOOK_TRACE] # are header fields, not entry keys)
- name: ask-the-model
type: prompt # the third kind; the model's reply IS the verdict
matcher: '^Bash$'
prompt: Does this command look destructive? $ARGUMENTS
model: claude-haiku-4-5 # optional; honoured only where the title backend can serve it
PostToolUse:
- matcher: 'Read|Write/Edit'
command: ./hooks/log-touch.shThose thirteen are the only keys an entry may carry. An unrecognised key is
refused rather than ignored. Which of them one entry may use turns on its
type: a command entry has no url, headers, allowedEnvVars, prompt
or model; an http entry has no command, prompt or model; and a
prompt entry has no command, url, headers or allowedEnvVars — a
stray key of another kind is refused the same way, because a row that asks
for two runners is not a row to guess at. A user-tier file's relative ./hooks/... command
resolves against ~/.candy-code/ — the file's own directory — not the repo you
open; so does a bare hooks/... spelling, but only when a real file exists
under ~/.candy-code/ (the existence gate means a cloned repo cannot plant the
script and take over the guard, and a command naming nothing keeps running
exactly as typed). Project-tier files keep repo-relative commands.
name matters because HookRegistry keys hooks by name: without it, two
entries sharing a command on one event silently collapse into a single
registration.
unattendedAsk: true is the entry's opt-in to the exit-3 promise below:
bypass-permissions will not auto-answer this hook's ASK — a headless run
fails closed to a refusal (the refusals row carries the unattended
qualifier) and a run at a terminal is put the real question. A non-bool value
is refused like disabled's, and the key is inert on a disabled: true
entry: an entry that never joins the chain never asks.
This is a security surface, so every "we could not use what you wrote" case stops the launch with exit 2 rather than degrading to a shorter hook chain. That covers a YAML syntax error, an unknown event name, an uncompilable matcher, and an unrecognised entry key. It used to do the opposite — all three came back as "no hooks", with nothing printed anywhere.
A guard silently missing from the chain is the one failure mode a guard must not have, and it is invisible exactly when it matters: the tool call the hook existed to stop is the one that runs.
Only a file that is not there is a no-op. A path that exists and is not a readable regular file — a directory, a dangling symlink — throws, because "not a hook file" is not the same as "no hook file". And a path with an unsearchable ancestor directory also refuses the launch: whether hooks are configured there is unknowable, and reading unknowable as absence would run a shorter guard chain and say nothing.
The matcher is a PCRE fragment, matched case-insensitively against the tool
name. You write the pattern without delimiters; HookConfig::pattern()
picks the first of / # ~ % ! @ ; : | + = that your pattern does not contain.
The subject a matcher is tested against is normally the frame's tool name, with
one widening: for a deferred mcp_call frame the registry also tests the wire
name the call's server/tool arguments resolve to, so a matcher naming
mcp__git__* fires whether the server is bridged or dispatched. The payload
never changes — tool_name stays mcp_call — only the matcher's view widens.
That is why matcher: 'Read|Write/Edit' works. Under a fixed / delimiter it
compiled to /Read|Write/Edit/i, whose delimiter closes at the slash — a valid
regex that made bin/candy-code exit 2 over a slash. Picking an absent
delimiter is both simpler and safer than escaping, which has to reason about
already-escaped \/ and gets it wrong at the edges. The same wrapping is what
makes the match-all the empty string: '' holds no delimiter either, so it
compiles to //i — the i is the case-insensitive modifier, and between the
two delimiters there is no pattern at all, which PCRE reads as matching every
subject. The glob instinct is the one spelling that does not survive the load:
matcher: '*' becomes /*/i, PCRE refuses it because the quantifier has
nothing to repeat, and the loud half of the rule above turns that into a refused
launch rather than a guard that fires on nothing. Omitting the key outright is
the third route, and it lands on .*, which matches everything the same way.
One definition serves the config's own validation and both matchers
(HookRegistry::matcherMatches() and HookDispatcher::matcherMatches()), since
a pattern validated under one delimiter and matched under another is a hook that
loads and never fires.
A pattern can also compile fine and still fail to evaluate: preg_match()
returns false — not 0 — when PCRE exhausts pcre.backtrack_limit or
pcre.recursion_limit on the subject, and '(a+)+$' against a long enough tool
name does exactly that. HookRegistry::matcherMatches() reads that as
matching: the hook runs and gets to deny, because treating an
unevaluable guard as satisfied is the one failure mode a guard must not have.
The pattern and the PCRE error are kept on HookRegistry::matcherFailures(),
and the first failure of each pattern is announced once through the same
per-turn notice drain /notices reads — announced, never printed
raw, because the match happens mid-frame where the renderer owns the screen.
HookRegistry::register() keys by event + name and overwrites, so an entry that
reuses a registered hook's name on that hook's own event would uninstall it —
a config file switching a guard off by naming it. HookManager::loadEntries()
refuses that. It also makes the outcome independent of load order: a project file
cannot disarm a hook you wrote in your home directory by reusing its name, in
either registration order.
The name to avoid is the one name() returns, not the class name. This trips
people up because two of the three built-ins are not named after their file:
| Class | name() returns |
event() returns |
|---|---|---|
BuiltIn\ProtectFilesHook |
protect-files |
PreToolUse |
BuiltIn\ConfirmRemoveHook |
confirm-rm |
PreToolUse |
BuiltIn\AuditHook |
audit |
PostToolUse |
So name: confirm-remove is accepted — it collides with nothing, and a hook
file using it gets a second, additional hook rather than the refusal its author
probably expected. name: confirm-rm on PreToolUse is the entry that is
refused.
And because the key is event plus name, the same name can be free on one
event and taken on another. Measured on this tree, with registerBuiltIns()
already run:
name: |
on event: PreToolUse |
on event: PostToolUse |
|---|---|---|
protect-files |
refused | accepted |
confirm-rm |
refused | accepted |
confirm-remove |
accepted | accepted |
audit |
accepted | refused |
audit is the row worth reading twice: AuditHook is a PostToolUse hook, so a
PreToolUse entry called audit does not displace it and is not refused.
src/Hooks/HookEvent.php defines sixteen:
| Event | Fires | Dispatched from |
|---|---|---|
PreToolUse |
before a tool runs — the one that can stop it | Runtime::gate(), Chat::gateToolCall(), McpServeHost::toolsCall() |
PostToolUse |
after a tool ran, in provider order | Runtime::settle(), Chat::applyPostToolUse() |
Stop |
the agent answered without calling a tool and is about to stop — the one that can keep it going | EngineBackend::runTurn() |
SubagentStop |
a sub-agent (a Task run, or a workflow stage's agent) is about to stop |
EngineBackend::runTurn() |
SessionStart |
the first prompt submitted into an empty history | Chat::dispatchTurnHooks(), SessionHost::fireTurnHooks(), NonInteractive::fireTurnHooks(), BackgroundSessionRunner::fireTurnHooks() |
SessionEnd |
the process is exiting: the TUI closed, or a -p run printed its answer |
NonInteractive::fireSessionEndDetached(), NonInteractive::fireSessionEnd() |
UserPromptSubmit |
you submitted a prompt | Chat::dispatchTurnHooks(), SessionHost::fireTurnHooks(), NonInteractive::fireTurnHooks(), BackgroundSessionRunner::fireTurnHooks() |
PreCompact |
before a compaction condenses the history — the one that can skip it | Chat::preCompactGate(), EngineBackend::runTurn() |
PostCompact |
after a compaction was applied | Chat::postCompactCmd(), EngineBackend::runTurn() |
TeammateIdle |
a teammate asked the board for its next task — the Team tool's claim with no task |
TeamManager::handleTeammateIdle(), TaskList::dispatchTeammateIdle() |
TaskCreated |
before a task joins a team's board (Team's add) — the one that can refuse it |
TaskList::addTaskIfAbsent() |
TaskCompleted |
after a teammate completed a task (Team's complete) |
TaskList::completeTask() |
StageStarted |
before the workflow engine dispatches one round of one stage — round counts from 1, always 1 without loop: |
WorkflowEngine::announceStageStarted() |
StageComplete |
a workflow stage settled without failing — status carries completed, or skipped for a when: clause that declined it (the ONLY event a skipped stage raises, with round 0) |
WorkflowEngine::announceStageComplete() |
StageFail |
a workflow stage settled as a failure — the engine's own fail-fast predicate, exactly one event per settled stage | WorkflowEngine::announceStageFail() |
WorkflowComplete |
a workflow run reached a natural terminal (completed or failed, a pre-flight refusal included) — paused and cancelled runs raise nothing, they are resumable |
WorkflowEngine::announceWorkflowCompleted() |
The three team rows are the ones raised outside a tool call and outside a turn,
so they do not go through HookManager: TaskList raises them through a
HookDispatcher over the launch's own registry. Bootstrap::hooks() hands
HookManager::dispatcher() to TeamManager::useLaunchHooks(), and every
Team that manager builds — the Team tool opens one per call — passes it to
its TaskList, so an entry in hooks.yaml reaches a team's board the same way
a PreToolUse entry reaches a tool call. See The team events below.
The four workflow rows are raised by WorkflowEngine on the same guarded-dispatch
idiom: whatever HookDispatcher the engine's host hands it, the engine announces
every stage round and every natural run terminal through it and discards the
verdict — all four are observe-only, and an unarmed engine raises nothing.
(HookDispatcher also carries a method for Stop, SubagentStop and
SessionEnd; nothing calls those — the live chain dispatches all three
through HookManager, see The stop events below.)
What a block (exit 2) does depends on the event, because for some of them the action has already happened:
-
PreToolUse,TaskCreated— stops the action outright, and stderr goes back to the agent. -
Stop,SubagentStop— the action is the agent stopping, so a block keeps the turn going: the reason goes back to the agent as its next prompt, at most eight times a turn. See The stop events below. -
PostToolUse— too late to stop, so it withholds the output instead: on both tool paths (Runtime::settle(), andChat::applyPostToolUse()on the dormant Chat path) the model and the UI get[output withheld by PostToolUse hook "<name>": <stderr>] The call ran; its output is not shown.in place of the tool's output. The image and diff are dropped with it,isErrorkeeps whatever the tool reported, and a permitting hook's note from earlier in the same chain is discarded with the verdict. A PreToolUse note is kept, because it was written before the output existed. Every verdict that does not permit counts: exit 1 or 2, any other non-zero exit, a timeout, an exit-3 ask (there is nobody to ask after the call ran). A hook that throws counts too: it has vetted nothing, and the hooks queued behind it never run, so its reason readshook failed: <exception class>: <message>. APreToolUsehook that throws is contained the same way: the call is refused (Hook denied: hook failed: ..., naming the hook), never runs, and the turn continues with that refusal as the tool result. On the Chat path a failed call's withheld text stays in its error slot, and the hook is shown the error text, asRuntimeshows itToolResult::content().<name>is the hook that refused, as the registry recorded it while running the chain — never what the hook's own result claims (HookResult::$refusedBy, or the first asker for an ask). It is the entry'sname:, which defaults to its wholecommand, so it is clipped to 60 characters with control characters blanked. A refusal no single hook owns — a chain that ran out of its time budget, or kept rewriting — reads[output withheld by the PostToolUse hook chain: <reason>]instead of guessing a name. -
TaskCompleted— too late to stop: the completion stands, and is marked contested on the board (listshowscompletion contested). -
TeammateIdle— the teammate is handed no task this time; itsclaimsays a hook held the next task back, with the hook's stderr as the reason. -
SessionEnd— nothing is left to stop, so the reason is one line of output (stderr for a-prun, the TUI log once the chain has been handed to a daemon, see below) and the exit is unchanged. -
PreCompact— skips the compaction: the history is left as it was, and stderr reaches you only. See The two compaction events below. -
PostCompact,SessionStart— stderr reaches you only; there is no agent action to feed it to. (SessionStartis elaborated under The two turn events below, including where a shipped block reason actually surfaces.) -
UserPromptSubmit— discards the prompt entirely; nothing goes to the agent.
When Runtime dispatches a same-turn batch of parallel-safe tool calls, every
member of the group is forked before any of them reaches PostToolUse. So a
hook here that mutates shared state — writes a file, touches a database — no
longer has that mutation observable by a later sibling in the same group, the way
it would under sequential dispatch. The number of invocations and their order are
unchanged; only the interleave point moved.
The safety rule that keeps concurrency invisible in tool results covers tools.
It cannot cover a hook body you wrote. Set
CANDY_CODE_DISABLE_PARALLEL_TOOL_CALLS=1 if your hooks depend on the
sequential interleave.
In the TUI, Chat::dispatchTurnHooks() is the only production dispatcher for both, reached
from submitDraft() on every prompt, or from scheduleParkedCompaction() instead
when the automatic 85% compaction tier parks the prompt behind a model-written
summary. A session driven without a screen (Host\SessionHost) fires the same
two events from SessionHost::fireTurnHooks(), through the same
Host\TurnController logic, so the order, the notes and the refusals below hold
there too. Each submission takes exactly one of the two, and a parked prompt is
judged when it is parked — so a block stops it before the summarization is paid
for, and a note is written immediately ahead of the echoed prompt, where it rides
the turn that goes out once the summary lands. Their verdicts behave differently
from the tool gates:
- Fired gate-first.
UserPromptSubmitruns beforeSessionStart, so a SessionStart script never spawns just to learn its prompt was blocked. The notes are inserted in the opposite order — session note, then prompt note, both asrole: systemhistory messages immediately before the user's line. - A
UserPromptSubmitblock discards the prompt. Nothing is sent, the draft stays in the input box, and the reason lands in the transcript as aMessage::system()line. That is a documented divergence from the strictHookEvent::stderrToUserOnly()reading:tests/Cli/StderrEmitterCensusTestpinsChat.php's emitter counts, so the transcript seam is the surface that answers "where does the user see it". And the history that refusal commits is the pre-compaction one — the notice is appended to$this->history, while a rewrite the automatic tier adopted for this same submit lives only in the local thatdispatchTurn()is handed — so a compaction that had already bought space goes out with the prompt by design instead of being persisted, and the tier re-runs on the next submit. - A
SessionStartblock stops nothing. PerstderrToUserOnly()the session continues, the hook's note is discarded outright, and only the reason appears in the transcript. - An
ASKfails closed on this path. The turn dispatch has no approver UI in front of it, soChat::turnHookRefusalReason()treats an ask as a block — the prompt is not sent rather than silently permitted. - The SessionStart gate is
count($this->history) === 0at the dispatch point — a once-per-empty-history gate, not once-per-session:/clearre-opens it, whileresumeand the palette's new-session path never re-fire it, andcompactis unreachable there. The method's own docblock records this as a known gap rather than papering over it. - Context is smuggled through the tool-shaped
HookContext.toolNamecarries the event name — the only slotHookRegistry::findMatches()tests —toolInputis JSON ({"prompt": …, "source": "startup"}forSessionStart,{"prompt": …}forUserPromptSubmit), andmodel/providerare empty. Amatcher:written against tool names will not fire on these events unless it names the event.
Hook notes go onto history, never into the prompt assembler — role: system
is the non-spoofable operator channel — which is why wiring these two events
moves no prompt golden.
EngineBackend::runTurn() fires Stop when the model answers without calling a
tool — the step that would end the turn — and SubagentStop instead when the
turn is a delegated run: a Task sub-agent, or an agent a workflow stage runs.
It runs in the turn's own process (the forked turn child on the TUI path), only
when a hook for the event is wired, so an unhooked turn ends exactly as before.
- A block keeps the turn going. Any verdict that does not permit — exit
1or2, an ask (there is nobody to ask), a timeout, a hook that throws — appends the hook's reason as the next prompt,Stop hook "<name>" did not let you finish yet: <reason>, and the turn takes another step. The answer it refused stays in the history ahead of it. - Bounded three ways. At most eight continuations a turn
(
HookManager::MAX_STOP_CONTINUATIONS), each one a step under the turn's step ceiling, and none once the spend cap is reached or a soft cancel is pending. Past any of them the turn ends on its last answer. "continue": falseends it. A JSON envelope with"continue": false(see JSON on stdout) ends the turn, as it was about to, and itsstopReasoncloses the reply:[turn stopped by hook "<name>": <stopReason>].- Context.
toolNamecarries the event name (write thematcher:against it), andtoolInputis JSON{"stop_hook_active": …, "last_assistant_message": "<the answer>"}—stop_hook_activeistrueonce a block has already kept this turn going, so a hook can let go.SubagentStopaddsagent_idandagent_type.
SessionEnd fires once as the process exits. The TUI hands the chain to
NonInteractive::fireSessionEndDetached() after its program loop returns
(bin/candy-code, with the session's own chain, id and root; toolInput
{"reason": "prompt_input_exit"}), and a -p run calls
NonInteractive::fireSessionEnd() directly once its answer is printed
({"reason": "other"}) — never from the TUI's quit paths, which only leave the
loop. A -p caller that supplies its own backend owns its session's end, so
nothing fires there. The session server (serve) does not fire it yet.
The TUI's dispatcher does not wait for the chain. By the time it runs, the alt
screen is left and the prompt looks finished, and a chain is bounded by the
sum of what its entries asked for — a caliber finalize at the sixty-second
default held the shell for a minute after a /exit that looked instant. So the
chain goes to a detached process (a Support\Daemonize daemon) that outlives the TUI and
runs to the deadlines its own hooks were configured with: what goes away is the
waiting, never the hook. It writes to the TUI log rather than your terminal, and
the two places it cannot be handed off — no log to write to, or a build that
cannot daemonize — keep the foreground behaviour of a -p run instead of dropping
the hook. This is why keepWarm daemons and /bg sessions are unaffected: they
were never waited on either.
Chat::preCompactGate() fires PreCompact for every compaction that would
condense the history through the TUI: /compact (trigger: manual), and the
automatic 85% tier when it parks a prompt behind a model-written summary
(trigger: auto) — or, ahead of need, when the 70% tier requests that summary
in the background (trigger: auto too; the 85% tier that later splices it in
does not ask again). Chat::postCompactCmd() fires PostCompact once such a
compaction has been applied. Inside a turn, EngineBackend::runTurn() fires
PreCompact (trigger: auto) before the model's own Prune call changes what
it is sent — a block refuses the call, and the model reads why — and around
the engine's step-level summary, the one it writes when a step's request is
over budget: PreCompact before the summary is requested (a block skips it,
and the step's request goes out as it stands), PostCompact once it is
applied. The automatic tier's heuristic route (no summary model configured)
does not fire them yet.
- Never on the render loop. A wired
PreCompactchain runs inside the compaction's own Cmd — before the summarization request is sent, so a block costs nothing — and a chain with a script hook in it runs in a forked child, the way the turn events do, so the screen keeps painting. With noPreCompacthook wired,/compactbehaves exactly as before. - A
PreCompactblock skips the compaction. Nothing is condensed and the transcript saysCompaction skipped: PreCompact hook blocked it (<reason>).On the automatic tier your prompt still goes out, against the uncompacted history. AnASKfails closed, and a hook that throws — or a forked child that reports nothing — counts as a block. - A permitting
PreCompacthook's note steers the summary. Its stdout is sent to the summarising model beside/compact <focus>'s focus text; it is not written into history. PostCompactis observe-only. The rewrite already happened, so neither its exit code nor its stdout is read back — use it for side effects such as logging or archiving the summary.- Context.
toolNamecarries the event name (write thematcher:against it), andtoolInputis JSON:{"trigger": …, "custom_instructions": "<the /compact focus>"}forPreCompact,{"trigger": …, "compact_summary": "<the summary rows the model now reads>"}forPostCompact.
A team's task board (the Team tool, see
AGENTS_AUTHORING.md) raises three events, in whichever
process runs the Team call — the forked turn child on the TUI path, or a
background teammate's own session:
TaskCreatedfires onadd, before the task is stored. A block refuses it: nothing is stored, and theaddfails witha TaskCreated hook refused "<title>": <stderr>.TaskCompletedfires once acompletehas landed. A block cannot undo it; the task is marked contested.TeammateIdlefires when a teammateclaims without naming a task, before the next task is picked. A block hands it nothing this time.- Context.
toolNameisTaskList(write thematcher:against it), the session id is the team id, andtoolInputis JSON:{"task_id", "task_subject", "team_name", "teammate_name"}for the two task events (teammate_nameis the claimant,nullfor a task nobody holds yet),{"team_name", "teammate_name"}forTeammateIdle. Hooks run in the launch's project root.
The workflow engine (the /workflow command and the Workflow tool, see
WORKFLOWS.md) raises its stage-lifecycle events into the same
chain while a run is live. All of them are observe-only: the verdict a hook
returns on these events is discarded, so a hook can watch a run but cannot
block or reshape one — and an engine built without a hook chain raises nothing
at all.
StageStartedfires before each round of a stage is dispatched — round one for a plain stage, the round number for each round of aloop:. A stage skipped by itswhen:clause never raises it. Atype: mapstage raises it once per round like any stage: there are no per-item or per-step events, by design, so a thousand-item map does not raise thousands of hooks.StageCompletefires when a stage settles without failing. It is the only announcement a skipped stage gets, and on a skip theroundreads zero: no round ever ran. On a loop it fires once, after the last round settled.StageFailfires exactly once when a stage settles as a failure, with the reason carried inerror.WorkflowCompletefires once per run at a natural terminal: completed or failed, a pre-flight refusal included. A run that pauses or cancels raises nothing — the resumed run announces its own terminal when it finishes. Acache:stage carried from a record raises nothing either: no dispatch happened. Nor does a plan the pre-run lint refuses (/workflow run, theWorkflowtool andcandy-code workflow runall lint first): it never reaches the engine. A budget stop (config.maxTokens/maxCost) is a pause, so it raises no terminal either, and a stage aWorkflowtoolresumeFromcarries from its record raises nothing. A run's announcements (announce:lines and the engine's truncation, casualty, budget and ceiling notices) are not hook events: they rideWorkflowResult::$announcementsand the engine's announcement sink.- Context.
toolNameisWorkflow(write thematcher:against it), the session id is the run's stamped identity (the workflow's name plus the mint's suffix), andtoolInputis JSON:{"workflow", "stage", "round"}forStageStarted;StageCompleteadds"status"andStageFailadds"status"and"error"; the terminal carries{"workflow", "status", "stages", "totalTokens", "totalCost"}. Hooks run in the launch's project root.
Two tool-call facts about stage agents belong here too. A schema'd stage
agent's StructuredOutput call — the tool call that hands in its structured
answer — bypasses the whole PreToolUse chain (and the permission gate): it
is the run's answer, not an action, and it is matched by tool instance, so a
same-named user or MCP tool is still hooked (see
WORKFLOWS.md).
And a Workflow-tool parallel agent that runs forked (because none of its
tools could ask permission) cannot relay a question: if a PreToolUse script
answers ask for one of its calls, that call fails closed — refused, and
the agent carries on — rather than running unasked.
src/Hooks/ScriptHook.php:
ScriptHook::execute() resolves the exit code with a four-arm match: 0,
3, 4, and default. (No line number here on purpose — the one that used to
be printed, line 181, had drifted by more than a hundred lines by the time
anybody checked it.)
| Exit | Verdict | stdout means |
|---|---|---|
0 |
allow | a model-visible note, capped at 10,000 bytes — see below |
3 |
ask | the question put to the user, clipped at 16 KiB |
4 |
modify | a JSON object replacing the tool's arguments, refused over its ceiling rather than clipped |
1, 2, or any other non-zero |
deny | — (stderr is the reason, clipped at 16 KiB; stdout is discarded) |
Where an exit-0 hook's stdout goes. Unless it is a JSON envelope (see
JSON on stdout), ScriptHook::execute()'s EXIT_ALLOW arm
hands it to ScriptHook::allowOrEnvelope(), which returns
HookResult::allow('', HookContextFiles::bound($output, HookResult::MAX_ADDITIONAL_CONTEXT_BYTES)) — the message stays empty, and the
stdout travels in the third payload channel, additionalContext. It is the
model-visible one, and HookRegistry::executeHooks() collects it across the
whole chain: every hook that ran contributes its note, notes are joined with a
blank line and re-bound through the same cap on every re-scan pass, and the
total is set onto the settled permitting verdict with
HookResult::withContextSet(). A settled ASK carries the collected notes
through the user's answer (HookManager::resolveAsk()); a hard DENY returns the
blocking verdict alone — the chain's notes die with the call they were collected
for.
Where the note then lands depends on the event:
PostToolUse— both live tool paths append it to the model-visible tool result:Runtime::settle()through the existingRuntime::annotate()seam,Chat::applyPostToolUse()onto whichever half (result or error) carries the body. An empty note returns the result byte-identical, so a chain that printed nothing cannot alter any payload, wired or not. This applies only when the chain permits. A refusing chain withholds the output on the engine path instead (see what a block does, above).PreToolUse— WHAT THIS SAID: that neither live gate consumes a permitting verdict's note, that both read onlymessageandmodifiedInput, and that "a note meant for the model belongs on aPostToolUsehook". WHAT IS TRUE NOW (since9d81a6823):Runtime::gate()returns the collected note as a fourth slot andChat::gateToolCall()as a fifth, and both live paths append it to the model-visible tool result exactly the wayPostToolUsedoes —Runtime::settle()through the existingRuntime::annotate()seam,Chat::applyPostToolUse()through its Chat twinChat::withAppendedModelNote()onto whichever half (result or error) carries the body. The model-visible bytes areresult\n\npre\n\npost, and that order is deterministic by construction rather than by timing: each consumer CAPTURES thePostToolUseverdict before appending anything, so the post chain still observes the RAW tool output — a pre-note is model-visible context, never the tool's own stdout — and only then are pre and post appended, in that order. The byte-identical discipline is the same on both halves of the pair: on an empty noteRuntime::annotate()is never called andChat::withAppendedModelNote()returns the instance untouched, so a chain that printed nothing cannot alter any payload, on either event. What the old sentence still gets right:denyandaskspeak throughmessage, interpolated into"Hook denied: …"— which is why the deny reason and the ask question reach the model — andmodifiedInputis the rewrite channel; and a hard DENY pins the note slot to''on every gate arm, so a blocked call carries no note at all, while a settled ASK carries the chain's notes through the user's answer. APreToolUsehook's stdout therefore reaches the model today: pick the event by what the hook needs to OBSERVE, not on the assumption that onlyPostToolUseis wired.
How much a hook may say, per exit code. Measured through
HookManager::preToolUse() with a 200,000-byte payload:
| Exit | What is bounded | Bound | Over the bound |
|---|---|---|---|
0 |
the note (additionalContext) |
10,000 bytes | UTF-8-safe head kept, plus a marker naming both figures and the file where the full output was retained |
3 |
the question | 16,384 bytes | clipped, with a marker naming both figures |
4 |
the rewrite (modifiedInput) |
the larger of 16,384 bytes and the byte length of the arguments it replaces | denied, naming the size and the ceiling |
1/2/other |
the deny reason | 16,384 bytes | clipped, with a marker |
A rewrite is refused, never truncated, and the two are not
interchangeable: a truncated rewrite is invalid JSON, rewrittenArgs() reports
that as null, and every consumer then runs the original arguments — the one
outcome a rewriting hook definitely did not ask for. The ceiling tracks the call
because a sanitiser that edits the file_path of a 300 KB Write has to print
the body back; a flat cap would break that outright.
Do not read 1 and 2 as two different denials. They land on the same
default => arm and produce the same HookResult::deny(). Measured, running one
ScriptHook per code: 1, 2, 5 and 7 all come back with
permitsExecution() === false and a message that differs only in the digit of
the "Hook exited with code N" fallback — and even that difference disappears
the moment the hook writes anything to stderr, since the arm is
$errors ?: "Hook exited with code $exitCode".
HookDispatcher does carry a notion of a non-blocking deny, keyed off an
[exit-1] message prefix. It is not reachable from here. Its own class
docblock records that no shipped HookInterface implementation emits that
prefix — not ScriptHook, not any BuiltIn/*Hook —
so everything that fails to permit execution resolves to exit code 2. A
hooks.yaml hook cannot select the non-blocking path, and it should not try to
by printing the marker itself — see the first bullet below.
0/3/4 are numbered the way they are because 0/1/2 were already
HookDispatcher's tested contract; ask and modify took 3 and 4 rather than
2 and 3. Quietly redefining 2 would have turned every existing "exit 2 to
block" hook into a prompt.
Notes that matter in practice:
- Do not try to reach the non-blocking path by printing
[exit-1]yourself. Only the dispatcher path strips that prefix. The live gates (Runtime::gate(),Chat::gateToolCall()andMcpServeHost::toolsCall()) quote the deny message verbatim into the tool result the call is answered with — the model's transcript for the first two, the MCP wire result onmcp serve— so a hook that emitted the marker would leak it into the transcript rather than being treated as non-blocking. - Exit 3 with no stdout falls back to the hook's
description, then to a generic question. A prompt with an empty body is unanswerable, and defaulting to allow or deny would make silence mean something the hook never said. - Your exit-3 question is asked every time. candy-code remembers two kinds
of approval: a Task spawn approved once in a turn is not re-asked for the same
agent in that turn, and
Chat's "allow always" reply skips later prompts for the same call. Both stand in for the user only when the permission gate was the only hook that asked.HookRegistry::executeHooks()records the name of every hook that returned an ask on the settled ASK (HookResult::$askedBy), overwriting anything a hook's own result carried, and the gate's name is reserved. A question your hook asks is about this call's content, so no earlier approval answers it. Underbypass-permissionsthere is a per-hook opt-in: a hook whose name is rostered viaHeadlessPermissionPrompt::requireUnattendedAnswer()keeps that promise even in bypass mode — with no terminal it fails closed to a refusal (the row carries the unattended qualifier), at a terminal the real question is put; un-rostered ASKs are answered allow by the operator's standing bypass consent. - Exit 4 whose stdout is not a JSON object is downgraded to a DENY, never to
an allow: a hook that meant to rewrite dangerous arguments and failed must not
have the original arguments run in its place. A JSON list or scalar is
rejected too. The test is on the opening brace of the text, not on
array_is_list()of the decoded value, because PHP's decoder throws away exactly the distinction being made —{}(run with no arguments, a deliberate rewrite) and[](a positional array the consumers cannot use) both decode to[]. - A hook that could not run denies.
proc_open()refuses acwdthat does not exist, so a mistyped--rootused to turn a denying hook into an allow. The hook now inherits the process directory rather than not running.
Everything above is the native table, and it is the table a hooks.yaml
entry gets. An entry that arrived from a .claude/settings*.json is read
through the shell that wrote it instead (ScriptHook::DIALECT_CLAUDE, stamped
by the loader):
0proceeds, exactly as above — including a JSON envelope on stdout, which is still read. The dialect never touches a successful hook.2blocks, exactly as above. This is the one hold-the-line answer Claude Code's hooks have, and it stays one.- Any other non-zero is a non-blocking complaint. Claude Code shows the user
the hook's stderr and runs the tool call anyway; it has no exit
3or4at all. So under this dialect those codes are not a prompt and not a rewrite — they are "this hook said something", and the call proceeds. Reading1through the native table would stop a tool call the file never meant to stop. - An
async: trueentry proceeds at every non-zero code,2included: the file asked for a hook that watches rather than gates. It still runs inline, inside itstimeout— candy-code has no detached runner — so whatasynccosts is the power to block, not the hook's execution. - Every such downgrade is announced, on the runtime-notice inbox
(
RuntimeNoticeSink): the hook's name, the code, and the start of its stderr. A hook that meant to gate and does not must be visible rather than silently obeyed. In the terminal you see the row between turns; a session hosted bycandy-code serveshows it once the hosted notice drain lands. - A timeout is not a downgrade. A hook that never answered has not allowed anything, so a dialect row whose run was killed still denies as native does — the dialect reads exit codes, and a killed hook's code says only "signalled".
The check sits in front of the match rather than inside it, so a
hooks.yaml row — the only kind there was before — resolves byte-for-byte as
it always did.
An exit-0 hook may print a JSON envelope instead of a note, in Claude
Code's shape, so a hook written for that tool carries over.
ScriptHook::allowOrEnvelope() reads it; every field is the JSON twin of an
exit code above, so it adds no verdict the exit codes could not reach — it lets
one hook say several things at once:
{"decision": "ask", "reason": "Touches prod config — run it?", "updatedInput": {"command": "make deploy DRY_RUN=1"}, "additionalContext": "deploy target is staging"}| Key | Twin of | Effect |
|---|---|---|
decision |
exit 2 / 3 |
deny or block refuses the call (reason is the refusal), ask puts reason to the user, allow or approve (or no decision) permits |
reason |
stderr on exit 2, stdout on exit 3 |
the refusal or the question, bounded exactly as its exit-code twin is |
updatedInput |
exit 4 |
a JSON object replacing the tool's arguments, refused over the same ceiling; with ask it rides the question as a proposal the chain re-scans |
additionalContext |
stdout on exit 0 |
the model-visible note, capped at 10,000 bytes |
continue + stopReason |
— | "continue": false refuses the call and ends the turn (HookResult::haltsTurn()); stopReason is the operator-facing reason the reply closes with |
suppressOutput |
— | drops the hook's stdout note (its additionalContext), never a verdict — see the rules below |
systemMessage |
— | a one-line message for the human through the RuntimeNoticeSink inbox, never model context, and it survives suppressOutput — see the rules below |
The same keys are accepted under hookSpecificOutput, where
permissionDecision and permissionDecisionReason spell decision and
reason. The nested spelling wins when both are present, as in Claude Code.
Rules worth knowing before you rely on it:
- Only exit
0is parsed. A blocking exit takes its reason from stderr, as in Claude Code, and exit4's stdout is already a JSON object meaning the arguments themselves. - The bar is a whole-stdout JSON object carrying at least one key from the
table. Anything else is a note, unchanged: a hook that prints
{"errors": […]}as context, a JSON list, or JSON with other text around it reaches the model exactly as before. - An envelope with a known key that cannot be honoured denies: a
"decision": "maybe", a"continue": "no", anupdatedInputthat is not an object. The hook evidently meant to steer the call, and guessing which way is the fail-open the exit-4rule already refuses. allowis one hook not objecting, not permission. In Claude Code aPreToolUseallowskips that tool's permission prompt. Here the chain still reaches the permission gate after your hook, so a hook file cannot widen the session's permission mode by printing a word.continue: falseends the turn. On aPreToolUseorPostToolUsehook it refuses the call (the model reads the reason in the"Hook denied: …"or withheld-output line), the step's other calls settle, and the engine's turn ends at that step boundary with no further provider call; the reply closes with[turn stopped by hook "<name>": <stopReason>]. OnStopandSubagentStopit ends the turn the same way (see The stop events). The TUI's own tool path (Chat::gateToolCall()) still only refuses the call.suppressOutputis read: it drops the hook's stdout note (itsadditionalContext), never a verdict — a deny reason and an ask question are not output, and keep reaching you as in Claude Code.systemMessageis read: a string one is shown to the human through the sameRuntimeNoticeSinkdrain described above — clipped, with control characters stripped, and never added to the model context.suppressOutputdoes not hide it: the notice is not the hook's stdout, exactly as in Claude Code. A session hosted bycandy-code serveshows it once the hosted notice drain lands.
ScriptHook::execute() sets eight CRUSH_* keys — six, on the one run where the temp directory will not
take a file, which is covered below — and lays them over the environment
CandyCode was launched with, which the hook inherits after three changes (see
What else the hook inherits):
CRUSH_SESSION_ID CRUSH_TOOL_NAME CRUSH_TOOL_INPUT
CRUSH_TOOL_OUTPUT CRUSH_MODEL CRUSH_PROVIDER
CRUSH_TOOL_INPUT_FILE CRUSH_TOOL_OUTPUT_FILE
The child also receives the Claude-Code-shaped JSON payload on stdin:
{"session_id", "cwd", "hook_event_name", "tool_name", "tool_input", "tool_response", "transcript_path"}. The shape is fixed at these seven keys on
every event: transcript_path is always present, and its value answers the
transcriptJsonl setting — null while the mirror is off (the default), the
session's append-only JSONL journal path when it is on, the same file
EnhancedSessionStore mirrors each committed transcript into. Reading the key
never creates the file. The CRUSH_* environment stays as above, and a
child that never reads stdin still verdicts on its exit code.
CRUSH_TOOL_INPUT (and the file behind CRUSH_TOOL_INPUT_FILE) is the tool's
arguments as JSON with slashes and non-ASCII left unescaped — a Read of
/etc/passwd arrives as {"file_path":"/etc/passwd"}, not
{"file_path":"\/etc\/passwd"} — so a plain grep -qF /etc/passwd or
grep -q 'rm -rf /' guard matches what the model asked for. An invalid UTF-8
byte is replaced with U+FFFD in the hook's copy. Arguments that cannot be
encoded at all are refused with a Hook denied: reason before any hook
runs; they are never handed to the chain as an empty {}, which a deny hook
would read as nothing to refuse. Both tool paths encode through the same
Runtime::hookInput(), and the UserPromptSubmit/SessionStart input
({"prompt":…}) leaves slashes and non-ASCII unescaped the same way.
Linux caps one environment entry at MAX_ARG_STRLEN, which is
PAGE_SIZE * 32 for NAME=VALUE\0 together, and fails the whole execve()
with E2BIG past that. On the usual 4 KiB pages that is 131,072 bytes; it
is 2 MiB on a 64 KiB-page kernel (ppc64le, and the aarch64 kernels RHEL and
SLES ship), and macOS and the BSDs cap the whole environment instead of one
entry, so the figures below are this platform's and not a portable constant.
CandyCode does not assume any of them — see the retry described below.
While CRUSH_TOOL_INPUT was the only route the payload had, that kernel limit
was a limit on the tool call: with any script hook registered, a Write
whose JSON arguments exceeded ~128 KB could not run at all. Measured on a
4 KiB-page host against a hook whose entire script is exit(0): 131,054 bytes
of value allowed, 131,055 denied, 200,000 and 1,000,000 denied identically —
with a refusal reading Hook <name> could not be executed, which names neither
the size nor the cause and reads as "your hook is broken".
CRUSH_TOOL_OUTPUT behaves the same way one byte lower, at 131,053/131,054,
because its name is one byte longer and the kernel measures NAME=VALUE\0.
So the payload now travels both ways:
-
CRUSH_TOOL_INPUT_FILEandCRUSH_TOOL_OUTPUT_FILEpoint at a0600temp file holding the complete bytes, and are set on every run in which such a file could be created — which is every run short of a temp directory that will not take a file. The files are deleted as soon as the hook exits: read them, do not stash the path. -
On a run where no temp file could be written, neither
_FILEvariable is set at all, and the two payloads split: an oversize one is a fail-closed deny before your hook ever starts, while one that fits is handed over inCRUSH_TOOL_INPUTexactly as it always was and your hook runs normally. A guard that reads only the file therefore sees nothing on that second case — which is why the snippet below falls back to the variable rather than trusting the path to be there. (Refusing every tool call because/tmpis full would be the worse trade, so this case is handled and not designed out.) -
CRUSH_TOOL_INPUT/CRUSH_TOOL_OUTPUTcarry the real bytes whenever the operating system will accept them, which is every call that works today. Nothing already written breaks. -
When the OS refuses to start your hook with the payload in its environment, CandyCode retries with the file-backed payloads moved out of the environment, and the variable carries a marker instead:
@@CRUSH_PAYLOAD_IN_FILE@@ 200011 bytes; read $CRUSH_TOOL_INPUT_FILENot a prefix of the JSON — truncated JSON is not smaller JSON, and a hook that decodes it leniently judges a call that does not exist. Not empty either, since an absent
CRUSH_*already means "empty" here.
If your hook inspects arguments, prefer the file, fall back to the variable,
and refuse when you end up with neither. A hook that reads only
CRUSH_TOOL_INPUT will now run on a call whose payload the environment could
not carry, and see the marker where it used to see arguments — whereas before,
the call was denied outright. A hook that reads only CRUSH_TOOL_INPUT_FILE
sees the empty string on a host whose temp directory will not take a file.
Either way, a guard that cannot read the arguments has not cleared them, so say
so with an exit 2:
if [ -n "${CRUSH_TOOL_INPUT_FILE:-}" ] && [ -r "$CRUSH_TOOL_INPUT_FILE" ]; then
input="$(cat "$CRUSH_TOOL_INPUT_FILE")"
else
input="$CRUSH_TOOL_INPUT"
fi
case "$input" in
''|'@@CRUSH_PAYLOAD_IN_FILE@@'*)
echo "hook: the tool arguments could not be read" >&2
exit 2
;;
esacBoth branches are exercised by ScriptHookTest, including on a host whose
TMPDIR is a regular file: without the fallback that guard was measured
allowing {"command":"rm -rf /"}, because cat on an unset path reads
nothing and an empty string matches no dangerous pattern.
CRUSH_TOOL_NAME and your matcher: are unaffected by any of this.
Platforms that cap the whole environment rather than one entry (macOS: 256 KiB for argv and environ together) are not modelled as a number anywhere — but they no longer need to be: the retry above is triggered by the exec the OS actually refused, not by a size CandyCode guessed at, so a payload pair that passes every per-entry check and is still refused gets moved onto the files and tried again. If even that is refused, the refusal names both payload sizes rather than saying only that the hook could not be executed.
Your launch environment reaches the hook — PATH, HOME, LANG,
VIRTUAL_ENV, the CANDY_CODE_* variables that configured the launch — with
three changes, made by ProcessContainment::scrubbedEnv():
- Credentials are removed. A variable
whose name matches
*_API_KEY,*_TOKEN,*_SECRET,AWS_*,*_PASSWORD,*_PASS,*_PWD,*_DSNor*_CREDENTIALS— case-insensitive — is dropped, as are the exact namesDATABASE_URLandPGPASSWORD(no underscore for a*_-glob to bite on), and so is every provider key CandyCode itself reads (ANTHROPIC_API_KEY,ANTHROPIC_AUTH_TOKEN,OPENAI_API_KEY,SGLANG_API_KEY,CUSTOM_PROVIDER_API_KEY). A hook's stdout can becomeadditionalContextthe model reads, so a key in its environment was oneenvaway from the transcript. Bash and Grep get the same scrub. If a hook genuinely needs one — a notifier posting withSLACK_TOKEN— name it insecretEnvAllowlistin your own~/.candy-code/settings.json(seeSETTINGS.md); a glob there never releases a provider key, only its exact name does, and no project file can set the key at all. - Two terminal handles are removed:
SUDO_ASKPASSandGPG_TTY, which would let a detached child reach a prompt or a tty nobody can see. - Fail-fast values are forced over whatever your shell had:
GIT_TERMINAL_PROMPT=0,GIT_ASKPASS=/bin/false,SSH_ASKPASS=echo,DEBIAN_FRONTEND=noninteractive,PAGER=cat,GIT_PAGER=catandSYSTEMD_PAGER=/bin/cat, so a command that would prompt refuses on stderr instead.
The CRUSH_* keys go on last, so no credential pattern can remove one.
This page used to say the opposite: that the hook's environment replaces
yours, that nothing from your shell survives, and that PATH is not inherited.
That described an earlier ScriptHook. Once every spawn moved onto the shared
containment block the hook inherited everything, credentials included, and the
page went on describing the old build until the F-E1 audit counted 129 lines
where it promised 8.
Those eight are what the hook sets. What a hook actually sees depends on the
shell you launched from, so the measurement fixes that shell: command: 'env | sort', the project root as cwd, and CandyCode launched under env -i with
exactly HOME, PATH, LANG, OPENAI_API_KEY, GITHUB_TOKEN, AWS_PROFILE
and SUDO_ASKPASS set — twice, varying only toolOutput:
toolOutput |
env lines |
Which |
|---|---|---|
'' (empty) |
18 | 7 × CRUSH_* + 7 forced + 3 inherited + PWD |
'RESULT-TEXT' |
19 | 8 × CRUSH_* + 7 forced + 3 inherited + PWD |
CRUSH_MODEL=…
CRUSH_PROVIDER=…
CRUSH_SESSION_ID=…
CRUSH_TOOL_INPUT=…
CRUSH_TOOL_INPUT_FILE=/tmp/crush-hook-payload-…
CRUSH_TOOL_NAME=…
CRUSH_TOOL_OUTPUT=… ← only in the second run
CRUSH_TOOL_OUTPUT_FILE=/tmp/crush-hook-payload-…
DEBIAN_FRONTEND=noninteractive
GIT_ASKPASS=/bin/false
GIT_PAGER=cat
GIT_TERMINAL_PROMPT=0
HOME=…
LANG=…
PAGER=cat
PATH=…
PWD=/…/project
SSH_ASKPASS=echo
SYSTEMD_PAGER=/bin/cat
The three inherited lines are HOME, LANG and PATH. The launch had four
more that the hook does not: OPENAI_API_KEY, GITHUB_TOKEN and AWS_PROFILE
are credential-shaped, and SUDO_ASKPASS is a terminal handle.
HookEnvironmentDocumentationDriftTest re-runs this exact measurement and
compares it with the table and the listing, so neither can drift from the code
again.
Note that CRUSH_TOOL_OUTPUT_FILE appears in both runs while
CRUSH_TOOL_OUTPUT appears in only one: the file is written even for an empty
payload, and an empty file is still a file, whereas env does not print an
empty value.
Two things fall out of that, and neither is the count above.
CRUSH_TOOL_OUTPUT vanishes from the listing when it is empty — the variable is
implemented and always passed, but an empty value is not something env prints.
Read an absent CRUSH_* variable as empty, never as a missing feature. (Which
also means the empty-toolOutput run prints one fewer CRUSH_* line than it
has keys — env hides empties — while the degraded run's six keys are six for
the temp-directory reason above. Do not conflate the two counts.)
And PWD is the one line that came from neither CandyCode nor your launch
environment: the command is passed to proc_open() as a string, so it runs
under /bin/sh -c, and sh exports PWD itself.
PATH is inherited, and exported, so a program your hook execs resolves
commands by it exactly as your shell would. (Earlier revisions of this page
said PATH was never inherited and printed a probe table to prove it. That
table measured the eight-variable environment described above as withdrawn, and
went with it.)
cwd is the project root when it is a real directory.
Both pipes are drained with stream_select() rather than sequential
stream_get_contents(). Sequential reads deadlock the moment a hook writes more
than one pipe buffer (64 KiB on Linux) to stderr — which is exactly the case a
security gate is most likely to be verbose in. A false from the select is
retried up to 128 consecutive times rather than treated as end-of-output,
because pcntl_async_signals() is on for the whole TUI and a terminal resize
during a hook returns EINTR: breaking there truncated deny reasons, half of an
exit 3 question, and — worst — a partial exit 4 rewrite, which is invalid
JSON and therefore a deny of a call the hook meant to permit differently.
additionalContext has exactly one bound, HookResult::MAX_ADDITIONAL_CONTEXT_BYTES
— 10,000 bytes, counted as bytes and not characters, because the figure that
matters is what the provider bills. It is applied by the producer, never
trusted from the writer: ScriptHook runs every exit-0 stdout, and
HookRegistry::executeHooks() re-runs every chain total after joining, through
HookContextFiles::bound().
At or under the cap the text passes through unchanged. Over it, what travels is the UTF-8-safe head plus a marker naming both figures and the file where the complete output was retained:
- retained files live in a
sc-hook-ctx-<euid>/directory inside the system temp directory — one directory per user, so the first user on a shared box cannot lock everybody else out of retention — one file per overflow, created0600, filled and then renamed, so a reader never sees a partial file; - they are never auto-deleted: a hook's output is treated as audit material and outlives the run that produced it;
- they are deliberately outside the tool-IPC sweep.
ToolIpcFiles::sweep()matches only its five bare-temp prefixes (sc_runtime_tool_*,sc_chat_tool_*,crush-hook-payload-*,sc_cc_sysprompt_*,sc_codex_schema_*), and a glob*does not cross the directory separator — so nothing undersc-hook-ctx-<euid>/can be swept however long the notes pile up; - if the temp directory will not take the file, the marker says the output could not be retained instead, and the bounded head still travels.
Because the chain re-binds after joining, the 10,000-byte figure bounds what one tool call puts in front of the model, not each hook: fifty hooks printing a kilobyte apiece still arrive as one bounded note on the result.
A hook run is bounded, drain and reap together. 60 seconds by default —
the hooksDefaultTimeoutSeconds setting in your own config.json moves that
default (1 to 3600 s; a project file cannot); timeout: on the entry overrides it, and anything that is not a positive
finite number is refused at load rather than read as "no timeout".
That last word is the whole guard, and it was one word short. 0, -1 and
'none' were refused from the start; .inf was not — is_float(INF) is true
and INF > 0 is true, so timeout: .inf set a deadline of
microtime(true) + INF and put back exactly the unbounded wait the key exists
to remove, behind an error message that promised it could not be asked for.
Measured at fc597e81: timeout: .inf parsed to INF, and a real
ScriptHook on sleep 300 under an 8-second external clock returned exit 124.
Every literal that overflows to infinity (1e400) did the same, and .nan
fell past the <= 0 test to be silently coerced to 60. All of them are
refused now, and .nan is refused rather than coerced because substituting a
number for one a user typed is what disabled: 'no' is refused for.
A hook CHAIN is bounded too, at the sum of its matching entries' timeouts,
armed once and shared across every re-scan pass. A per-hook bound alone was
"one hook cannot freeze the CLI" — the chain runs every matching hook and
re-scans up to MAX_REWRITE_PASSES times, so the real freeze was
hooks x passes x 60. The sum is used rather than a new constant because it is
the only figure derived from what you already wrote: on a single pass every
entry gets exactly the budget it asked for, and what is taken away is the
multiplication nobody asked for. A chain that runs out is a DENY, naming
the budget. Command (script) hooks and type: http hooks both carry a bounded
timeout, so both contribute to that sum and are charged against it. Two kinds
do not: hand-written PHP hooks (HookInterface implementations that are not
ScriptHook) are a synchronous call in this process with no deadline to
honour, and type: prompt hooks apply no timeout to the model call at all
(see "Prompt hooks" below). Neither contributes to that budget nor is charged
against it, and a chain made only of those has no ceiling here — the sum is
absent, not zero, so nothing is denied for lack of clock — as it always was.
A deny reason is clipped at 16 KiB, with the clip announcing itself, and so
is an EXIT_ASK question. Both are quoted verbatim into the model's tool
result, so both are prompt text paid for per token — the deny reason written by
a process this class has just decided it cannot trust to finish, and the
question by one whose answer nobody is necessarily there to give
(Runtime::settleAsk() on a run with no approver attached interpolates the
question whole and hands it to the model). The clip is what the MODEL sees; the
permission modal was never the unbounded half of that path, since it keeps 8
wrapped rows and appends its own … N more lines well before 16 KiB.
EXIT_MODIFY JSON is not clipped, and that half is permanent: a truncated
rewrite is invalid JSON, so clipping would become a deny of the very call the
hook meant to permit differently — hence refusal at the ceiling instead. An
EXIT_ALLOW message used to be unclipped because it reached the model nowhere;
its stdout now travels in additionalContext, and the cap that rides on it is
HookResult::MAX_ADDITIONAL_CONTEXT_BYTES — see above.
It used to be unbounded in two independent places, and either one alone was
enough to freeze the CLI — no spinner, no Escape. Measured at 4a4ecb98, each
under a 5-second external clock and each returning exit 124:
| Hook command | Where it parked |
|---|---|
sleep 30 |
the drain's stream_select(), called with a null timeout |
printf hi; exec 1>&- 2>&-; sleep 30 |
proc_close(), which waits — the drain had already finished at EOF |
Past the deadline the child gets SIGTERM, half a second, then signal 9, and the
hook is reported as a DENY: an expired hook has answered nothing, and
letting the call through would silently skip the guard that was written to stop
it. On PostToolUse the engine path (Runtime::settle()) treats it as any
other deny and withholds the tool's output. That is fail-closed, so a
secret scanner that runs out of time cannot let through what it never finished
reading. The dormant Chat path (Chat::applyPostToolUse()) does the same.
A type: http entry posts the same JSON a script hook gets on stdin — see
"Environment handed to the script" for the fields — to its url, and reads the
answer as the JSON envelope a script would print to stdout. The shape is the
one {@see \SugarCraft\Code\Hooks\HttpHook} runs, and it is deliberately
small, because the URL is configuration the chain has no reason to trust:
- Only
httpandhttps, and no credentials in the URL. A password typed into a URL lands in logs and proxies, so it is refused at load rather than stripped at call. - Refused at load, refused again at call. {@see HookConfig} asks the guard
whether the host is dialable while it parses the file, so a project-tier file
cannot park
127.0.0.1or169.254.169.254until something later reaches it. The call repeats the check on the address it actually dials: DNS that answers differently at call time gets the same answer as the guard gave at load. Both questions go toSupport\PublicUrlGuard— the repo's one SSRF rule, the same oneWebFetchdials through — so there is no second policy to fall out of agreement with. - No redirects. A
3xxis not an answer, and following one would let a host that passes the check hand the request to one that does not. A redirect is reported as the hook answered nothing. - The response is capped at 262,144 bytes (
HttpHook::MAX_RESPONSE_BYTES); a body that does not end inside the cap is also answered nothing, not truncated into a verdict. - Header values read
$VARfromallowedEnvVarsonly. A name that is not on that list stays literal text in the value, so forgetting the list fails by sending a template instead of by leaking a secret. The framing fields (Host,Content-Length,Content-Type,Transfer-Encoding,Connection, and the rest) are owned by the transport and refused as entry keys; a value carrying a control byte is refused as request smuggling. - Nothing secret is echoed. A refusal or a notice names the hook and
scheme://host(never the path, query, or any header value), so anAuthorizationfield cannot ride out of the process in its own error message. - A 2xx that is not an envelope ALLOWS, and its body arrives as additional context — untrusted-sanitised and clipped to the same bound a script hook's context gets. A 2xx envelope is read by the same {@see HookEnvelope} that reads a script's stdout, with the same precedence: a deny in it denies, and a malformed one refuses the call loudly rather than approving it.
- Failing to consult is dialect-split, exactly like an unexpected exit
code: under the native format it is a DENY (a guard that could not be
reached has not approved the call); under Claude Code's, or on an
asyncrow, it is an ALLOW with a notice, so a dead endpoint costs a message on the notice strip rather than the whole tool call. - The bound is the hook's
timeout. It is a per-request transport timeout on a call the user configured, which is what the request needs; the ban on a blanket total-request timeout is about LLM calls, and this is not one.
The reach is the reach of a command hook with a network: a project-tier
type: http entry can post your tool arguments to a host someone else chose.
That is why it rides the SAME gate — trustedProjectHooks decides whether the
file is read at all, and an untrusted tier's file never reaches the URL
question. A project that needs a remote guard should ship a hook whose URL is
its own, reviewed, and dialable; the guard will not take your loopback either
way.
A type: prompt entry asks a MODEL instead of forking a process or dialling a
URL. The runner is {@see PromptHook}: one tool-less completion on the launch's
TITLE backend (the same cheap auxiliary the session titles and exec reviews
ride), carrying the entry's prompt with every $ARGUMENTS replaced by the
hook input — the same JSON a command hook would get on stdin — fenced as
untrusted data between UNTRUSTED_HOOK_INPUT_BEGIN/END markers that the
payload cannot forge: the text is PromptFence::escaped, any marker bytes it
carries are broken apart, and the block is clipped before it is inserted. An
entry whose prompt names no $ARGUMENTS gets the fenced block appended. The
reply must be exactly one JSON object: {"ok":true} allows (a reason on an
allow is shown as a notice), and {"ok":false,"reason":"..."} DENIES the call
with that reason, sanitized and clipped — the model's own words are the guard
that fired.
Anything else is the hook saying nothing, and the dialect decides what silence
means, exactly as it does for an HTTP hook that never answered: a native entry
DENIES (deny_unanswered — a guard that failed to guard has not approved the
call), while a claude-dialect or async entry allows with a launch notice. A
launch with no provider has no title backend to ask, and that lands on the
same door rather than a fourth one.
Two laws the shape depends on:
timeoutis accepted and never applied to the call. The entry'stimeoutis validated like every row's and then left alone — the ban on a blanket total-request timeout is about LLM calls, and this is one.PromptHookis deliberately not a bounded hook: the registry charges it no deadline and the call carries only the provider's connect timeout, exactly asExecReviewer's does.- The spend is not the chat's. The verdict call rides a fresh tool-less
EngineBackendbuilt once per launch (Bootstrap::titleBackend()), never the conversation's backend, and nothing of it settles into the/budgetaccounting — again theExecReviewerprecedent. A matched prompt hook is cheap tokens per gated call, not a billed turn.
model is honoured, not promised: the entry may name one, and the hook asks
EngineBackend::withModel() only if the rebound backend can show it serves
that exact id — a provider that reports nothing back, or serves something
else, keeps the title model silently rather than running the guard on a model
nobody chose. The reply contract is the entry's own ok/reason shape, NOT
the script hook's JSON envelope: a prompt hook answers the hook author's
question; it does not speak decision/continue.
The reach is the reach of a hook that feeds text into a model: a project-tier
type: prompt entry puts its prompt in front of the title backend beside
the tool arguments. That is why it rides the SAME gate — trustedProjectHooks
decides whether the file is read at all, and the hook input beside it is
fenced no matter which tier wrote the entry.
HookManager::registerBuiltIns() registers three unconditionally, ahead of
anything from a file and ahead of the permission gate. Registration order is
the order a chain runs in, with one exception: AuditHook always runs after
every other PostToolUse hook, whatever order they were registered in
(HookRegistry::findMatches()). It records what a call produced, so
it runs only once the rest of the chain has permitted that output — see
below.
| Hook | Event | What it does |
|---|---|---|
ProtectFilesHook |
PreToolUse on ^(Bash|PtyRun|Edit|Write|ApplyPatch|Read|Grep|Glob|Lsp|mcp__.*)$ |
denies secret and policy files; asks for the rest — the shell half is derived from ShellSubjectTools::NAMES, and a PtyRun step is judged from its DECODED keystrokes as well as its raw bytes — see below and PERMISSIONS.md |
ConfirmRemoveHook |
PreToolUse on ^(?:Bash|PtyRun)$ |
asks before obvious destructive shell (rm -rf, find … -delete, …); an unanswered ask never runs — typed keystrokes count as shell text here too |
AuditHook |
PostToolUse, matcher .* |
appends every call — and every refused or withheld one, see below — to whatever AuditHook::defaultLogFile() answers — a fixed leaf inside a per-user directory the hook creates 0700 and refuses to use if it is not its own |
Twelve more exist and are not registered by default:
PermissionGateHook— registered byBootstrap::hooks()when a gate exists, which is every CLI launch. It is what makes the six-mode gate reachable from the main loop at all.BashEscapeDenyHook— constructed with a jail root, and NOT part ofregisterBuiltIns(). In this product its only registrant isEngineBackendon a worktree-isolated teammate's run, where the worktree root is the jail; everywhere else it is embedder opt-in. Its matcher covers every shell-subject tool (^(?:Bash|PtyRun)$, derived fromShellSubjectTools::NAMES), so a typedPtyRunkeystroke is judged like a command.RepeatCallGuardHookandRepeatCallCountHook— the repeat-call loop guard, registered per turn byEngineBackend::resolveHookManager()around one sharedBackend\ToolCallLoopGuardledger, on a copy of the launch's chain and on awithoutHooks()turn too. Within one turn, the same tool called with the same arguments (key order ignored) that returns the same result gets a warning appended to its 3rd result (PostToolUse, asadditionalContext), is denied from the 5th call (PreToolUse), and ends the turn on the 8th. A changed result resets the count. They are not inregisterBuiltIns()because their ledger lives one turn and a hook manager lives for the launch.SubAgentGrantHook— the delegated run's own tool declaration, registered byEngineBackend::resolveHookManager()only on the copy of the chain aTasksub-agent runs on (TaskToolbinds it), ahead of the permission gate and on awithoutHooks()turn too. It denies a call outside the preset'stoolsgrant or matched by itsdisallowedTools, argument halves included, soBash(git *)refusesrm x, and, when the preset'spermissionModeis stricter than the session's, holds each admitted call to that mode as well (seePERMISSIONS.md). SeeAGENTS_AUTHORING.md. Its name,subagent-grant, is reserved like the gate's (HookRegistry::isReserved()): no other hook may register under it, and a disable naming it is ignored.PostEditFormatHook— the post-edit format, registered byBootstrap::hooks()whenformatCommandsnames a command, orformatAutoarms the built-in table for a trusted project, after the three above and ahead of the post-edit lint, so the linter reads formatted bytes. See Post-edit format.PostEditLintHook— the post-edit lint, registered byBootstrap::hooks()on every launch, after the three above and ahead of the hook files, because it reads the user'slintCommands. See Post-edit lint.PostEditDiagnosticsHook— the post-edit diagnostics, registered byBootstrap::hooks()when a language server is configured underlspand started, right after the post-edit lint and ahead of the hook files. See Post-edit diagnostics.AutoCommitHook— the auto-commit of each edit, registered byBootstrap::hooks()whenautoCommitisedit, after the post-edit diagnostics and ahead of the hook files. See Auto-commit.AutoTestHookandAutoTestEditHook— auto-test reflection, registered byBootstrap::hooks()whenautoTestis on andtestCommandis set, after the auto-commit and ahead of the hook files. See Auto-test.BoardNoticeHook— shared-board notices, registered byBootstrap::hooks()on every launch, after the hooks above and ahead of the hook files. It is inert outside a parallelTaskbatch. Inside one, when a peer has posted something for a member (to its id, or toALL) since the member was last told, the member's next tool result gets one<shared-agent-board-notice>note (PostToolUse, asadditionalContext), however many posts arrived; aBoardReadresult never does, since reading counts as being told. It tells a member's run from the rest throughAgents\Board\ActiveBoard, whichTaskToolbinds for the length of a member's run in the member's own process. SeeAGENTS_AUTHORING.md.
One more is turn-scoped and lives outside src/Hooks/BuiltIn/:
Context\Pruning\CompressPreviewHook, which EngineBackend::runTurn()
registers on a /compact --self turn's own copy of the chain, ASKs before the
model's Compress call is applied, showing you its summary (30 lines, then
"… (N more lines)").
ConfirmRemoveHook and BashEscapeDenyHook are both documented in their own
source as heuristics, not security boundaries. Neither can see through
shell indirection: x=rf; rm -$x, aliases, $(echo rm) -rf, a variable set
earlier (d=/etc; cat $d/passwd), symlinks and here-docs fed to an
interpreter all evade them. They catch the obvious footgun — a model literally
emitting rm -rf or cat ~/.ssh/id_rsa — not a hostile command. For real
containment, run the process in a jail or container.
BashEscapeDenyHook reads the command through the same quote-aware tokenizer
as the permission rules, so separators, pipes, subshells and glued
redirections (cat</etc/shadow, cd ..;ls, echo x >/tmp/out) do not hide a
path. It expands ~, $HOME and $PWD (the root), denies $OLDPWD, cd -
and ~user, and also judges the bodies of $(…), backticks, <(…),
sh -c '…' and eval. It allows /dev/null, /dev/std* and an absolute
path to an existing executable in command position (/usr/bin/php -v).
Quoting is not among those evasions for ConfirmRemoveHook any more: each
pattern runs against the raw command and its quote-removed words (the same
Permissions\ShellWords tokeniser the permission gate's step-0 breaker uses),
so rm '-rf' x, rm "-rf" x, find . '-delete' and dd 'of=/dev/sda' are
asked about like their unquoted spellings. Earlier cuts let the first three pass
the whole built-in chain under bypass-permissions, then the default mode on
every path (it still is for -p and background sessions; the TUI now starts in
default).
After every Write, Edit or ApplyPatch that did NOT fail, PostEditFormatHook
runs the formatter named by formatCommands over each edited file and lets it
REWRITE the file. It is registered ahead of PostEditLintHook — the linter
then reads the bytes that actually stand on disk — and only registers at all
when something can run: the map naming a command, or formatAuto arming the
built-in table for a trusted project. formatCommands is off by default, and
where the lint falls back to a built-in php -l, a formatter has no safe
default to pick for you.
{"formatCommands": {"php": "vendor/bin/php-cs-fixer fix {file}", "ts": "npx prettier --write"}, "formatAuto": true}-
formatAuto(off by default) arms a built-in candidate table for extensions the map names no command for:gofmt -w,rustfmt,ruff formatthenblack,shfmt -w,terraform fmt, and the project's ownnode_modules/.bin/prettier --writefor the js/ts/json/css/md/yaml family. ExplicitformatCommandsentries win per extension, and an extension switched off withfalsestays off under the arm too. A candidate runs only when it is actually present — aPATHlookup for the named tools, the project's ownnode_modulesfor prettier, never a global prettier. Because the table runs binaries the operator never typed, and the project-local prettier loads plugins that are JavaScript from that samenode_modules, the arm is gated twice: the user (never a project file) must setformatAuto, and the project must be listed intrustedProjectHooks— the same grant the project's hook files need. -
The command line is built exactly like a lint command: the file goes last, shell-quoted, or wherever the command writes
{file}; the command runs in the project root, resolves through the same workspace jail, and answers to the same 30-second wall, 64 KiB output capture and 2 MiB source gate asLintRunner. -
The command MUTATES the file, so the runner hashes around the run. After it returns, the file is read again: a rewrite that removed the file, emptied it, grew it past the size wall, overran its deadline mid-rewrite or exited non-zero after already changing bytes is UNDONE — the pre-run bytes are put back — and the note says which of these happened. A clean rewrite stands; a run that changed nothing is silent.
-
A failed call is not formatted at all. When the tool result carries an error — the staleness refusal, a bad patch, a missing string — the call left the user's bytes on disk, and formatting them would REWRITE the file in the very call that failed to change it.
Runtimehands the chain the call's error bit asHookContext::$toolFailed, and this hook stands down on it. The lint hook has no such standing-down: a failed edit is linted like any other, because lint READS and format WRITES. -
A kept rewrite is recorded in the launch's read ledger — the same instance
Read,Edit,WriteandApplyPatchconsult — so the formatter's change never reads as an external edit and never trips the staleness refusal on the nextEdit. But the recording is conditional: the ledger's pre-format staleness check over the bytes read before the formatter ran must have agreed. A file the user moved in the meantime is formatted (the rewrite stands, the note reports it) but NEVER blessed — its staleness stays visible to the next call, exactly as if no formatter had run. That recording is the ledger reason the hook exists; an embedder that registers it without a ledger still formats, it just cannot make the change look read. -
The model still hears about it: each kept rewrite earns a note that the file's bytes are no longer the ones it wrote, so line numbers from the previous read are stale and worth re-reading against.
-
User tier only. A format command is shell that WRITES, so no project settings file may name one, trusted or not —
lintCommands' argument with the mutation added. -
It never refuses. The edit has already happened; every outcome is an allow with a note. It counts against the chain deadline like a script hook (
BoundedHookInterface) and runs through the same bounded spawn asBash, so a hung formatter is stopped rather than freezing the turn. The note is capped at 10,000 bytes like any other hook note, with the formatter's own output cut first.
After every Write or Edit, PostEditLintHook lints the file the call
changed (each file, for an ApplyPatch) and appends what the linter found to that call's result, so the model
reads it on the very result it looks at next. The format is Aider's: the
command that ran, its output, then the flagged lines marked █ among
│-marked context, with ⋮... where lines were skipped.
# Fix any errors below, if possible.
## Running: flake8 --select=E9,F63,F7,F82 'app/main.py'
app/main.py:3:10: E999 SyntaxError: invalid syntax
## See relevant line below marked with █.
app/main.py:
1│import sys
2│
3█def main(:
4│ return 0
PHP files are checked with php -l (the interpreter running candy-code) out
of the box. Add, replace or switch off linters by file extension with
lintCommands in your own ~/.candy-code/config.json or
~/.candy-code/settings.json:
{"lintCommands": {"php": "vendor/bin/phpstan analyse --no-progress --error-format=raw", "py": "flake8 --select=E9,F63,F7,F82", "js": false}}- The file goes last on the command line, shell-quoted, or wherever the command
writes
{file}, relative to the project root; the command runs in the project root. - Only a file the edit could reach is linted: the path is resolved through the
same workspace jail
Edituses. The chain also runs after an edit the tool refused, and a linter quotes the lines it flags, so a refused edit outside the workspace must not get those lines read. false,nullor""switches an extension off, the built-inphpentry included. A value of any other shape is ignored, not refused.- User tier only. A lint command is shell, so no project settings file can name one, trusted or not.
- A clean lint adds nothing, so the result stays byte-identical. A linter that exits non-zero produces the report above. One that cannot start (exit 126 or 127) or runs past its 30-second budget produces a one-line note saying the file was not checked.
- It never refuses. The edit has already happened, and withholding its output would hide what the model needs to fix the error. Every outcome is an allow with a note.
- It counts against the chain deadline like a script hook (it implements
BoundedHookInterface), and it runs through the same bounded spawn asBash, so a hung linter is stopped rather than freezing the turn. - The note is capped at 10,000 bytes like any other hook note, with the linter's own output cut first so the marked lines survive.
When you list a language server under lsp in your own
~/.candy-code/config.json (or settings.json), every Write, Edit or
ApplyPatch to a file that server owns is followed by PostEditDiagnosticsHook: the server is
asked to re-check the file as it now is on disk, and the errors it reports
are appended to that call's result:
LSP errors detected in this file, please fix:
<diagnostics file="/abs/path/src/Order.php">
ERROR [42:9] Undefined method 'totl'.
… and 2 more
</diagnostics>
{"lsp": {"php": {"command": "intelephense", "args": ["--stdio"]},
"typescript": {"command": "typescript-language-server", "args": ["--stdio"], "extensions": ["ts", "tsx"]}}}- Each key is the LSP language identifier. Per server:
command(required),args,extensions(default: the key itself),env,initializationOptions,timeout(seconds per request, default 10),disabledandsandbox(falseexempts this server from thesandboxScopejail when thelspscope jails language servers; the map is user-tier, so the exemption is the operator's own statement). A malformed entry or a server that will not start is reported at launch and costs only that server. - The servers start once, at launch, in the process that builds the tools, and every forked turn, tool call and sub-agent shares them. They are stopped at exit.
- Errors only (severity 1), at most 20 per file, positions 1-based. Warnings and hints are left out.
- It waits at most 5 seconds for the server's verdict, less when the chain has
less time left (
BoundedHookInterface). A server that says nothing in time, a file no server owns and a clean file all add nothing — silence is never reported as "no errors". - Jailed like the post-edit lint: only a file the edit could reach is sent.
- User tier only. Starting a server is code execution, so no project settings file can name one.
- It never refuses, for the post-edit lint's reason.
The same servers answer the Lsp tool and give the Read tool its outline of
a file too long for one page.
autoCommit (user tier only, default off) commits what candy-code changes,
Aider's way:
turn— when a turn settles in the TUI, every file changed since the checkpoint taken before its prompt is committed in one commit. The subject is a one-line Conventional-Commits message (fix: …,feat: …, at most 72 characters) written by the cheap title model (CANDY_CODE_TITLE_MODEL/titleModel) from the diff, or a plainchore: update …when there is no title model, the spend cap is reached, or its answer is unusable. One transcript line says what was committed or why not. A turn that a queued prompt follows at once is not committed on its own.edit—AutoCommitHookcommits eachWrite/Editas it lands (anApplyPatchfile by file; a deleted or moved-away file is not committed), with the call's owndescriptionas the subject (chore: rename the legacy config helper), and tells the model the commit it made. It never refuses; a commit that fails leaves the change in the file, uncommitted, and says why.
Either way:
- Your hooks run. There is no
--no-verify: a pre-commit hook that rejects the commit fails it. - Your work is never mixed in. A file you had already changed before the
turn is first committed as you had it, in its own commit (
chore: snapshot user changes before candy-code edit), and the model's change goes on top. What you had is read from the turn's checkpoint; a tracked file with changes and no checkpoint to separate them is left uncommitted. Only the files candy-code changed are committed — the rest of your index is untouched. - The author is you (
user.name/user.email); the trailer isattribution.commit, orCo-authored-by: candy-code <candy-code@noreply.invalid>when that is unset (an empty string drops it). /undoreverts the last commit this session made —git checkout HEAD~1 -- <files>thengit reset --soft HEAD~1— and tells the model the change was undone. It refuses, changing nothing, when HEAD is not this session's commit, is a merge or the first commit, a file it changed has uncommitted changes now, a file it changed did not exist before it, or it is already on a remote. A session that never auto-committed gets the checkpoint/undoinstead.
With autoTest on and a testCommand set (both in your own
~/.candy-code/config.json or settings.json — user tier only, since the
command is shell run with no tool call in the path), a turn that edited a file
runs your tests before it ends, Aider's way:
{"testCommand": "composer test", "autoTest": true}-
AutoTestEditHook(PostToolUseon^(Write|Edit|ApplyPatch)$) notes each edit and never changes a result.AutoTestHook(Stop) runs the command only when an edit was noted since its last run, so a turn that only read and answered ends exactly as before. ATasksub-agent's edits count toward its caller's turn; the tests do not run at eachSubagentStop. -
A failing run keeps the turn going through the stop events' continuation: the model's next prompt is the run in Aider's
run_outputshape,Stop hook "auto-test" did not let you finish yet: I ran this command: composer test And got this output: FAILURES! Tests: 12, Assertions: 30, Failures: 1.with stderr folded into stdout as the command wrote it, terminal escapes removed, and the last 10,000 bytes kept when the output is longer. Each one is a step under the turn's step ceiling and spend cap.
-
At most three reflections a turn (
AutoTestHook::MAX_REFLECTIONS). If the tests still fail after the third, the turn ends on its last answer and the reply closes with[turn stopped by hook "auto-test": the test command `composer test` still fails (exit 1) after 3 attempts to fix it]A command that cannot start (exit 126 or 127) or runs past its bound ends the turn the same way at once: neither is something the model's next edit can fix.
-
The run happens in the project root, in the turn's own process, through the same bounded spawn as
Bash(credential-scrubbed environment, no terminal, the whole process group stopped at the bound). That process sends the TUI nothing while the tests run, so the bound sits 10 seconds insideturnIdleTimeoutSeconds(110 seconds by default): raise that setting for a slower suite. It is also charged against the chain deadline (BoundedHookInterface).
While bashSandbox is on, one sandboxScope list decides which of these
supporting runs — script hooks, post-edit lint, post-edit format, auto-test —
join that same jail. There is no second jail: a scoped run gets the same
backend and the same mode Bash gets, and a run whose scope is not listed
behaves exactly as it always did, byte for byte. The list is user-tier for
the same reason bashSandbox is: a checked-out project can neither trim the
scope list to un-jail its own hooks nor widen one beyond the switch the
operator set. An unrecognised entry reads as every scope — the strictest
answer — and the settings keys audit in doctor names the entry it could
not place. While bashSandbox is off every scope is inert: there is no
jail to join, and the entries cost nothing until the switch is on.
When the jail cannot start on the host, the fail-closed answer splits into
the two shapes that fit each surface. A script hook denies: it rides the
same could-not-execute path as a refused proc_open(), so a PreToolUse
row vetoes the call and a gating hook is never quietly skipped. Lint, format
and the auto-test run skip with the reason as the note the model sees —
the familiar exit 126 could-not-run classification, never a fabricated
pass, and never an unconfined fallback.
Two jail details matter when a hook is written. The staged input and output
payloads arrive as temporary files in the parent's temp directory, and the
Linux jail mounts a private /tmp over that ground — so the hook carries its
payload files in as read-only binds, and they stay visible inside the jail at
exactly the paths CRUSH_TOOL_INPUT and its siblings name. And the hook's
working directory is pinned through the jail's --chdir, the project root.
A hook that needs cache space therefore writes it under the project root —
durable and reviewable — or uses the /tmp the jail itself hands out, which
is private to the command and gone when it exits. Nothing a hook caches in
the parent's temp directory survives a journey into the jail, because that
directory is not mounted at all.
One line per record, in three shapes. The separator after the input says which one it is:
[2026-10-02 09:14:03] <session> Bash {"command":"ls"} => README.md\nsrc
[2026-10-02 09:14:05] <session> Read {"file_path":".env"} =! DENY hook: This hook prevents modification of files matching: …
[2026-10-02 09:14:09] <session> Bash {"command":"env"} =! WITHHELD "secret-scan": output contains AWS key, blocked
=>is a call that ran. The excerpt is the first 200 bytes of its output, cut on a UTF-8 character boundary.=! DENY <kind>:is a call the engine refused before it ran. That covers aPreToolUsedeny (includingprotect-filesand a hook that timed out), a permission-gate refusal, an ASK that was refused or that nobody could answer, and arguments that cannot be encoded as JSON.<kind>is the denial kind's token:hook,refusedorunanswered. A refused call never reachesPostToolUse, so the engine writes this line itself, through the registeredaudithook, from the gate's refusal arm. Both the sequential path and the concurrent path gate there. None of these left a record until this check existed.=! WITHHELD "<hook>":is a call that ran but whose output aPostToolUsehook refused, or a hook in that chain threw (see the block rules above). The line keeps the hook's name and reason; it reads=! WITHHELD:when no single hook owns the refusal. It is the call's only record: the audit hook runs last in the chain, and a refusal returns before reaching it, so no=>line holds an excerpt of the output that was withheld. Earlier, the audit hook ran first —registerBuiltIns()is called ahead of every hook file — and wrote 200 bytes of the very output a secret scanner then refused.
Every field written into a line is escaped. That means the session, the tool
name, the input, the excerpt and the reason. C0 controls, DEL, NEL, U+2028 and
U+2029 are written as \n, \r, \t, \xNN or \u{NNNN}. Invalid UTF-8
becomes U+FFFD. A newline in a web page or a command's output therefore cannot
write a forged second record, and neither can a terminal escape. Backslashes
are left as they are, so the JSON input stays readable. The escaping is
therefore not reversible: it promises one record per line, not a decodable
field.
The input is capped at 4 KiB (AuditHook::INPUT_CAP_BYTES). Anything longer
ends in [truncated: <n> bytes], so a Write no longer copies the whole file
it wrote into the log. The log itself is size-capped: past
AuditHook::ROTATE_AT_BYTES the hook-owned default rolls to .1, one
generation deep, before the next append — a caller-supplied path is never
touched, because its retention belongs to the caller. And before any field is
cut to fit, it is scrubbed of secret-shaped text by the same redactor memory
notes use, so a bearer token straddling the cut boundary is replaced whole
rather than leaking its first characters.
The matcher was once ^(Bash|Edit|Write|Read)$ and the .env
pattern wanted whitespace on both sides of the name, so cat .env;true,
cat ".env", .env.local and — the easiest route — Grep pattern="=" path="." include_ignored=true all read the secret under bypass-permissions, then
the default on every path. Now:
| Tool | Arguments judged |
|---|---|
Bash |
the raw command and its quote-removed words and redirection targets (Permissions\ShellWords), so cat '.env', cat .e''nv and cat < .git/"config" are denied like their plain spellings |
Read, Edit, Write |
file_path, as given and canonicalised (symlinks resolved) |
ApplyPatch |
every path the patch adds, updates, moves to or deletes, each as given and canonicalised — one protected file among ten refuses the whole call; a patch that does not parse is matched as its raw text |
Grep |
path (canonicalised) and include — not pattern, which is the text searched for |
Glob |
path (canonicalised) and pattern — **/.env* is refused; a **/* listing that happens to include .env is not, because naming a file is not reading it |
Lsp |
path, canonicalised |
mcp__* |
every string leaf of the decoded arguments, at any depth (not the raw JSON text) — so an MCP call whose free text merely mentions .env is refused too |
Read, Grep, Glob and Lsp cannot write, so they skip the write-only
policy patterns (.candy-code/hooks.yaml, config.json and agents/, plus
.git/hooks/ and .git/info/, which are denied; and the always-asked rest —
settings.json, settings.local.json, the skills/, skills-proposed/,
commands/, rules/ and workflows/ directories, .mcp.json, and the .claude/ / .opencode/
skill, agent and command trees); Bash, the write tools and MCP tools get the full list — so
cat .git/hooks/pre-commit in Bash is refused, and cat .mcp.json asks,
where Read of either file is not. The asked rows are a hook's ask(), put to
you in every permission mode; a deny-class match in the same call wins.
.git/hooks/ and .git/info/ are on that list: a file
written to .git/hooks/pre-commit runs on the user's next git commit,
outside any candy-code session, and cp ./payload.sh ./.git/hooks/pre-commit
was allowed under bypass-permissions and auto-run under accept-edits. The
known limit is git config: git config core.hooksPath ./evil (or
core.fsmonitor, a filter driver, …) rewrites .git/config without naming it,
so no path pattern sees it — the permission mode is the boundary there.
The secret-file family is a deliberate list: .env, .env.<anything>
(.env.local, .env.production, .env.bak) and direnv's .envrc are
denied; the committed templates .env.example, .env.sample, .env.dist,
.env.template, .env.tpl (and .env.<stage>.example) are allowed; and a
name where .env is glued to more name (process.env.KEY, foo.env.example,
.environment) or a .env/ virtualenv directory is not a .env at all.
Key material is read-denied the same way: *.pem and *.key (any case, with a
stem or a glob stem, so server.key and Glob **/*.key are refused but jq .key is not) and the SSH identities id_rsa, id_dsa, id_ecdsa,
id_ed25519 with any suffix (id_rsa_work, id_ed25519_sk) — except the
.pub half, which exists to be shared. A public .pem certificate is refused
too: the extension cannot tell a chain from a key.
A hook cannot screen a directory search — Grep path="." contains .env —
so Grep itself never opens one: it always passes --exclude=.env --exclude=.envrc --exclude=.env.* and --exclude-dir=.git (plus
--exclude=config when searching inside a .git directory), even with
include_ignored: true. That also skips the templates in a Grep walk; Read
them directly.
The Bash half stays best-effort: $HOME expansion, globs (cat .en?),
variables and cd are outside what any text match sees. It is defence in depth,
not a jail.
Every run of a configured hook appends one JSON line to
~/.candy-code/hooks-log.jsonl: timestamp, session id, event, hook name,
verdict, elapsed milliseconds, and the first line of the hook's message.
Built-in hooks are excluded — they keep their own audit trail — so the file
reads as what your configuration actually ran.
Messages are secret-redacted before they are written: SecretRedactor runs
first, then the first line is taken, then the line is cut to 200 bytes. That
order is what makes it safe: a token straddling the cut leaves no fragment,
where a cut-then-redact would keep the part it clipped in.
The file is bounded. It rotates at 1 MiB and keeps one previous generation
(the .1 file); older history is out of scope. The write follows the same
owned-home discipline as the rest of ~/.candy-code: the directory is
created 0700, the file is created under a private umask, and a directory or
leaf that is a symlink, foreign-owned or foreign-writable is refused rather
than followed. If the home itself cannot serve, the log falls back to a
per-user candy-code-hooks- directory under the system temp directory.
Writing is fail-open in every case: a refused write never changes the hook's
verdict, and the first refusal in a process surfaces as one runtime notice
instead of a flood.
Read it with /hooks log [n] — the last 20 rows for the current session by
default, n accepted from 1 to 200. Rows the tail could not read whole
(torn writes, a leaf swapped under us) are skipped, never guessed at, and the
report then carries a plain-language suffix saying so. The log is
observation, not enforcement: the chain runs whether or not it can be
recorded.
Implement SugarCraft\Code\Hooks\HookInterface (name(), event(),
matcher(), execute(HookContext): HookResult) and register it on a
HookManager. HookResult has four constructors — allow(), deny(),
ask(), modify() — the same four the exit codes above map onto, each taking
an optional trailing $additionalContext: that is where a PHP hook puts the
model-visible note ScriptHook derives from stdout, and the chain collects it
the same way. This is the route for anything the six-key YAML shape cannot
express; it needs an embedder, not a config file.
PERMISSIONS.md— the layer the chain ends in.TROUBLESHOOTING.md— "candy-code exits 2 and will not start".CONTEXT.md— the compactionsPreCompactandPostCompactsurround.AGENTS.md— the sub-agentsSubagentStopreports on.- The README — every other page.