YouMind
Iniciar sesión

Skill Engineering + Hooks: Why Claude Ignores Your CLAUDE.md and the Fix It Can't Skip (Full Course)

@0xarcos
INGLÉS27 nov 2026
356K
200
15
63
383

TL;DR

This guide details using Claude Code hooks to enforce skill compliance, addressing issues where agents skip steps defined in markdown files.

Uber evaluates one million agent skill invocations a month.

Last week Anthropic put skills and connectors into one plugin directory, 10,000+ deep.

70+ agent platforms now support the same skill format, from ChatGPT to Cursor to VS Code.

Skills are how agents learn a job now.

Here's the part I measured.

I run one skill in Claude Code every day: 58 files, 48 of them markdown. Three weeks ago I put a hook at the end of every run. It checks one thing: did Claude do what the skill says?

In 21 days it stopped Claude 126 times from finishing a job it hadn't finished.

422 skipped steps. Every one of them was written in the skill, in plain English.

The most common one wasn't a wrong answer. It was a right-sounding answer built without opening the file it was supposed to come from. 168 times.

Nothing in the reply would have told me.

Boris Cherny, who created Claude Code, has a name for the gap between what your team knows and what the agent does with it: a failure of automation. His fix is to turn the knowledge into infrastructure.

https://x.com/bcherny/status/2077460395279692197

This article is that, for the rules you already wrote.

Prompts → Agents → Harness → Loops → Graphs → Verification → Skills

Verification proves the work. Skills define the job. Hooks make sure the job gets done the way it's written.

Everything below runs in a real setup every day: the block log, the numbers, and every file you need. Works in any repo that runs Claude Code.

