DEV Community

Sora Terui
Sora Terui

Posted on Edited on

My AI Skips Written Rules, So I Turned One Into a Check: A Write-Time Guard Hook

TL;DR

Rules written as text (AGENTS.md and the like) get skipped by the AI on a bad day. For a rule that kept getting broken, I replaced the sentence with a check: validate on write, and refuse the write if it violates the rule.

This post covers: (1) what started it (a reader comment on my previous post), (2) what I researched (Claude Code hooks, validation tools, where a check cannot be bypassed), (3) what I built (a standalone script with three entry points) and the live test, and (4) what went wrong and the limits.

Previous post: https://dev.to/sora_uzu/i-put-my-ais-memory-in-markdown-and-git-the-failures-i-fixed-along-the-way-kfb

What started it

A reader commented on my previous post. In short:

  • "None of these fixes is 'ask the AI to be careful'" is the right instinct.
  • But most of the fixes are still text the agent reads, so it can skip one on a bad day.
  • What held best became a check: for example, make a fact / guess / unconfirmed split a required field on every record, validated on write or in a pre-commit hook, so a record without it is refused instead of saved.

I had the same problem. My meal-log rule, "always include the fixed daily items in the totals", was written down and still forgotten four times. After the fourth time, what I wrote was... another sentence of rule text. The comment was right.

What I researched

1. Stopping a write: Claude Code PreToolUse hooks [1]

From the official docs:

  • A hook runs before a tool call and receives JSON on stdin (tool_name, tool_input, tool_use_id, and more).
  • For Write, tool_input has file_path and content. For Edit it has file_path, old_string, new_string, replace_all. file_path is always expanded to an absolute path.
  • Exit code 2 blocks the call, and stderr goes back to the model. Other codes, including 1, are non-blocking errors. To enforce a policy, use 2.
  • You can also return JSON with permissionDecision: "deny" and a reason.
  • Caveats the docs state: a file rewritten through Bash is not seen by an Edit|Write matcher, and a timed-out hook does not block by default. For hard deny rules, the docs point you to permissions, not hooks.

2. Reports that it does not block

There is a GitHub issue saying a PreToolUse hook exiting with 2 still let a Write/Edit go through [2], and a similar one for Bash [3]. Both were closed automatically as duplicates with no maintainer reply, so I cannot tell from the issues whether it was fixed. Before you rely on it, test on a throwaway file.

3. Tools that validate required frontmatter [5][6]

docmeta, mdtype, mdschema, docuchango, remark-lint-frontmatter-schema and others exist. The commenter also mentioned iwe, a Markdown CLI with schema checks; its release notes say changes that violate a bound schema are rejected.

These validate the frontmatter of each file. My meal log is one file with a section per date, so they did not fit.

4. Where a check cannot be bypassed [4]

  • A pre-commit hook alone has been bypassed by agents using git commit --no-verify, in several reports.
  • People layer defenses: a write-time hook, a hook that rejects --no-verify, the same checks in CI. The same sources say none of this stops a determined agent completely.

What I built

My policy: do not depend on a specific AI service. The check is a standalone script; the AI hook is a thin entry point that just calls it.

How the write-time check works: the AI writes, a layer-1 hook, a layer-2 PostToolUse hook and a layer-3 pre-commit all call the same check script, which passes or flags a violation

The check (standalone script)

Rule: if a dated section (## YYYY-MM-DD) has content, it must contain a line marked as the fixed items. On a violation, exit with code 2.

#!/usr/bin/env python3
import re, sys

HEADER = re.compile(r"^## (\d{4}-\d{2}-\d{2})")

def check(text):
    errors, sections = [], []  # (date, lines)
    for line in text.splitlines():
        m = HEADER.match(line)
        if m:
            sections.append((m.group(1), []))
        elif sections:
            sections[-1][1].append(line)
    for date, lines in sections:
        body = [l for l in lines if l.strip()]
        if body and not any("固定" in l for l in body):   # "固定" = "fixed"
            errors.append(f"{date}: no line for the fixed daily items. Add it to the totals and write a 'fixed' line")
    return errors

def main():
    src = sys.argv[1] if len(sys.argv) > 1 else "-"
    text = sys.stdin.read() if src == "-" else open(src, encoding="utf-8").read()
    errors = check(text)
    for e in errors:
        print(e, file=sys.stderr)
    return 2 if errors else 0

if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

A header-only section (tomorrow's empty entry) passes.

Layer 1, at write time (Claude Code hook)

The hook builds the full text as it would be after the write, then passes it to the check. For Write it is content; for Edit it is the current file with old_string replaced by new_string. On a violation it exits with 2.

#!/usr/bin/env python3
import json, os, subprocess, sys

TARGET = "nutrition-log.md"
CHECKER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "check_meal_log.py")

def main():
    data = json.load(sys.stdin)
    inp = data.get("tool_input") or {}
    path = inp.get("file_path", "")
    if os.path.basename(path) != TARGET:
        return 0
    if data.get("tool_name") == "Write":
        text = inp.get("content", "")
    elif data.get("tool_name") == "Edit":
        try:
            cur = open(path, encoding="utf-8").read()
        except OSError:
            return 0
        old, new = inp.get("old_string", ""), inp.get("new_string", "")
        text = cur.replace(old, new) if inp.get("replace_all") else cur.replace(old, new, 1)
    else:
        return 0
    r = subprocess.run([sys.executable, CHECKER, "-"], input=text, text=True, capture_output=True)
    if r.returncode != 0:
        sys.stderr.write("Meal log check failed: " + r.stderr)
        return 2
    return 0

if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

Register it in .claude/settings.json [1]:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "python3 \"${CLAUDE_PROJECT_DIR}/scripts/hooks_pretool_meal_log.py\"" }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Layer 2, right after a Bash command (PostToolUse hook)

