Claude Code hooks, skills and memory: where setups go wrong

Hook exit codes that do not block, rules that never load, skills that abort and memory that stays on one machine: the failure modes and the fix for each.

Published

Updated

Reading time

11 min

A hook script crashes with exit code 1, and the command it was meant to stop runs anyway. Nothing looks wrong: no error, no warning, a guard that has been decorative since the day it was written. It is the most dangerous mistake available in Claude Code configuration, and it is a good place to start, because it shows the difference that organises everything else here. CLAUDE.md, rules, skills and auto memory are context that the model reads and may weigh against other things. Hooks and permission rules are code the harness runs whatever the model decides. The memory documentation says it plainly: Claude treats CLAUDE.md as context, not enforced configuration, and points to a PreToolUse hook when an action must be blocked.

What follows are the traps I would check for first when a setup misbehaves, each with what you see, why it happens, and the fix. For how the layers fit across many repositories, see setting up Claude Code for a multi-repo workspace.

Trap: a hook that fails but does not block#

What you see. A guard hook exists, and a command it should refuse goes through.

Why. For command hooks, exit 0 means proceed, exit 2 blocks the action and sends stderr back to Claude as the reason, and any other non-zero code is a non-blocking error: the action goes ahead. The hooks reference warns about exactly this, since 1 is the conventional Unix failure code. A script that dies on a missing jq, a syntax error or an unset variable under set -u exits non-zero and silently lets everything through.

Fix. Block deliberately: exit 2 with the reason on stderr, or exit 0 and print a deny decision as JSON. Test the script by piping a sample payload into it by hand, including the case where its dependencies are missing. For checks where a crashed hook must also stop the action, the documentation describes an onFailure: "block" setting for hooks.

Trap: a guard that is a seatbelt, not a boundary#

What you see. A hook that blocks terraform apply against production is bypassed by a command written slightly differently.

Why. A hook matches text. A single regular expression over the whole command string misses wrapped forms (sh -c, a subshell, a variable prefix) and matches things it should not, such as a commit message that mentions the command. The more clever the pattern, the more it looks like a boundary and the less it is one.

Fix. Do two things. First, make the guard tokenise rather than pattern-match: split the command into segments at operators and quotes, find the real executable, and read its first non-flag argument. The version below does that. Second, do not let the hook be the only control. The boundary for production is that the credentials a session runs with cannot apply to production at all, which is what least-privilege IAM is for. Add a permission rule as well, which the harness enforces itself and which does not depend on a script surviving.

The if field narrows when the script runs, using permission-rule syntax, so it only starts for matching commands. The documentation calls the filter best effort and says to use the permission system for a hard allow or deny, so the script below does its own parsing instead of trusting it:

.claude/settings.jsonjson
{
  "permissions": {
    "deny": ["Bash(terraform apply *)", "Bash(terraform destroy *)"]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-terraform-apply.sh",
            "timeout": 10
          }
        ]
      }
    ]
  }
}
.claude/hooks/block-terraform-apply.shbash
#!/usr/bin/env bash
# PreToolUse guard: refuse terraform apply/destroy from an agent session.
set -uo pipefail
 
deny() {
  jq -n --arg reason "$1" '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: $reason
    }
  }'
  exit 0
}
 
cmd=$(jq -r '.tool_input.command // ""')
 
# Turn operators, quotes and subshell markers into line breaks so that
# "cd x && terraform apply", "sh -c 'terraform apply'" and "$(terraform apply)"
# all yield a segment that starts with the real command.
segments=$(printf '%s' "$cmd" | tr ';&|()`"'"'"'' '\n')
 
while IFS= read -r segment; do
  read -r -a words <<<"$segment"
  [ "${#words[@]}" -gt 0 ] || continue
 
  i=0
  # Skip leading VAR=value assignments.
  while [ "$i" -lt "${#words[@]}" ] && [[ "${words[$i]}" == *=* ]]; do i=$((i + 1)); done
  [ "$i" -lt "${#words[@]}" ] || continue
  [ "$(basename "${words[$i]}")" = "terraform" ] || continue
 
  # The subcommand is the first word that is not a flag, so
  # "terraform -chdir=envs/prod apply" is caught as well.
  for word in "${words[@]:$((i + 1))}"; do
    case "$word" in
      -*) continue ;;
      apply | destroy) deny "terraform $word runs from the pipeline, not from a session." ;;
      *) break ;;
    esac
  done