(It's long. The files at the end are the point.)

What you'll walk away with:

→ the 6 ways Claude skips a skill, with real counts, and the check that catches each one

→ why a longer CLAUDE.md makes every rule in it weaker

→ the two-question test that tells you where any rule belongs

→ how to write a skill description that fires on the right job, and only that job

→ the 4 hooks that turn a written rule into one Claude can't skip

→ one contract file that tells every hook what "done" means for every skill

→ the 3 numbers that tell you if any of it works

Let's build it.

00. The 30-second version

If you only read one section, read this one.

→ CLAUDE.md is loaded into every session, whole. Every line you add makes every other line weaker.

→ A skill loads only when the job matches its description. Rules for one job belong in that job's skill.

→ A rule that must never be skipped doesn't belong in markdown. It belongs in a hook.

→ Hooks are code that Claude Code runs at fixed points. The model doesn't get a vote.

→ One file, gates.json, says what each skill must read, must run and must report. Every hook reads it.

→ Start in observe mode. Read the log. Then enforce.

Put every rule in the cheapest layer that still gets it followed.

01. The 6 ways Claude skips a skill

"Claude ignored my rule" isn't a diagnosis. It's a mood.

Here is what my Stop hook actually caught in 21 days, sorted. Every row was a step written in the skill.

text
1SKIP WHAT HAPPENED TIMES → CAUGHT BY
2SKIP-READ answered without opening the file it needed 168 → must_read
3NO-CHECK CLAIM stated a fact without running the check 106 → must_run
4MISSING LINE left a required line out of the answer 65 → checklist ID
5UNMARKED left checklist items blank 52 → checklist ID
6NO LOG didn't write the record the skill asks for 20 → checklist ID
7NO SOURCE didn't verify against the source 3 → must_run
8 other 8
9 total 422
Arcos - inline image

Look at the top two rows. 274 of 422.

Neither one is the model being dumb. Both are the model being fast. It already had something plausible in context, so it answered from that instead of doing the slow step the skill asked for.

That's the pattern to design against. Not "Claude can't follow rules". Claude skips the expensive step when the cheap answer looks good enough.

A rule that says "read X first" is asking Claude to choose the slow path. Sometimes it won't.

So you stop asking.

02. One file, every task, every rule

First, why the rules get skipped at all.

Here's how a CLAUDE.md grows. Claude makes a mistake, you add a line. It's exactly how the Claude Code team works: one shared file, checked into git, and every time Claude does something wrong, the fix goes in.

https://x.com/bcherny/status/2007179840848597422

That works. For a while.

Then the file is 300 lines. Code style, deploy steps, the PR format, the one API that times out, the folder nobody touches. All of it loaded into every session, for every task, including the ones where 290 of those lines don't apply.

Karpathy named the cost early. Context engineering is filling the window with just the right information for the next step. Too little and the model can't do the job. Too much or too irrelevant, and the cost goes up while performance comes down.

https://x.com/karpathy/status/1937902205765607626

Arcos - inline image

Your PR rule isn't missing. It's sitting between a CSS rule and a staging-database rule, in a session where Claude is renaming a variable. When a PR finally comes up, deep into a long session, it's one line in a crowded window.

And the usual fix makes it worse. You write the rule again, in capitals. Now it's two lines in a more crowded window.

03. The two-question test

Every rule you write has two properties. Ask both, and you know where it lives.

Question 1: when is this true?

Question 2: can a program check it?

text
1TRUE FOR A PROGRAM CAN CHECK IT? IT LIVES IN
2every task no CLAUDE.md
3one job no that job's SKILL.md
4any task yes a hook
5one job yes a hook, scoped to that skill in gates.json
Arcos - inline image

That gives you three layers. Always, when, must.

text
1LAYER LOADS HOLDS CAN CLAUDE SKIP IT?
2CLAUDE.md every session, all of it 5-20 lines true for ALL work yes
3SKILL.md only when the job matches the rules for ONE job yes, less often
4HOOK on a fixed event checks, written as code no

Always. CLAUDE.md is for the handful of things true on every task. That's about it.

When. A skill is the rules for one job, and nothing else. How to open a PR. How to write the weekly report. How to cut a release.

Must. A hook is a rule turned into code. It doesn't ask Claude to remember anything. It checks.

Most setups have one layer. Everything is in CLAUDE.md, written as a request, and the agent decides what to honor.

Run the test on your own CLAUDE.md tonight. Most lines fail question 1.

04. A skill costs nothing until its job shows up

When Anthropic launched Skills, the one-line pitch was packaged instructions that teach Claude your way of working.

https://x.com/claudeai/status/1978855432123723909

The part that matters is how they load. Anthropic's engineering team laid it out in their guide to Agent Skills:

https://x.com/AnthropicAI/status/1978896757489594404

text
1LEVEL WHAT LOADS WHEN
21 name + description at session start, for every skill
32 the body of SKILL.md when the job matches the description
43 files the skill points to when a step needs them
Arcos - inline image

Twenty skills in a repo cost you twenty descriptions. The 300-line PR guide, the release checklist, the report template: none of them touch the window until the job that needs them.

That's why the fix for a bloated CLAUDE.md is not a shorter CLAUDE.md. It's moving each job's rules into that job's skill.

The Claude Code team ships a command for exactly this. /checkup cleans up unused skills and plugins to save context, and breaks a root CLAUDE.md into nested CLAUDE.md files plus skills.

https://x.com/bcherny/status/2074997570317779038

It scales. Uber's engineering team evaluates one million skill invocations a month, and their definition of a skill is the same: a markdown file for one job, like creating a pull request.

https://x.com/UberEng/status/2125008806249930999

And it travels. Agent Skills started as an experiment in Claude Code. 70+ platforms have integrated the standard since, and Anthropic donated it to the Agentic AI Foundation, next to MCP.

https://x.com/bcherny/status/2113333859907747871

Write the skill once. It works in the next tool too.

05. The description is the trigger

Level 1 is the only part Claude always sees. So the description isn't documentation. It's the switch.

Too vague and the skill fires on everything, which puts you back in the 300-line problem. Too narrow and it never fires.

text
1DESCRIPTION FIRES ON
2"Helps with git" everything that touches git
3"PR helper" almost nothing, no job named
4"Open a pull request in this repo. Use when the "open a PR", "send this for review",
5 user asks to open, create or send a PR, or to "ship it"
6 ship or submit a change for review."
Arcos - inline image

Three rules for a description that fires right:

→ name the job as a verb: open, write, cut, review

→ list the words a person actually types when they want it

→ one job per skill. Two jobs means two skills

Then test it the boring way. Fresh session, ask for the job in your own words, check the skill loaded. If it didn't, the description is wrong, not Claude.

06. Heavy skill? Fork it.

Some skills are long jobs. Research, audits, a migration plan. They read 40 files to produce one page.

Run that in your main session and the 40 files stay in your window for the rest of the day. Every later rule competes with them.

Skills have a fix for this built in. Add one line to the frontmatter:

markdown
1---
2name: audit-deps
3description: Audit this repo's dependencies for outdated and vulnerable packages. Use when the user asks to audit, check or update dependencies.
4context: fork
5---

Lydia Hallie from the Claude Code team explained it: the skill runs in an isolated subagent with a fresh context window, CLAUDE.md plus your skill as the prompt. Your main context only sees the final result, not the tool calls in between.

https://x.com/lydiahallie/status/2033603164398883042

The rule of thumb:

→ the skill reads a lot and returns a little: fork it

→ the skill edits files you'll keep working on in this session: don't

A forked skill keeps your main window clean. Which keeps every other rule in it louder.

07. Markdown asks. Code checks.

This is the line I'd tape to the monitor.

A skill makes the right rules show up at the right time. It still asks. And section 01 showed what happens to an ask when the slow path competes with a plausible answer.

Boris put the principle in one line in the post at the top of this article: if Claude writes a lint rule, a CI step or a routine instead of fixing an issue each time it shows up, that class of issue is automated forever.

Same with your rules. Anything a program can check, a program should check:

text
1RULE IN MARKDOWN SAME RULE AS CODE
2"never push to main" PreToolUse: the command doesn't run
3"never commit a key" PostToolUse: the file goes back to Claude
4"read CONTRIBUTING.md before a PR" Stop: no read, no finish
5"end with the checklist" Stop: no checklist, no finish

What stays in markdown is judgment. How to phrase the PR body. What counts as risky. What good looks like. Code can't check taste, so taste stays in the skill.

Everything else moves into a hook.

08. The 4 hooks that matter

Hooks are commands Claude Code runs at fixed points in the agent loop. They get the event as JSON on stdin. What they print, and the exit code they return, decide what happens next.

Arcos - inline image
text
1HOOK FIRES WHAT IT CAN DO
2UserPromptSubmit before Claude reads your prompt add text to its context
3PreToolUse before a tool runs exit 2: the tool call is blocked
4PostToolUse after a tool runs decision "block": the reason goes back to Claude
5Stop when Claude tries to finish decision "block": Claude keeps working

UserPromptSubmit puts the contract in front of Claude at the start, when it's cheapest. The prompt says "open a PR", the hook adds one line: read these, run these, end with the checklist.

PreToolUse is where "never" lives. The command is checked before it runs. A blocked command doesn't happen, and Claude gets the reason.

PostToolUse checks the file Claude just wrote, while Claude still remembers writing it.

Stop is the one that changes everything. Claude says it's done. The hook reads what Claude actually did in this turn and checks it against the skill. Steps missing, and Claude goes back to work.

One field makes the Stop hook safe: stop_hook_active. It's true when Claude is already continuing because of a Stop hook. Block once, then let Claude stop and warn yourself instead. A gate that can hold an agent forever is broken, not strict.

09. One contract for every skill

Here's the piece most hook setups miss.

If every hook carries its own rules, the rules live in two places. The skill says one thing, the hook checks another, and they drift apart in a week.

So the rules live in one file. Every hook reads it.

json
1{
2 "mode": "observe",
3 "skills": {
4 "open-pr": {
5 "trigger": "\\b(pr|pull request|open a pr|ship it)\\b",
6 "must_read": ["CONTRIBUTING.md", ".claude/skills/open-pr/checklist.md"],
7 "must_run": ["npm test", "npm run lint"],
8 "checklist": ".claude/skills/open-pr/checklist.md"
9 }
10 },
11 "deny": [
12 {"pattern": "rm\\s+-rf\\s+(/|~|\\.)(\\s|$)", "why": "deletes the repo or the home folder"},
13 {"pattern": "git\\s+push\\s+.*(--force|-f)(\\s|$)", "why": "rewrites shared history"},
14 {"pattern": "git\\s+push\\s+\\S+\\s+main(\\s|$)", "why": "nobody pushes to main directly"}
15 ],
16 "banned": [
17 {"pattern": "sk-[A-Za-z0-9_-]{20,}", "why": "an API key in a file"},
18 {"pattern": "console\\.log\\(", "why": "debug logging left in the code"}
19 ]
20}
Arcos - inline image

Read it as three promises:

→ skills: what each job must read, must run and must report before it's done

→ deny: commands that never run, however the request is phrased

→ banned: things that never land in a file

Look at the first block again with section 01 in mind. must_read is SKIP-READ. must_run is NO-CHECK CLAIM. The checklist is MISSING LINE, UNMARKED and NO LOG. The contract is the skip table, turned around.

The skill explains how to do the job. gates.json says what proves it was done. The hooks only enforce.

A new skill is one SKILL.md and one entry in gates.json. No new hook.

10. Build it in 30 minutes

Arcos - inline image
text
1your-repo/
2 CLAUDE.md the few rules true for all work
3 .claude/skills/open-pr/SKILL.md how to do the job
4 .claude/skills/open-pr/checklist.md what to report, item by item
5 .claude/gates.json the contract every hook reads
6 .claude/hooks/remind.py UserPromptSubmit: contract up front
7 .claude/hooks/pre_guard.py PreToolUse: commands that never run
8 .claude/hooks/post_check.py PostToolUse: things that never land in a file
9 .claude/hooks/stop_gate.py Stop: no contract, no finish
10 .claude/settings.json turns the 4 hooks on

The lazy way: one prompt

Open Claude Code in your repo, paste this article, then paste this.

text
1Set up the skill + hooks layer from the article above in this repo.
2
31. Create these files exactly as the article shows them:
4 CLAUDE.md (append if it exists), .claude/skills/open-pr/SKILL.md,
5 .claude/skills/open-pr/checklist.md, .claude/gates.json,
6 .claude/hooks/remind.py, pre_guard.py, post_check.py, stop_gate.py,
7 .claude/settings.json (merge with mine if it exists).
82. Replace npm test and npm run lint in SKILL.md and gates.json with
9 this repo's real test and lint commands.
103. Keep "mode": "observe" in gates.json. Do not switch to enforce.
114. On Windows without Git Bash, use the PowerShell form of each hook
12 from Step 8 ("shell": "powershell", python, $env:CLAUDE_PROJECT_DIR).
135. Add .claude/gate.log to .gitignore.
146. Show me the file tree. Don't change any app code.

Claude Code will ask before it writes anything into .claude/. Hooks and settings are protected files, so expect a few "allow?" prompts. That's the safety check working. Read each file, then say yes.

Then come back here, because the steps explain why each file exists.

Step 1. CLAUDE.md, cut down to "always"

markdown
1# Always
2- Plain words. Short answers.
3- Never push to main. Never force-push.
4- Anything you do more than once has a skill in .claude/skills. The rules live there, not here.
5- When a hook sends you back, do what it lists. Don't argue with it.

Four lines. Everything else moves into a skill or a hook.

The push rule is in two places on purpose. CLAUDE.md tells Claude the reason. pre_guard.py makes sure.

Step 2. The skill

markdown
1---
2name: open-pr
3description: Open a pull request in this repo. Use when the user asks to open, create or send a PR, or to ship or submit a change for review.
4---
5# Open a PR
6
7## Read first
8- CONTRIBUTING.md
9- .claude/skills/open-pr/checklist.md
10
11## Steps
121. Run the tests: npm test. Copy the summary line.
132. Run the linter: npm run lint.
143. Add one line to CHANGELOG.md under Unreleased.
154. Search the diff for keys and tokens.
165. Write the PR body with four parts: What, Why, How tested, Risk.
176. End your reply with the checklist block below. Mark every item.
18
19## Checklist block
20CHECKLIST open-pr:
21P1 [x] or [-] reason
22P2 ...
23
24## Done when
25The reply ends with "CHECKLIST open-pr:" and every item in checklist.md is marked [x], or [-] with a reason.

Read the last section twice. "Done when" is written so a program can check it.

Step 3. The checklist

markdown
1# open-pr checklist
2P1 tests ran, summary line pasted in the reply
3P2 lint clean
4P3 one CHANGELOG line under Unreleased
5P4 no keys or tokens in the diff
6P5 PR body has What / Why / How tested / Risk

Every item has an ID. The Stop hook reads the IDs from this file, so a new item in the checklist is a new item in the gate. Nothing else to change.

[-] is allowed. A skipped item with a reason is honest. A skipped item with no mark is what we're catching.

Step 4. remind.py, the contract up front

python
1# .claude/hooks/remind.py - UserPromptSubmit.
2# When a prompt matches a skill, put that skill's contract in front of Claude before it starts.
3import json, os, re, sys
4
5event = json.load(sys.stdin)
6root = os.environ.get("CLAUDE_PROJECT_DIR") or event.get("cwd", ".")
7gates = json.load(open(os.path.join(root, ".claude", "gates.json"), encoding="utf-8-sig"))
8prompt = event.get("prompt", "")
9
10for name, g in gates["skills"].items():
11 if re.search(g["trigger"], prompt, re.I):
12 print(f"Skill {name} applies. Read: {', '.join(g['must_read'])}. "
13 f"Run: {', '.join(g['must_run'])}. "
14 f"End the reply with 'CHECKLIST {name}:' and mark every item.")

One line, at the moment it's cheapest to follow. Prompts that don't match get nothing.

Every hook opens its files with utf-8-sig, not utf-8. Plenty of Windows editors save JSON with an invisible marker at the start, and plain utf-8 crashes on it. My first live run died on exactly that.

Step 5. pre_guard.py, the "never" list

python
1# .claude/hooks/pre_guard.py - PreToolUse on Bash or PowerShell.
2# The "never run X" lines from CLAUDE.md, as code. Exit 2 = the command does not run.
3import json, os, re, sys
4
5event = json.load(sys.stdin)
6root = os.environ.get("CLAUDE_PROJECT_DIR") or event.get("cwd", ".")
7gates = json.load(open(os.path.join(root, ".claude", "gates.json"), encoding="utf-8-sig"))
8cmd = event.get("tool_input", {}).get("command", "")
9
10for rule in gates["deny"]:
11 if re.search(rule["pattern"], cmd):
12 print(f"Blocked: {rule['why']}. Find another way, or ask the user.", file=sys.stderr)
13 sys.exit(2)

This one ignores the mode on purpose. Observe mode is for gates that might be wrong. "Don't delete the repo" is never wrong.

Step 6. post_check.py, things that never land in a file

python
1# .claude/hooks/post_check.py - PostToolUse on Write|Edit.
2# Reads the file Claude just wrote. A banned pattern sends Claude back to fix it.
3import json, os, re, sys
4
5event = json.load(sys.stdin)
6root = os.environ.get("CLAUDE_PROJECT_DIR") or event.get("cwd", ".")
7gates = json.load(open(os.path.join(root, ".claude", "gates.json"), encoding="utf-8-sig"))
8path = event.get("tool_input", {}).get("file_path", "")
9if not path or not os.path.isfile(path):
10 sys.exit(0)
11
12text = open(path, encoding="utf-8", errors="ignore").read()
13hits = [rule["why"] for rule in gates["banned"] if re.search(rule["pattern"], text)]
14if hits:
15 print(json.dumps({"decision": "block",
16 "reason": f"{os.path.basename(path)}: " + "; ".join(hits) + ". Fix the file, then go on."}))

My own setup has the same kind of hook for characters that must never appear in a final text. Written in the skill, that rule was a request. In a hook, it's a check.

Step 7. stop_gate.py, no contract, no finish

python
1# .claude/hooks/stop_gate.py - Stop.
2# If a skill ran in this turn, its contract has to be met before Claude is allowed to stop.
3# observe: log only. enforce: send Claude back once, then let it stop and warn you.
4import json, os, re, sys, time
5
6event = json.load(sys.stdin)
7root = os.environ.get("CLAUDE_PROJECT_DIR") or event.get("cwd", ".")
8gates = json.load(open(os.path.join(root, ".claude", "gates.json"), encoding="utf-8-sig"))
9mode = gates.get("mode", "observe")
10if mode == "off":
11 sys.exit(0)
12
13entries = []
14for line in open(event["transcript_path"], encoding="utf-8"):
15 try:
16 entries.append(json.loads(line))
17 except ValueError:
18 pass
19
20def parts(e):
21 c = (e.get("message") or {}).get("content")
22 return c if isinstance(c, list) else [{"type": "text", "text": c or ""}]
23
24def is_prompt(e):
25 return (e.get("type") == "user" and not e.get("isMeta")
26 and not any(p.get("type") == "tool_result" for p in parts(e)))
27
28start = max([i for i, e in enumerate(entries) if is_prompt(e)] or [0])
29turn = entries[start:]
30prompt = " ".join(p.get("text", "") for p in parts(turn[0]) if p.get("type") == "text") if turn else ""
31calls = [p for e in turn if e.get("type") == "assistant" for p in parts(e) if p.get("type") == "tool_use"]
32reply = "\n".join(p.get("text", "") for e in turn if e.get("type") == "assistant"
33 for p in parts(e) if p.get("type") == "text")
34
35missing = []
36for name, g in gates["skills"].items():
37 used = re.search(g["trigger"], prompt, re.I) or any(
38 c.get("name") == "Skill" and c.get("input", {}).get("skill") == name for c in calls)
39 if not used:
40 continue
41 read = [str(c["input"].get("file_path", "")).replace("\\", "/") for c in calls if c.get("name") == "Read"]
42 ran = " ".join(str(c["input"].get("command", "")) for c in calls if c.get("name") in ("Bash", "PowerShell"))
43 missing += [f"{name}: read {f}" for f in g["must_read"] if not any(r.endswith(f) for r in read)]
44 missing += [f"{name}: run {cmd}" for cmd in g["must_run"] if cmd not in ran]
45 ids = re.findall(r"^([A-Z]+\d+)\s", open(os.path.join(root, g["checklist"]), encoding="utf-8-sig").read(), re.M)
46 head = f"CHECKLIST {name}:"
47 if head not in reply:
48 missing.append(f"{name}: no '{head}' block at the end of the reply")
49 else:
50 block = reply.split(head)[-1]
51 missing += [f"{name}: {i} not marked" for i in ids if not re.search(rf"{i}\s*\[(x|-)\]", block)]
52
53if not missing:
54 sys.exit(0)
55
56with open(os.path.join(root, ".claude", "gate.log"), "a", encoding="utf-8") as log:
57 verb = "would-block" if mode == "observe" else "blocked"
58 log.write(f"{time.strftime('%Y-%m-%d %H:%M')} {mode} {verb}: {'; '.join(missing)}\n")
59if mode == "observe":
60 sys.exit(0)
61if event.get("stop_hook_active"):
62 print(json.dumps({"systemMessage": "Gate: still missing after one retry: " + "; ".join(missing)}))
63 sys.exit(0)
64print(json.dumps({"decision": "block",
65 "reason": "Not done. The skill contract is not met:\n- " + "\n- ".join(missing)}))

What it does, in plain words:

→ finds this turn in the transcript: your last prompt and everything after it

→ checks if a skill ran, by its trigger words or because Claude called it by name

→ checks the files the skill must read were read, and the commands were run

→ reads the checklist IDs from checklist.md and checks each one is marked

→ observe: writes the miss to gate.log. enforce: sends Claude back with the list

→ second miss in a row: lets Claude stop and tells you what's still missing

It doesn't trust Claude's summary of what it did. It reads what Claude did.

Step 8. settings.json, turning it on

json
1{
2 "hooks": {
3 "UserPromptSubmit": [
4 {"hooks": [{"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/remind.py\""}]}
5 ],
6 "PreToolUse": [
7 {"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/pre_guard.py\""}]}
8 ],
9 "PostToolUse": [
10 {"matcher": "Write|Edit", "hooks": [{"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/post_check.py\""}]}
11 ],
12 "Stop": [
13 {"hooks": [{"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/stop_gate.py\""}]}
14 ]
15 }
16}