Bash can write files with echo >>, sed -i and so on. Layer 1 picks its targets by tool name (Edit, Write), so Bash writes slip through, and you cannot reliably tell from the command string what it will write.

So I added a hook that checks the meal-log file itself right after any Bash command. Because it looks at the resulting file, it does not care how the write was done. The write has already happened, so it cannot block; its job is to tell the AI about the violation so it fixes it.

#!/usr/bin/env python3
import os, subprocess, sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG = os.environ.get("MEAL_LOG_PATH") or os.path.join(ROOT, "01-private", "nutrition-log.md")
CHECKER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "check_meal_log.py")

def main():
    sys.stdin.read()                      # the JSON payload is not needed here
    if not os.path.exists(LOG):
        return 0
    r = subprocess.run([sys.executable, CHECKER, LOG], text=True, capture_output=True)
    if r.returncode != 0:
        sys.stderr.write("Meal log check failed after a Bash write. Please fix: " + r.stderr)
        return 2
    return 0

if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

Register it in .claude/settings.json as a PostToolUse hook with the matcher Bash:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "python3 \"${CLAUDE_PROJECT_DIR}/scripts/hooks_posttool_meal_log.py\"" }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

What happens after the error
The write has already happened, so the file stays in violation. Instead of blocking, the hook sends the error text to the AI. In my test, the AI read the error and fixed the entry with Edit, adding the "fixed" line and the total. Until it was fixed, even a read-only Bash command (wc) showed the same error; after the fix, the next Bash command showed none. It makes a missed fix hard to overlook.

Layer 3, at commit time (git pre-commit)

The last line of defense, right before a commit. It also catches writes that slipped past layers 1 and 2.

#!/bin/sh
ROOT="$(git rev-parse --show-toplevel)"
LOG="$ROOT/01-private/nutrition-log.md"
[ -f "$LOG" ] || exit 0
python3 "$ROOT/scripts/check_meal_log.py" "$LOG" || { echo "pre-commit: meal log check failed" >&2; exit 1; }
Enter fullscreen mode Exit fullscreen mode

Install it with ln -sf ../../scripts/pre-commit.sh .git/hooks/pre-commit.

What I saw in a live test

  • Layer 1: I had the AI write a meal log with no "fixed" line. The write was blocked, and the check's message reached the AI. The file was not created. The "does not block" problem from the issues did not happen in my environment (this version).
  • The existing meal log passed in full (no false positives).
  • Layer 2: I appended a section without the "fixed" line through Bash on purpose. Right after, the hook's error message reached the AI (PostToolUse:Bash hook blocking error). I restored the log from a backup and confirmed it was identical.
  • Layer 3: I temporarily added a violating section and ran the hook. It stopped with exit code 1. After I restored the file, it passed.

What went wrong

  • My test input was broken JSON, and the hook crashed with an exception. That was my test's fault, but it points to something real. Per the docs, exit code 1 and timeouts are non-blocking, so if the hook itself breaks, the check silently lets everything through. In production you need to decide what happens when the hook fails.

Limits

  • It only checks that the line exists. It does not check that the numbers are right or that the totals include it.
  • Shell writes bypass layer 1. Layer 2 notices right after, but cannot block (the write has already happened); layer 3 catches them again at commit time.
  • Layer 2 runs after every Bash command (it is fast). While a violation remains, you get a notice after every Bash command.
  • An agent that tries could rephrase its way around the check. The official docs do not treat hooks as a security boundary.
  • This is one setup. I cannot promise the same result elsewhere.
  • If I switch AI tools, only the thin entry point needs rewriting. The check itself stays.

Takeaways

  • For a rule that keeps getting broken, a check that refuses the write beats adding more sentences.
  • Put the check in a standalone script that does not depend on an AI service, and keep the AI hook as just an entry point.
  • Before relying on it, test on a throwaway file that it really blocks, and check what happens when the hook itself fails.

Update (2026-11-24): making a crashed hook visible

Readers pointed out that a hook that fails still lets everything through. I looked it up, changed it, and tested it.

What the docs say

  • By default, a failed hook does not stop the action.
  • To stop it, set "onFailure": "block" (Claude Code v2.1.295 or later).
  • A hook can print JSON with a warning for the human (systemMessage) and text for the AI (additionalContext).

What I changed