done <<<"$segments"
 
exit 0

It errs towards blocking: a commit message containing the words "terraform apply" inside quotes will be refused, which is a nuisance and not a hole. A determined rewrite, such as a script file that calls terraform, still gets past it. That is the reason for the permission rule and the credentials.

Trap: a rule in CLAUDE.md that is silently ignored#

What you see. An instruction you wrote is not followed.

Why. Four causes account for nearly all of it, and they are cheap to tell apart.

  1. The file did not load. Run /context and check the memory files list.
  2. Two layers contradict each other, and Claude picked one.
  3. The wording is not checkable. "Test your changes" gives nothing to verify; "run pnpm test before committing" does.
  4. The instruction lives in a nested file that has not been triggered, or in conversation that was compacted away.

Fix. For the first cause, the InstructionsLoaded hook tells you what loaded and why. Its input carries file_path, memory_type and load_reason, which is one of session_start, nested_traversal, path_glob_match, include or compact. A hook that appends those to a log answers "did my path-scoped rule ever load?" in one look:

.claude/settings.local.jsonjson
{
  "hooks": {
    "InstructionsLoaded": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '[.load_reason, .file_path] | @tsv' >> /tmp/claude-instructions.log"
          }
        ]
      }
    ]
  }
}

It does not fire for an AGENTS.md that Claude reads directly in place of a CLAUDE.md. It does fire for one that a CLAUDE.md imports, which is the simplest way to share a file with other tools: make the first line of CLAUDE.md @AGENTS.md and put Claude-specific notes below it.

For the second cause, /doctor prompt-audit asks Claude to look for contradictions, references to files that no longer exist and instructions written for older models. It reports with proposed edits and changes nothing until you ask, and it needs Claude Code v2.1.283 or later. For the third, rewrite. For the fourth, remember that the project-root CLAUDE.md is re-read from disk after /compact, but an instruction given only in conversation is not.

If an instruction must hold at a fixed point in the workflow, stop adjusting the wording. Make it a hook.

Trap: loading everything at launch#

What you see. Every session starts heavy, and the model follows any one rule less reliably than it used to.

Why. Whatever loads at launch is re-sent on every turn: the CLAUDE.md chain, rules without a paths field, the first 200 lines or 25KB of the memory index, and the name and description of every skill. The documentation puts the target at under 200 lines per CLAUDE.md, and notes that @path imports do not reduce cost because imported files load with the file that imports them. Block-level HTML comments are stripped before the content reaches Claude, so maintainer notes are free; comments inside code blocks are not.

Fix. Move file-type conventions into a rule with paths frontmatter, which loads only when Claude reads a matching file. paths is the only frontmatter field Claude Code reads from a rule:

.claude/rules/migrations.mdmarkdown
---
paths:
  - "db/migrations/**/*.sql"
---
 
# Migrations
 
- One schema change per migration file.
- Never edit a migration that has been merged; add a new one.
- New indexes on large tables use CREATE INDEX CONCURRENTLY.

Move multi-step procedures into skills, which cost a description until they are used.

Trap: a skill that aborts, goes stale or never fires#

A skill is a directory with a SKILL.md. Personal skills live in ~/.claude/skills/<name>/, project skills in .claude/skills/<name>/. Four behaviours catch people.

A command in the skill makes the whole invocation fail. A line beginning with an exclamation mark and a backtick-quoted command runs before Claude sees the skill, and its output replaces the placeholder. If the command exits non-zero, the entire invocation aborts with an error and Claude never sees the skill. Exit code 1 from search and comparison commands counts as a normal result with the default shell, but anything else fails. Commands that may legitimately exit non-zero need || true. In the release skill below, git describe exits 128 in a repository with no tags, which is the right outcome: the skill should not run blind.

.claude/skills/release-notes/SKILL.mdmarkdown
---
name: release-notes
description: Draft release notes from the commits since the last tag. Use when preparing a release.
disable-model-invocation: true
arguments: [version]
---
 
Draft release notes for version $version.
 
## Commits since the last tag
 