On Windows without Git Bash, this file needs one more change. Claude Code then runs hook commands in PowerShell, where $CLAUDE_PROJECT_DIR comes out empty. Python can't find the script and exits with code 2, and code 2 means "block". Your prompt just disappears. That was my first live run.

The fix is two fields on each hook. Same for all four:

json
1{"type": "command", "shell": "powershell", "command": "python \"$env:CLAUDE_PROJECT_DIR/.claude/hooks/stop_gate.py\""}

Before you trust any of it, test it without Claude. Every hook reads JSON on stdin, so you can hand it a fake event:

bash
1echo '{"tool_input": {"command": "git push origin main"}}' | python3 .claude/hooks/pre_guard.py
2echo $?

You want "Blocked: nobody pushes to main directly" and a 2. On Windows PowerShell, check $LASTEXITCODE instead of $?. I ran 19 cases like this through all four hooks before publishing. All 19 pass.

11. The same prompt, live

Fake events prove each hook works alone. So then I put the demo repo in front of a real Claude Code session, gate on enforce, and typed the kind of prompt people actually type:

text
1Quick one: write a PR title and a short body for the greet.js change.
2Don't run anything, I already ran the tests.

First run, without remind.py. Claude opened greet.js and nothing else. No CONTRIBUTING.md, no checklist. The title didn't start with Add, Fix or Remove, which CONTRIBUTING.md asks for. The body said "Existing tests pass." on my word.

