Reference: amplihack hooks block¶
amplihack registers its Claude Code hooks in a hooks object inside
settings.json. One module, install/hook_block.rs, defines that object and
is the only code that merges it into a file or compares a file against it.
For the reasons behind this design, see
One source for the hooks block.
Contents¶
- The block
- Files that hold the block
- Writers
- Merge rules
- Drift
- Launch settings file
- Doctor report
- File safety
- Environment variables
- Module interface
The block¶
The block is built from the AMPLIHACK_HOOK_SPECS table. Each entry becomes
one wrapper under its event name. The command is the quoted path to the
amplihack-hooks binary followed by a subcommand.
| Event | Subcommand | Timeout (s) | Matcher | asyncRewake |
|---|---|---|---|---|
SessionStart |
session-start |
10 | ||
Stop |
stop |
120 | ||
PreToolUse |
pre-tool-use |
* |
||
PostToolUse |
post-tool-use |
* |
||
UserPromptSubmit |
workflow-classification-reminder |
5 | ||
UserPromptSubmit |
user-prompt-submit |
10 | ||
PreCompact |
pre-compact |
30 | ||
SessionEnd |
session-stop-event |
30 | ||
StopFailure |
limit-resume |
see below | rate_limit |
true |
That is nine entries across eight events. StopFailure is included only when
the installed Claude Code supports it; on an older Claude Code it is left out
and any existing amplihack StopFailure entry is removed (#1659). Its timeout
is LIMIT_RESUME_TIMEOUT_SECS.
A PreToolUse wrapper as written to a file:
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "\"/home/you/.local/bin/amplihack-hooks\" pre-tool-use"
}
]
}
The binary path is absolute and wrapped in double quotes; ~ is never used,
because Claude Code does not expand it inside a quoted path.
The block never contains an XPIA hook, whether or not tools/xpia/hooks/ is
present on disk. See XPIA.
Files that hold the block¶
| File | Created by amplihack | Kept current by |
|---|---|---|
~/.claude/settings.json |
Yes, by amplihack install only |
install, update, launch repair, rotator cycle |
$CLAUDE_CONFIG_DIR/settings.json |
No | launch repair, when CLAUDE_CONFIG_DIR is set and the file exists |
<profile root>/<name>/settings.json |
Copied at profile seeding | profile refresh, profile seeding; rotator cycle for the live profile only |
$AMPLIHACK_HOME/runtime/launch-hooks-settings.json |
Yes, at each claude launch |
amplihack launch / amplihack claude |
The profile root is resolved through root_config, as for every other
amplihack profile command; its default is ~/.amplihack/claude-profiles.
A profile with no settings.json stays without one. No writer other than
install creates a settings file, and install always targets
~/.claude/settings.json; it does not read CLAUDE_CONFIG_DIR.
Only the launch repair reads CLAUDE_CONFIG_DIR. Install, the rotator cycle
and doctor work on ~/.claude/settings.json whether or not the variable is
set, so a $CLAUDE_CONFIG_DIR/settings.json that has drifted is repaired only
by the next amplihack launch and is not shown by doctor.
Writers¶
Every writer below calls the same merge. None of them has its own copy of the hook list.
| Writer | When it runs | Target | Skipped when |
|---|---|---|---|
amplihack install / update |
On request | ~/.claude/settings.json (created as {} if absent) |
The file is refused; install reports it and finishes its other steps |
| Launch repair | Each amplihack launch / amplihack claude |
$CLAUDE_CONFIG_DIR/settings.json, else ~/.claude/... |
The running binary is older than the install stamp; AMPLIHACK_SKIP_AUTO_INSTALL is set; no drift |
| Profile refresh | amplihack profile refresh paths |
Each <profile root>/<name>/settings.json |
The profile root is refused by hook_path_refusal; the file is absent |
| Profile seeding | After settings.json is copied into a new profile |
The new profile's settings.json |
Older binary; no hooks binary; the profile root is refused. Seeding still succeeds |
| Rotator cycle | End of each swapped or stayed cycle |
~/.claude/settings.json and the live profile's file only |
Read-only mode; older binary; no hooks binary; no drift. A refused or unidentified live profile is logged and does not stop the home heal |
| Launch settings file | Each claude launch |
$AMPLIHACK_HOME/runtime/launch-hooks-settings.json |
See When the file is not used |
Nothing else in amplihack removes amplihack's hooks from a settings file. The
session-start step in amplihack-hooks that used to delete the global hooks
when a project also had project-local hooks no longer does so; see
Global hooks at session start and doctor.
Launch repair¶
The launch repair reads the target with the drift check first and writes only
when the check reports drift or the home settings file is absent. Launch can
create ~/.claude/settings.json; an absent $CLAUDE_CONFIG_DIR/settings.json
is left absent. Any missing or differing event counts, so a file
that lost only StopFailure, or holds a stale StopFailure entry, is repaired
as well as a file that lost every hook.
Issue #2589 added a second pass beside this one, which refreshes the
dangerous-command deny entries in the same file. It is not part of the drift
check: a file whose hooks block is clean is left by the repair and still
reaches that pass, so a launch can change permissions.deny without the hooks
block having drifted. See
the dangerous-command policy. The rest of this
section describes the hooks repair alone.
A binary older than the install stamp never writes, because it would write an
older block. If reading the install stamp fails, the binary is treated as
older. In that case amplihack doctor reports the drift and
amplihack install repairs it.
An unreadable or refused file produces one warning line from this repair and no write. Since #2589 the deny pass beside it reports the same file on its own line, so a launch that meets one prints two warnings, one per pass. The wording below is an example; only the path and the reason in brackets are fixed:
amplihack: warning: /home/you/.claude/settings.json could not be used (is a symlink); hook registrations were not checked or repaired. Fix the file, then run `amplihack install`.
Rotator cycle¶
amplihack profile rotate (both a single run and the watch daemon) checks the
hooks after each cycle that ends swapped or stayed. amplihack profile
switch does not run this check; the next rotator cycle does. It runs
after the cycle has released the swap lock and adds no timer of its own; it
reacts to the cycle finishing.
The live profile's directory comes from the profile store and root_config,
never from the ledger, a status file or the environment. Profiles other than
the live one are not checked by the cycle; they are repaired only by profile
refresh. A file that is current either with or without StopFailure is
left alone. The rotator decides whether to register StopFailure from the
claude on its own PATH and keeps that answer until it restarts, so it
may disagree with the launch repair; accepting either answer stops the two
from taking turns rewriting the file and leaving a backup each time. The heal never
touches .claude.json, .credentials.json or any login, and it never changes
the cycle outcome or the exit code. It logs one line per file it writes. The
wording below is an example; the path and the event names are fixed:
hooks: restored amplihack's hooks block in /home/you/.claude/settings.json (PreToolUse, PostToolUse, StopFailure)
Each file it writes is also counted in hook-heals in the rotate state
directory, one Unix time per line, kept for 24 hours. amplihack profile
rotate status prints the count on its own line, just before log::
hooks repaired: none in the last 24h
hooks repaired: 3 in the last 24h (last 2026-11-11T16:51:40Z); something is still removing amplihack's hooks
A count above zero means some program is still removing the hooks after each repair. The repair keeps sessions working, but the cause has to be found: see the program that stripped the file.
Merge rules¶
The merge changes only settings["hooks"].
- Added or corrected: every spec entry for the current
limit_resumevalue, with the current hooks binary path, timeout, matcher andasyncRewake. - Removed: amplihack's own wrappers that are stale (an old binary path, a
duplicate, a
StopFailureentry whenlimit_resumeis off), any wrapper whose command containstools/xpia/hooks/, and any wrapper left empty by these removals. A wrapper whosehookslist was already empty is not amplihack's and is kept. - Kept byte-equal and in order: every wrapper that amplihack does not own. A hook command is amplihack's only in one of these forms:
- a path whose file name is exactly
amplihack-hooks(oramplihack-hooks.exe), quoted or bare, followed by one known subcommand and nothing else, for example"/home/u/.local/bin/amplihack-hooks" stop; - the exact selected hooks binary path followed by one known subcommand
and nothing else, including a custom basename selected through
AMPLIHACK_AMPLIHACK_HOOKS_BINARY_PATHwhen no deployed binary exists; - a legacy script under
tools/amplihack/hooks/; - an XPIA script under
tools/xpia/hooks/.
A foreign hook such as block-tmux-kill.py is kept even when another field
mentions amplihack. So is a user's wrapper whose name or arguments mention
amplihack-hooks, such as ~/bin/my-amplihack-hooks-wrapper stop or
sh -c '/opt/x/amplihack-hooks stop'.
- Never touched: env, permissions, statusLine (outside install),
model and every other top-level key.
The merge is idempotent. Merging an already-current file reports Unchanged,
and the file is not rewritten: its bytes and modification time stay the same
and no backup is made.
XPIA¶
No writer adds an XPIA hook, and every writer removes one it finds. No writer
adds, changes or removes keys under env. Where env.XPIA_ENABLED is absent
it stays absent; where it is "false" it stays "false". XPIA asset checks
in amplihack install (#1266) are unchanged.
Backups¶
Two writers go through update_file_with_backup and so back up the file
before they change it: amplihack install (and update), and the launch
repair. Each writes a backup only when the merge changes the file. The backup
is written from the bytes already read, opened with
O_CREAT | O_EXCL | O_NOFOLLOW and mode 0600. No code path ever restores a
backup over a settings file.
Profile refresh, profile seeding and the rotator cycle call merge_file and
make no backup. The #2589 deny pass calls update_file and makes none
either, so a launch that adds only the deny entries changes
~/.claude/settings.json and leaves the backup directory empty. It adds
entries and never removes or rewrites one, so there is nothing a backup would
restore.
Profile refresh runs only inside amplihack install, which is the explicit
installer; it does not consult the install stamp. Profile seeding is implicit
and writes nothing from a binary older than the install stamp.
There is no lock between amplihack's writers and other programs. If another
process changes hooks between amplihack's read and its rename, that change
is lost; changes to other keys made in the same window are lost too. This is
accepted: the window is one read, merge and rename, and the next drift check
reports any result.
Drift¶
The drift check compares a file's hooks object against the block and
returns three lists of event names.
| List | An event is listed when |
|---|---|
missing |
A spec entry for the event has no matching wrapper |
differing |
amplihack's wrapper for the event exists but its binary path, timeout, matcher or asyncRewake differs, or it appears more than once |
extra |
The file holds an amplihack-owned wrapper not in the spec: an XPIA hook, or StopFailure when limit_resume is off |
One event may appear in both missing and extra. A file is clean when all
three lists are empty. The check is read-only.
amplihack install uses the same check for its post-install contract
validation, and the implicit-install warning uses its missing list. A file
that contains no amplihack hook at all reports every event as missing.
Launch settings file¶
When the agent binary is claude, amplihack launch and amplihack claude
write the block to a private file and pass it to Claude Code as an extra
settings source:
The runtime home is $AMPLIHACK_HOME when it is set and non-empty and does
not name a Git checkout. Otherwise it is $HOME/.amplihack. The resolved
path must be absolute. This keeps the launch hooks file out of the checkout
when a recipe sets AMPLIHACK_HOME to its bundle source (#2361).
--settings is placed before the arguments you pass. The path is passed, never
inline JSON, so no settings text appears in the process command line (#2030).
The file holds only the hooks object:
It contains no env, permissions or other key. It is written with mode
0600 inside runtime/ (mode 0700), and only when its bytes would change.
Claude Code reads --settings as a source separate from the user settings
file, so a session started through amplihack has amplihack's hooks even if
something has stripped ~/.claude/settings.json.
Duplicate hook commands¶
The commands in the launch file and the home file are built by the same code from the same binary path, so they are byte-identical.
Claude Code runs a handler once when the same handler is defined in more than one settings file (https://code.claude.com/docs/en/hooks), so the session runs each amplihack hook once.
A Claude step with extra command hooks whose amplihack is older than the
install stamp builds its launch file from its own release's hook list, with
the installed amplihack-hooks. A hook whose command is the same in both
releases still runs once.
Extra command hooks for agent steps¶
Set AMPLIHACK_EXTRA_HOOKS_FILE to the path of a Claude Code settings file
before launching amplihack. Recipe and sub-recipe agent steps inherit the
setting. A relative path is resolved from the directory where you invoke
amplihack, including when recipe run -w selects a different working
directory. The path must be UTF-8. A path that is not stops the launch with
an error that names the setting, in a direct launch and in a detached recipe
alike, and it is never read as unset. Each launch reads the file's hooks
object and reports any other top-level keys it ignored together in one notice.
For recipe and sub-recipe steps, the notice identifies the step and appears in
the run's output after the attempt returns. The file must be readable, owned
by the effective user, and free of group or other write permissions. A missing
file, a symbolic link, duplicate JSON keys, or invalid settings stop the launch
with an error that names the file and the reason.
Claude launches append the extra command hooks after amplihack's hooks for
each event. A hook is added once: an extra entry is dropped only when an
earlier entry has the same event, the same matcher and the same hook in every
field, including the full command and its arguments. Two hooks that differ in
any of these are both kept. An omitted matcher, an empty matcher and "*" are
distinct.
The extra hooks go only into the settings file that amplihack writes for the
launch. Every --settings source the step already has stays on the command
line, in its order, after amplihack's file. Amplihack does not read or merge
them. The file is private to the launch and is removed when the launch ends.
If the merged file is larger than the 2 MiB Claude Code accepts, the launch
stops with an error that names the extra hooks file and the reason. No hook is
dropped silently. With the setting unset, launches use the shared settings
file and behave as they did before.
A recipe run keeps the amplihack it started with, so after a newer install
its binary is older than the install stamp. Its Claude steps still start with
the extra hooks. The launch writes only its own settings file, and amplihack's
hooks in that file run from the installed release, through the same
amplihack-hooks as the user's Claude settings. The shared launch settings
file, the user's Claude settings and profile seeding are left to the installed
release. If no amplihack-hooks binary is found, the launch stops with an
error that gives the path of the extra hooks file.
The if field is supported on PreToolUse, PostToolUse,
PostToolUseFailure, PermissionRequest, PermissionDenied, and
PreSkillShellCommand. On other events, the launcher reports the file and
event and stops the launch.
Some steps start without the extra hooks, and the run log names each one once with the events that were left out:
- Codex steps.
- Copilot steps.
- Steps launched in the Docker container. The host names the step when it starts the container. The setting is not passed into the container.
- Claude steps in safe mode, whether
--safe-modeis passed,CLAUDE_CODE_SAFE_MODE=1is inherited, or the LiteLLM proxy is in use. Safe mode itself is unchanged.
Foreground runs write the line to recipe.log in the run directory, and
detached runs append it to the detached session log. If the append fails, the
recipe reports the write error and the original notice in its run output, so
a successful run still shows it. Extra hooks for Codex are tracked in #3480,
equivalent Claude wildcard matchers in #3481, and Docker in #3485.
The guidance check continues to use amplihack's own hooks.
When the file is not used¶
Checked in this order. With extra command hooks configured, a Claude launch
reports an error if it cannot create the launch settings file. Otherwise it
continues without --settings.
| Condition | Behaviour |
|---|---|
The agent binary is not claude |
Nothing written |
The LiteLLM proxy or safe mode is in use (it passes --setting-sources "") |
Nothing written |
You passed --settings <x> or --settings=<x> and supplied no extra hooks |
One notice line; the home-file repair still runs |
| The running binary is older than the install stamp | Nothing written, unless extra command hooks are configured: then only the launch's own file |
No amplihack-hooks binary is found, or its path contains unsafe characters |
Nothing written |
| The resolved runtime home is not owned by you, or is writable by group or others | Nothing written |
runtime/ is a symlink, is not owned by you, or cannot be made 0700 |
Nothing written |
| Writing the file fails | One warning line |
When the skip is because the resolved runtime home or runtime/ is not private, the
launch prints one warning that names the directory and says it must not be
group- or other-writable. The other skips are logged at debug level only.
A --settings that appears after -- is an argument to something else and
does not suppress the injection.
Doctor report¶
amplihack doctor checks every settings file that should hold the block and
prints one line per file, in this order:
~/.claude/settings.json;- each
<profile root>/<name>/settings.json, sorted by profile name; $AMPLIHACK_HOME/runtime/launch-hooks-settings.json.
Each line has the form <path>: <state>, where the state is one of:
| State | Meaning |
|---|---|
clean |
The file matches the block |
absent |
The file does not exist |
unparseable (<reason>) |
Not valid JSON; the reason gives line and column only |
refused (<reason>); replace it with a regular file you own |
Not read, for a file-safety reason |
drift missing=[..] differing=[..] extra=[..] |
The file differs from the block; lists hold event names |
absent; repo-local install clean |
Home file only: absent, and <cwd>/.claude/settings.json matches the block |
When the profile root cannot be resolved or listed, or the amplihack home is unknown or not absolute, doctor prints one line for that source instead of leaving its files out:
profiles: cannot list (permission denied)
launch file: cannot list (amplihack home unknown or not absolute)
Example with one stripped profile. The <path>: <state> lines are fixed; the
✗ hooks installed heading and the indentation are an example of doctor's
existing grouping:
$ amplihack doctor
✗ hooks installed
/home/you/.claude/settings.json: clean
/home/you/.amplihack/claude-profiles/team/settings.json: drift missing=[PreToolUse, PostToolUse, StopFailure] differing=[] extra=[]
/home/you/.amplihack/claude-profiles/work/settings.json: clean
/home/you/.amplihack/runtime/launch-hooks-settings.json: clean
The check fails when the home file is anything other than clean, when a
profile or launch file that exists shows drift, is unparseable or is refused,
or when a source cannot be listed. An absent profile or launch file passes.
An absent home file passes only when the project-local
<cwd>/.claude/settings.json is clean, which is a repo-local install (#1088).
A project-local file is read only in that case and has no line of its own. Failure uses doctor's existing exit
code; there is no new one.
The check is read-only: it changes no bytes and no modification times. Its
output never contains file content, only paths, event names, fixed phrases,
io::ErrorKind names and JSON line and column numbers.
Doctor does not check:
- the project-local
<cwd>/.claude/settings.json, except as above when the home file is absent; $CLAUDE_CONFIG_DIR/settings.json. WhenCLAUDE_CONFIG_DIRis set, the file the session reads may differ from the home file doctor reports.
To fix drift, run amplihack install. The live profile's file is repaired by
the next rotator cycle; other profile files are repaired by profile refresh.
File safety¶
Every read and write of a settings file in this module follows these rules.
| Rule | Detail |
|---|---|
| No symlinks | Opened with O_NOFOLLOW; a symlink is refused (is a symlink) |
| Regular files only | A FIFO, socket or directory is refused |
| Size limit | Files over 1 MiB are refused |
| Owner | A file not owned by the effective uid is refused |
| Hard links | A file with more than one link is refused at replace time |
| Root must be an object | A file whose JSON root is not an object is refused and left unchanged |
Well-formed hooks |
A hooks value that is not an object, or an event value that is not an array, is unparseable and left unchanged; it is never replaced |
| Atomic write | Temp file with O_EXCL and mode 0600, fsync, rename |
| Write only on change | An unchanged file keeps its bytes and modification time |
| No creation | Only amplihack install creates a settings file; every other writer reports Absent |
| No content in messages | Reasons and log lines never quote the file |
| Unix only | On other platforms every file operation returns refused (unix-only) |
The first write by this module sets the file mode to 0600. A home
settings.json that was 0644 becomes 0600 after its first repair.
A settings.json that is a symlink (for example one managed by GNU Stow or
another dotfile manager) or has more than one hard link is refused by every
writer, including amplihack install. Before this change install wrote
through the link; now it prints a warning naming the file and the reason,
reports "Settings.json configuration had issues" and finishes its other
steps. amplihack doctor reports the file as refused. Replace the link with a
regular file to let amplihack manage its hooks.
Before any profile file is written, hook_path_refusal checks the profile
root, so a test or tool running with a throwaway HOME cannot write a real
profile (#1699).
If two processes change the hooks object at the same moment, the later write
wins. There is no lock or retry.
Environment variables¶
| Variable | Effect |
|---|---|
CLAUDE_CONFIG_DIR |
Launch repair targets $CLAUDE_CONFIG_DIR/settings.json. Used only when set, non-empty and absolute. Install, the rotator cycle and doctor ignore it |
AMPLIHACK_HOME |
Runtime home for runtime/launch-hooks-settings.json when set, non-empty and not a Git checkout; otherwise $HOME/.amplihack. The resolved path must be absolute |
AMPLIHACK_SKIP_AUTO_INSTALL |
Suppresses the launch repair |
AMPLIHACK_CLAUDE_PROFILE_ROOT |
Profile root for refresh, seeding, the rotator heal and doctor |
AMPLIHACK_EXTRA_HOOKS_FILE |
Optional Claude Code settings file containing extra command hooks for agent launches. Unset by default. |
Module interface¶
crates/amplihack-cli/src/commands/install/hook_block.rs:
pub(crate) struct HookTarget { pub bin: PathBuf, pub limit_resume: bool }
/// None when no hooks binary is found or its path has unsafe characters.
pub(crate) fn hook_target() -> Option<HookTarget>;
pub(crate) fn block(t: &HookTarget) -> serde_json::Value;
pub(crate) fn merge(settings: &mut Value, t: &HookTarget) -> Merge; // Changed | Unchanged
pub(crate) fn drift(settings: &Value, t: &HookTarget) -> Drift; // missing, differing, extra
pub(crate) enum FileMerge { Written, AlreadyCurrent, Absent, Unparseable(String), Refused(String) }
pub(crate) fn merge_file(path: &Path, t: &HookTarget) -> FileMerge;
pub(crate) fn update_file(path: &Path, f: impl FnOnce(&mut Value)) -> FileMerge;
pub(crate) fn update_file_with_backup(path: &Path, f: impl FnOnce(&mut Value)) -> FileMerge;
pub(crate) enum FileDrift { Clean, Absent, Unparseable(String), Refused(String), Drift(Drift) }
pub(crate) fn drift_file(path: &Path, t: &HookTarget) -> FileDrift; // read-only
FileDrift maps to the doctor states: Clean to clean, Absent to
absent, Unparseable(r) to unparseable (r), Refused(r) to
refused (r) and Drift(d) to the drift missing=[..] differing=[..]
extra=[..] line. A reason holds only a path, an event name, a fixed phrase or
an io::ErrorKind name, never text from the file.
Drift::is_clean() is true when all three lists are empty; Drift::lines()
gives the strings used by the install contract validation.
Profile refresh maps FileMerge to its Refresh result:
FileMerge |
Refresh |
|---|---|
Written |
Updated |
AlreadyCurrent |
Unchanged |
Absent |
Missing |
Unparseable(r), Refused(r) |
Skipped(r) |