!`git log --oneline "$(git describe --tags --abbrev=0)"..HEAD`
 
Group the commits under Added, Changed and Fixed. Skip merge commits and
dependency bumps. Keep each entry to one line and link the pull request
number where the commit message has one.

Claude starts it when you did not want it to. disable-model-invocation: true stops Claude from invoking the skill on its own. Use it for anything with side effects.

The instructions only made sense at the moment of invocation. The rendered skill enters the conversation as one message and stays there across later turns; Claude Code does not re-read the file. Write standing instructions, not "step one, now do step two" narration.

allowed-tools stops applying. It grants permission for the listed tools during the turn that invokes the skill, and clears when you send your next message. Do not rely on it to pre-approve something for a long session.

A skill also never fires if its description does not say when to use it. The combined description and when_to_use text is truncated at 1,536 characters in the skill listing, so put the trigger first and keep it short. /skill-doctor shows what each of your skills costs in context and how often it is used, so you can find ones to turn off. It requires Claude Code v2.1.252 or later and needs feature-flag fetching to be available.

Trap: treating auto memory as shared or permanent#

What you see. Claude remembers a preference on one machine and not on another, or a teammate does not see a convention you thought was recorded.

Why. Auto memory is notes Claude writes for itself, of four kinds recorded in each file's type: user, feedback, project and reference. It is stored in ~/.claude/projects/<project>/memory/, derived from the git repository so worktrees of one repository share it. It is machine-local and not shared with the team. Only the first 200 lines or 25KB of the MEMORY.md index load at session start; topic files are read on demand.

Fix. Treat it as a draft inbox. Every few weeks run /memory, open the folder and read the files, which are plain markdown. Anything that is a team convention gets promoted into the committed CLAUDE.md; anything stale gets deleted. To switch it off for one project:

.claude/settings.jsonjson
{
  "autoMemoryEnabled": false
}

Globally, use the toggle in /memory or set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1.

Trap: a Stop hook that cannot be satisfied#

What you see. The session keeps going and will not finish.

Why. A Stop hook can block stopping with exit 2 or a block decision, which sends Claude back to keep working. If the condition it checks is one Claude cannot change, such as a CI status on a remote service or a file Claude is not allowed to edit, it asks again forever.

Fix. Check only conditions that Claude's next action can plausibly change (a test command, a linter), keep the hook fast, and give it a short timeout. A hook that runs your check and refuses to let the turn end until it passes is a legitimate way to make "done" mean something on unattended runs; just make sure the check can pass.

Trap: a committed hook is code on everyone's machine#

A hook committed to a shared repository runs on every teammate's machine and in every CI job that starts a session. Review hook scripts in pull requests the way you review CI configuration. Also remember that headless runs behave differently: claude -p runs a project's hooks without a trust prompt unless you pass --bare, which skips hooks, skills, auto memory and CLAUDE.md altogether.

Placing a new instruction#

When you are about to add a line to CLAUDE.md, three questions place it, in this order:

  1. Must it hold every time, with no judgement involved? Make it a hook or a permission rule. A sentence in CLAUDE.md can document it but is not the control.
  2. Is it a multi-step procedure that only some tasks need? Make it a skill.
  3. Is it a fact most sessions need? If you wrote it, it goes in CLAUDE.md, or in a path-scoped rule when it only applies to some files. If Claude learned it from your corrections, it lives in auto memory until you promote it.
Three questions, asked in this order, place almost every instruction.

The order matters because the cheap mistake is to start at question three. A line like "never run terraform apply against production" feels like a fact, so it lands in CLAUDE.md, and it works until the one session where it does not.

The same advice applies to the size of the setup. A small repository with one developer needs a 30-line CLAUDE.md with the build and test commands and the default auto memory. Add a hook the first time Claude does something you would never want repeated, and a skill the first time you paste the same checklist twice. Configuration written before the need exists encodes guesses, and guesses are the contradictory, stale instructions that /doctor prompt-audit ends up flagging later.

Share
All articles →

A layered CLAUDE.md, tight permissions, hooks, skills and scoped MCP servers: the setup that keeps Claude Code safe and cheap across dozens of repositories.

13 min

An agent does what the spec says, not what you meant. Scope, named files and an executable check turn a long unattended session into a reviewable diff.

12 min