Then it tried to finish:

text
1Stop hook feedback:
2Not done. The skill contract is not met:
3- open-pr: read CONTRIBUTING.md
4- open-pr: read .claude/skills/open-pr/checklist.md
5- open-pr: run npm test
6- open-pr: run npm run lint
7- open-pr: no 'CHECKLIST open-pr:' block at the end of the reply

Second try: it read both files, changed the title to start with "Fix", rebuilt the body as What / Why / How tested / Risk, and wrote out the CHANGELOG line it was missing.

Same prompt, remind.py back on:

text
1RUN FIRST ANSWER AFTER ONE BLOCK
2no reminder read greet.js only, no checklist read both files, 4-part body
3reminder on read both files, 4-part body checklist marks fixed
4both tests not run: I said not to after the retry: let through, I got a warning

The reminder moved the reading to the first try. The gate caught what the reminder didn't.

And where my instruction and the skill disagreed, the gate didn't overrule me. After one retry it let Claude stop and told me exactly what wasn't done:

text
1Gate: still missing after one retry: open-pr: run npm test; open-pr: run npm run lint

Two more runs. "ship it. I'm in a hurry" with the reminder on: every step done on the first try, the gate stayed silent. And a direct "git push origin main": blocked before it ran. Claude didn't hunt for a workaround. It listed my options, opening a PR among them.