I wrapped the end of each hook in a try/except, so a crash of the hook itself produces a warning.

if __name__ == "__main__":
    try:
        sys.exit(main())     # normal: 0 = allow, 2 = violation, block (unchanged)
    except Exception as e:   # only when the hook itself crashed
        warn("The check hook crashed. Nothing was checked. Cause: %r" % (e,))
        sys.exit(0)          # do not block
Enter fullscreen mode Exit fullscreen mode

warn() just prints systemMessage and additionalContext as JSON. I chose a warning over blocking because a broken meal-log check shouldn't stop every edit.

Situation What happens
No problem Allowed
Meal log violation Blocked (unchanged)
The hook itself crashed Allowed, but both the human and the AI get a warning (new)

What I saw when I tested it

I crashed the hook on purpose and watched Claude Code.

  • systemMessage: shown inside a collapsed "notifications" line. Easy to miss, and the AI does not see it.
  • additionalContext: reaches the AI, so the AI can tell me. I confirmed it for the hook before a tool call (PreToolUse) and after it (PostToolUse).

What is still not covered

  • A hook that never starts (for example, a wrong path). Only onFailure: "block" covers that, and I haven't tried it.
  • Protection against the check itself being edited (hashing), and CI. I'll add them if it becomes a problem.

Thanks to everyone who commented.

References

[1] Claude Code, Hooks reference: https://code.claude.com/docs/en/hooks

[2] anthropics/claude-code, issue 13744 (PreToolUse exit code 2 and Write/Edit): https://github.com/anthropics/claude-code/issues/13744

[3] anthropics/claude-code, issue 23284 (PreToolUse on Bash): https://github.com/anthropics/claude-code/issues/23284

[4] On agents bypassing pre-commit hooks: https://pydevtools.com/handbook/how-to/how-to-stop-ai-agents-from-bypassing-pre-commit-hooks/ , https://stevekinney.com/courses/self-testing-ai-agents/making-it-hard-to-cheat-the-guardrails , https://microservices.io/post/genaidevelopment/2025/09/10/allow-git-commit-considered-harmful.html

[5] Frontmatter validators: docmeta https://cdn.jsdelivr.net/npm/docmeta@4.14.0/README.md , mdtype https://github.com/serejke/mdtype , mdschema https://github.com/jackchuka/mdschema , docuchango https://github.com/jrepp/docuchango

[6] iwe (release notes): https://github.com/iwe-org/iwe/releases

Japanese version on Zenn: https://zenn.dev/uzunaru/articles/f67ac6f4d8a540

Top comments (9)

Collapse
 
anas_alkhatib profile image
Anas Alkhatib •

Really like that the check lives in its own script and the hook is only an entry point. One gap I ran into: the agent can also edit the check script or the hook settings, and then everything still passes. What helped me was saving a hash of the check files and the settings before the session, and failing the pre-commit if they changed. Same idea as your layer 3, just pointed at the rules themselves.

Collapse
 
sora_uzu profile image
Sora Terui •

Thanks, this is a real gap. The agent can edit the check script or the hook settings, and in my setup nothing would notice. I haven't hit it yet, so I'm not adding anything now, but hashing the check files and settings before the session and failing the pre-commit on a change is on my list for when it becomes a problem. Appreciate you sharing what worked for you.

Collapse
 
anas_alkhatib profile image
Anas Alkhatib •

Makes sense to wait until it bites. One cheap early warning in the meantime: a one-line check that prints a warning if the hook or check files show up in git diff. It costs nothing and tells you the day an agent first touches them.

Thread Thread
 
sora_uzu profile image
Sora Terui •

Thanks, I added it. A warning-only check in pre-commit now flags any commit that includes the hook scripts, the check script, or the hook settings. It never blocks a commit, and it prints a single line, so it should tell me the first time an agent touches them. Appreciate the practical suggestion.

Thread Thread
 
anas_alkhatib profile image
Anas Alkhatib •

Glad it helped, and nice that it never blocks a commit. I'm publishing a short write-up later today on what I saw when testing agents on failing tests, if you're curious.

Collapse
 
gimalay profile image
Dmytro Halichenko •

Glad it held up in a live test, and thanks for writing the whole thing out. On the fail-open problem: wrap the hook body in a try/except that exits 2 on any exception, so a crashed check blocks the write instead of passing it, and run the same check script in CI so a --no-verify commit still meets it once. One honest limit on iwe since you cited it (I work on it): its schema check validates each file's frontmatter, so it won't fit a log with one section per date unless each day becomes its own file.

Collapse
 
sora_uzu profile image
Sora Terui •

Thanks for the concrete suggestions. Wrapping the hook body in a try/except that exits 2 is exactly the fail-open fix I need, and running the same check in CI to catch --no-verify is a good point too. And thanks for being upfront about where iwe fits and where it doesn't. That helps me decide what to try.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

The hook failing open is the part that sticks. A check that dies quietly still looks like coverage.

Collapse
 
sora_uzu profile image
Sora Terui •

Thank you. That's the part I most wanted readers to take away: a check that fails silently can be worse than no check, because it looks like coverage.