The live runs also found two bugs that 19 fake events didn't: the empty $CLAUDE_PROJECT_DIR on Windows and the invisible marker in gates.json. Both are fixed in the files above.

Test on a real session before you trust a gate.

12. One real run: 21 days of blocks

This is the part I can't make up, because the log won't let me.

My daily skill isn't open-pr. It's a research-and-writing job with a long list of steps: files to read before writing, checks to run before claiming anything, lines every answer must carry. Same design as above. Same Stop hook idea.

Every time it stopped Claude, from the first day it was on:

text
1DAYS BLOCKS
2week 1 (Nov 6-12) 59
3week 2 (Nov 13-19) 42
4week 3 (Nov 20-26) 25
5total 21 days 126
Arcos - inline image

And what happened right after each block:

→ 108 times, the next attempt passed the gate: the file got read, the check got run

→ 18 times, Claude missed again, and the hook let it through with a warning to me

→ 11 of week 3's 25 blocks came on one day: the day I built a second skill with new rules

The rules didn't change. The model didn't change. The only thing that changed is that skipping stopped being free.

13. The 3 numbers that tell you it's working

You can't tell from the replies. A skipped step reads exactly like a done one. That was the whole problem.

Track these instead, straight from gate.log:

text
1skips per week blocks in the log, this week vs last
2retry pass rate blocks fixed on the next try / all blocks
3let-throughs second misses the gate had to wave through

Mine, for the 21 days above:

text
1skips per week 59 → 42 → 25
2retry pass rate 108 / 126 = 86%
3let-throughs 18

How to read them:

→ skips per week should fall, then jump each time you add a skill. A jump after a new skill is the gate doing its job

→ a low retry pass rate means the reason is unclear, not that Claude is stubborn. Make the block message name the exact file or command

→ every let-through is a step Claude couldn't do even when told. That's not a gate problem. Rewrite that step in the skill

14. Start every gate in observe mode

The fastest way to kill this setup is to turn on enforce on day one.

The gate blocks something it shouldn't. Someone loses an hour. Someone deletes the hook. You're back to rules in markdown.

text
1MODE WHAT HAPPENS HOW LONG
2off nothing until the files exist
3observe logs "would-block", blocks nothing 1 to 2 weeks
4enforce blocks once, then warns you from then on

In observe, read .claude/gate.log once a day for the first week:

text
12026-11-27 17:37 observe would-block: open-pr: read CONTRIBUTING.md; open-pr: run npm test; open-pr: no 'CHECKLIST open-pr:' block at the end of the reply

Every line is one of two things. A real skip, so the gate works. Or a false alarm, so a trigger or a must_read is wrong. Fix gates.json, not the gate.

When a few days pass with no false alarms, switch "mode" to "enforce". The deny list was never in observe, so nothing changes there.

15. Every correction goes to its layer

The Claude Code team puts every correction into CLAUDE.md. Keep the habit. Change where the line goes.

text
1CLAUDE DID THIS THE LINE GOES
2the same mistake, on every kind of task CLAUDE.md, one line
3a mistake in one job that job's SKILL.md
4skipped a step it already knew checklist.md, one new ID
5ran something it must never run gates.json deny
6wrote something that must never ship gates.json banned

Boris runs a bigger version of this loop. His team gave Claude daily maintenance routines across their apps: a crash fuzzer, a dead-code remover, a duplicate unifier. In a few weeks the routines opened 388 PRs, and 180 were merged after review. When a routine gets something wrong, they ask Claude to tune the routine so it's better the next day.

https://x.com/bcherny/status/2088014489438621990

That's the ratchet. Every miss becomes a rule in the right layer, and the same miss stops being free.

And prune, or it grows back. Once a month:

→ /checkup: unused skills, MCPs and plugins out, root CLAUDE.md split into nested files plus skills

→ /skill-doctor: which skills you actually use

→ /context: what's in the window right now

Addy Osmani keeps a short list of these cleanup commands. Each answers a different question.

https://x.com/addyosmani/status/2098297991019057363

Any checklist item that hasn't fired in two months is a step Claude now does on its own, or a step nobody needs. Delete it.

16. Which layer is missing?

text
1SYMPTOM → MISSING
2Claude follows the rule in short sessions only → it's in CLAUDE.md, move it to a skill
3the skill exists but never loads → the description doesn't name the job
4the skill loads on every task → the description is too vague
5a long skill leaves your window full → context: fork
6Claude "forgot" a step it knows → a checklist ID + the Stop hook
7the answer sounds right but nothing was opened → must_read in gates.json
8a fact with no check behind it → must_run in gates.json
9Claude ran a command you banned → gates.json deny, PreToolUse
10a key or debug line shipped → gates.json banned, PostToolUse
11the gate blocks good work → back to observe, fix gates.json

Find your symptom. Fix that one layer first. You don't need all of it on day one.

17. What it can and can't do

Arcos - inline image

This setup CAN:

→ keep CLAUDE.md short, so the rules in it get followed

→ load each job's rules only when that job shows up

→ block commands you never want run, every time

→ catch keys and debug lines in files as they're written

→ stop Claude from finishing a job with steps skipped, and tell it which

→ show you, in one log, what Claude skips most

This setup CAN'T:

→ check judgment. "Write a clear PR body" stays a request

→ know about a rule you never wrote down

→ prove a step was done well. It proves it was done

→ make a vague skill precise. Bad steps get enforced too

→ run for free. Every retry costs tokens and time

18. Tonight: the one-evening protocol

→ 10 min: run the two-question test on every line of your CLAUDE.md

→ 15 min: paste the lazy prompt. Gate in observe

→ 10 min: move one job's lines into its first skill. Description = a verb + the words you'd type

→ 10 min: give Claude that job. Then open .claude/gate.log

→ 5 min: every "never" in your CLAUDE.md that's a command goes into deny

By the end of the week you'll know which of your rules Claude was following, and which ones it was only reading.

The checklist

Run it against your setup before you write one more rule.

text
1[ ] CLAUDE.md holds only rules true for every task, under 20 lines
2[ ] Every repeated job has its own skill
3[ ] Every description names the job as a verb and the words people type
4[ ] Long, read-heavy skills run with context: fork
5[ ] Each skill ends with a "Done when" a program can check
6[ ] Every checklist item has an ID
7[ ] One gates.json holds must_read, must_run, checklist, deny, banned
8[ ] Commands that must never run are in deny, not in prose
9[ ] The Stop hook blocks once, then warns. It never traps
10[ ] New gates start in observe
11[ ] You track skips per week, retry pass rate, let-throughs
12[ ] Once a month: /checkup, and delete what hasn't fired

The shift

text
1PROMPT what to say
2CONTEXT what it sees
3HARNESS where it runs
4LOOPS how it improves
5GRAPHS what runs together
6VERIFICATION how you know
7SKILLS what the job is
8HOOKS what can't be skipped

For a year we wrote rules for agents the way we write notes for people. Polite. In prose. All in one file.

Then we wondered why they got skipped.

A rule in the wrong layer is one line among hundreds. A rule in the right layer shows up when its job does. A rule in a hook can't be skipped.

The whole course in three lines:

Write each rule where it's true.

Check it where it's cheap.

Read the log, not the summary.

If this saved you a month of rules Claude quietly skipped:

→ Bookmark it. The files and the checklist are built to steal.

→ Follow @0xarcos - this is Field Manual Nº 004: Skill Engineering + Hooks. The next one goes deeper.

→ Reply with the rule Claude keeps skipping in your setup. I'll tell you which layer it belongs in.

Guardar con un clic

Lee artículos virales en profundidad con IA en YouMind

Guarda la fuente, haz preguntas concretas, resume el argumento y convierte un artículo viral en notas reutilizables en un único espacio de trabajo con IA.

Explora YouMind
Para creadores

Convierte tu Markdown en un artículo de 𝕏 impecable

Cuando publicas tus propios textos largos, dar formato en 𝕏 a imágenes, tablas y bloques de código es un fastidio. YouMind convierte un borrador completo en Markdown en un artículo de 𝕏 impecable y listo para publicar.

Prueba Markdown a 𝕏

Más patrones por descifrar

Artículos virales recientes

Explorar más artículos virales