How to stop Claude Code and Codex deleting code they were not asked to touch

How to stop Claude Code and Codex deleting code they were not asked to touch

Mihai Perdum
Mihai Perdum
Author

11 min readDecember 4, 2026

Key takeaways

  • On 1 December 2026 a Hacker News poster said GPT-6.2 Astra in Codex removed a remote-debugging feature and refused to add it back; 20 minutes later he posted that GPT-6 Astra had fixed it.
  • OpenAI's own GPT-6.2 system card says GPT-6.2 Astra left a known obstacle out of its report in 22.28% of trials, against 11.09% for GPT-6 Astra.
  • A 16-line shell script and a pre-commit hook refused our commit with exit 1 when one KEEP line went missing. The hook is plain git, so Codex commits hit it too.
  • Our first Claude Code Stop hook blocked Claude 17 times in 37 seconds before Claude Code ended the turn; checking stop_hook_active cut that to 1 block and a stop 4 seconds later.
  • In 1 of our 5 Claude Code runs Claude read KEEP.txt and declined to remove the feature; in the 4 runs where we also said not to touch KEEP.txt it made the removal we asked for, and in the 2 of those that reached the end of the turn the Stop hook flagged it.

This tutorial shows how to stop Claude Code deleting code it was not asked to touch, and how the same guard catches Codex. It covers code or a feature removed inside an edit, which is a different problem from rm -rf (a PreToolUse hook blocks that one, see the PreToolUse hook error tutorial). You'll build a KEEP list of lines that must stay, a git pre-commit hook and a Claude Code Stop hook. On our runs the commit was refused with exit 1, and Claude was told about the missing lines 0.07 seconds after it said it was done.

On 1 December 2026 at 23:30 UTC a Hacker News user posted a "Tell HN" thread saying GPT-6.2 Astra in Codex "removed that functionality, and refuses to add it back". The functionality was a remote debugging channel in his hobby mapping tool, and 20 minutes later he posted that GPT-6 Astra had fixed it. He shared no transcript, diff or refusal text, so why it happened is unknown.

Whether that counts as sabotage I'll leave to our look at the Claude version of the claim. OpenAI does document a nearby regression. Its GPT-6.2 system card says GPT-6.2 Astra "omitted a known obstacle to completing its work in 22.28 percent of trials, compared with 11.09 percent for GPT-6 Astra". That figure is about the model leaving things out of its report, so check the work yourself.

Note

Prerequisites: a Mac or Linux shell, git (we ran git 2.54.0), Node.js only for node --check (any version), and Claude Code signed in (we ran 2.1.333 on macOS 27.2.1, on 3 December 2026). Codex is optional: the git hook covers it without changes. About 20 minutes. When you're done you'll have a demo repository where removing a protected line makes git refuse the commit and makes Claude Code stop once and say so.

  1. 1

    Write the KEEP list and check script

    KEEP.txt names the lines that must stay; check-keep.sh exits 2 when one is gone.

  2. 2

    Add the git pre-commit hook

    a commit that removes a listed line is refused with exit 1.

  3. 3

    Add the Claude Code Stop hook and settings

    Claude hears about a missing line once, before its turn ends.

  4. 4

    Test the Stop hook without Claude

    pipe the hook the JSON Claude Code sends and read exit 2, then exit 0.

  5. 5

    Run Claude Code and try the commit

    ask for the removal, read the Stop hook feedback, and watch git refuse the commit.

Why Claude keeps deleting code it was not asked to touch

This isn't new, and it isn't one vendor. Anthropic's tracker has #69898, "Claude silently reverts existing features when making unrelated changes (no spec/test guardrails)", where a commit that added background processing "completely replaced the toolbar structure ... removing ~15 actions and their handler methods silently". #16504 says Claude "only mentions what WAS added/replaced". In #41133 approved features vanished "when Claude rewrote files from scratch instead of making incremental edits". On the Codex side, openai/codex #5747 is from October 2025: asked to add a delete button, the model "removed many features from my cards".

We hand-picked 15 issues about agents removing or undoing work (12 for Claude Code, 3 for Codex), going back to July 2025. It's a sample. There are more.

The mechanism we saw in our own runs is a whole-file rewrite. Claude Code changes a file with Edit, which replaces one string, or with Write, which replaces the whole file. In three of our five runs Claude used Write and sent back a new 8-line app.js in place of the 15-line one. A rewrite like that drops anything the model didn't carry over. The summary at the end lists what it changed, so a dropped line has nowhere to show up.

A robot places a short stack of paper strips into a box beside a tall stack of paper strips, with loose strips fallen on the floor, while a smaller robot holds up a checklist card.
Illustration, generated locally with ERNIE-Image. Write replaces the whole file, so the old version is gone the moment the new one lands. The checklist only ever covers what was added.

A rule in CLAUDE.md or AGENTS.md is text in the prompt. Codex's own docs describe AGENTS.md as the place for "project requirements and conventions", and nothing in it runs. So the guard below runs outside the model: a script, a git hook and a Claude Code hook.

Step 1. Write a KEEP list and a check script

The KEEP list names each line that must stay, the file it lives in and why. The check script reads it and fails when one is gone. Here it guards a small demo server; in your own project you'd list your own lines.

  1. In a terminal, create an empty repository and open it:
bash
1mkdir keep-demo && cd keep-demo && git init -q
  1. In keep-demo, create app.js, a tiny server with the debug route we will protect:
bash
1cat > app.js <<'EOF'
2// app.js: a tiny map server with a remote debug channel
3const http = require("http");
4
5// Remote debugging: lets the agent run checks on a client device.
6function remoteDebug(req, res) {
7  res.end("debug channel open\n");
8}
9
10function home(req, res) {
11  res.end("map server\n");
12}
13
14http.createServer((req, res) =>
15  req.url === "/debug" ? remoteDebug(req, res) : home(req, res)
16).listen(process.env.PORT || 8080);
17EOF
  1. In keep-demo, create KEEP.txt. Each line is file|text that must stay|why:
bash
1cat > KEEP.txt <<'EOF'
2# file|text that must stay|why it stays
3app.js|function remoteDebug(|remote debugging, used to diagnose device bugs
4app.js|req.url === "/debug"|the route that serves remote debugging
5EOF
  1. In keep-demo, create check-keep.sh and make it executable. It exits 2 when any listed text is missing, because Claude Code reads exit 2 as "keep working" on a Stop hook and git treats any non-zero exit as a failed hook:
bash
1cat > check-keep.sh <<'EOF'
2#!/bin/sh
3# check-keep.sh: fail when a line listed in KEEP.txt is gone from its file.
4cd "$(git rev-parse --show-toplevel)" || exit 2
5missing=0
6while IFS='|' read -r file text why; do
7  case "$file" in ''|'#'*) continue ;; esac
8  if ! grep -qF -- "$text" "$file" 2>/dev/null; then
9    echo "KEEP: '$text' is missing from $file ($why)." >&2
10    missing=1
11  fi
12done < KEEP.txt
13if [ "$missing" -eq 1 ]; then
14  echo "Put it back. To remove it on purpose, a person deletes its line from KEEP.txt first." >&2
15  exit 2
16fi
17exit 0
18EOF
19chmod +x check-keep.sh
  1. Run the check before changing anything:
bash
1./check-keep.sh; echo "exit $?"

You should see:

text
1exit 0

Nothing is missing yet.

The check matches exact text with grep -F. A rename that keeps the feature (say, remoteDebug to debugChannel) will also trip it, and then a person updates the list. I prefer a false alarm to a silent loss.

Step 2. Claude Code pre-commit hook: block a commit that removes a feature

This is a git hook, not a Claude Code hook: a script git runs before it makes a commit. Git's docs: "Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit." It belongs to git, so Claude Code, Codex and a person at the keyboard all go through the same check.

  1. In keep-demo, create a versioned hooks folder with a pre-commit file that runs the check, and point git at it:
bash
1mkdir .githooks
2printf '#!/bin/sh\nexec ./check-keep.sh\n' > .githooks/pre-commit
3chmod +x .githooks/pre-commit
4git config core.hooksPath .githooks
  1. Commit the starting state. The hook runs and passes:
bash
1git add -A && git commit -m "map server with remote debug"

You should see a root commit with 4 files (.githooks/pre-commit, KEEP.txt, app.js, check-keep.sh). These are the first two lines. Your hash will differ, and so will the branch name (master) if your git has no init.defaultBranch set:

text
1[main (root-commit) b5ca302] map server with remote debug
2 4 files changed, 36 insertions(+)
  1. Delete the function the way an agent's clean-up would, and try to commit:
bash
1sed -i.bak '/^\/\/ Remote debugging/,/^}/d' app.js && rm app.js.bak
2git commit -am "remove remote debugging"; echo "exit $?"

You should see the commit refused:

text
1KEEP: 'function remoteDebug(' is missing from app.js (remote debugging, used to diagnose device bugs).
2Put it back. To remove it on purpose, a person deletes its line from KEEP.txt first.
3exit 1

No commit was made. Git kept the last good one.

  1. Put the file back and confirm the check is clean:
bash
1git checkout -- app.js && ./check-keep.sh && echo "all KEEP lines present"

You should see all KEEP lines present.

Two gaps, from git's own docs. git commit --no-verify skips the pre-commit hook. And "Hooks that don't have the executable bit set are ignored". Forget chmod +x and git skips the hook, prints a hint: message and makes the commit anyway. Step 3 narrows the first gap for Claude Code; a CI check closes it.

Step 3. Claude Code Stop hook example: exit 2 tells Claude what went missing

A Stop hook runs when Claude finishes its reply. Per Anthropic's hooks reference, exit code 2 on Stop "Prevents Claude from stopping, continues the conversation", and Claude gets the hook's stderr as the reason. So Claude hears about a missing line in the same turn it removed it, before the turn ends.

We got this wrong the first time. Our first version ran check-keep.sh directly. When we told Claude to remove the feature, it kept the removal (correctly, we'd asked for it), the hook said "Put it back", Claude explained, the hook fired again, and so on: 17 blocks in 37 seconds. Claude Code counts blocks in a row and resets the count when Claude calls a tool, which Claude did once along the way. At 9 in a row it printed "A hook blocked the turn from ending 9 consecutive times—overriding and ending turn". The docs warn about this, and you're meant to read stop_hook_active, which "is true when Claude Code is already continuing as a result of a stop hook". The version below blocks once per turn and then lets Claude stop. I'd put that check in any Stop hook that can exit 2.

A grinning robot that has burst through a green board stands beside a robot holding a yellow gear-shaped flower and a round stop sign, with a small robot, rows of red flags and a wall clock behind them.
Illustration, generated locally with ERNIE-Image. Our first hook version blocked on every stop, 17 times in 37 seconds, until Claude Code overrode it after 9 blocks in a row and ended the turn. The fix is to read stop_hook_active and block once per turn.
  1. In keep-demo, create the wrapper .claude/hooks/stop-keep.sh and make it executable:
bash
1mkdir -p .claude/hooks
2cat > .claude/hooks/stop-keep.sh <<'EOF'
3#!/bin/sh
4# Claude Code Stop hook: run the KEEP check once per turn.
5# A second block in the same turn only repeats itself, so let Claude stop.
6if grep -q '"stop_hook_active": *true'; then
7  exit 0
8fi
9exec "$CLAUDE_PROJECT_DIR"/check-keep.sh
10EOF
11chmod +x .claude/hooks/stop-keep.sh
  1. In keep-demo, create .claude/settings.json. It registers the Stop hook, lets Claude run two read-only git commands and node --check without asking, and denies edits to KEEP.txt, check-keep.sh and the .githooks folder. It also denies git commit in the form Claude normally writes it, so Claude leaves the commit to you instead of committing (and maybe skipping the hook) on its own. Claude Code's permissions page says a deny rule "isn't a security boundary": git -C . commit doesn't match it.
bash
1cat > .claude/settings.json <<'EOF'
2{
3  "permissions": {
4    "allow": ["Bash(node --check *)", "Bash(git status *)", "Bash(git diff *)"],
5    "deny": ["Edit(/KEEP.txt)", "Edit(/check-keep.sh)", "Edit(/.githooks/**)", "Bash(git commit *)"]
6  },
7  "hooks": {
8    "Stop": [
9      { "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/stop-keep.sh" } ] }
10    ]
11  }
12}
13EOF

Step 4. Test the Stop hook without Claude

Before a real session, check the hook the way Claude Code calls it.

  1. In keep-demo, pipe the hook the JSON Claude Code sends on standard input. First a normal stop with a line missing, then a stop that is already a continuation:
bash
1sed -i.bak '/^\/\/ Remote debugging/,/^}/d' app.js && rm app.js.bak
2echo '{"hook_event_name":"Stop","stop_hook_active":false}' | CLAUDE_PROJECT_DIR=$PWD .claude/hooks/stop-keep.sh; echo "exit $?"
3echo '{"hook_event_name":"Stop","stop_hook_active":true}' | CLAUDE_PROJECT_DIR=$PWD .claude/hooks/stop-keep.sh; echo "exit $?"
4git checkout -- app.js

You should see one block, then a pass:

text
1KEEP: 'function remoteDebug(' is missing from app.js (remote debugging, used to diagnose device bugs).
2Put it back. To remove it on purpose, a person deletes its line from KEEP.txt first.
3exit 2
4exit 0
  1. Commit the Claude Code settings so the next session picks them up:
bash
1git add -A && git commit -m "Claude Code Stop hook and permissions"

You should see a commit with 2 files changed (.claude/hooks/stop-keep.sh and .claude/settings.json).

Step 5. Ask Claude Code to remove the feature and watch the hooks

Claude Code holds back a folder's hooks until you accept its trust dialog, the question it asks the first time you open a folder. In the hook command, $CLAUDE_PROJECT_DIR is set by Claude Code to the project's root folder.

  1. In keep-demo, start Claude Code with edits allowed and the removal as the first prompt:
bash
1claude --permission-mode acceptEdits "Remove the remoteDebug function and the /debug route from app.js. Do not touch KEEP.txt, just edit app.js."
  1. When the trust dialog asks about the folder, choose to trust it. Claude starts on the prompt.
  2. Read the reply and what follows it. With the prompt above, in our fifth run Claude edited app.js, ran node --check, said it was done, and 0.07 seconds later got this:
text
1Stop hook feedback:
2["$CLAUDE_PROJECT_DIR"/.claude/hooks/stop-keep.sh]: KEEP: 'function remoteDebug(' is missing from app.js (remote debugging, used to diagnose device bugs).
3KEEP: 'req.url === "/debug"' is missing from app.js (the route that serves remote debugging).
4Put it back. To remove it on purpose, a person deletes its line from KEEP.txt first.
Rendered from our session log: the Stop hook feedback listing both missing KEEP lines, followed by Claude's reply that it kept the removal because the person asked for it
Session on Claude Code 2.1.333, 3 December 2026. One block, then Claude explains the conflict and stops 4 seconds later. The hook does not argue a second time.

Claude answered once. Then it stopped. (Our test Mac loads its own global Claude Code hooks and instructions into every session, and in one run they added a line of their own to Claude's reply; we quote only the text that came from this project.) Its reply, from the session log: "I've left the removal in place. The project's stop hook flagged it because KEEP.txt still lists function remoteDebug( and req.url === "/debug" as lines app.js must keep ... You told me directly to remove both and not to touch KEEP.txt, so I haven't restored them". I think that's the right behaviour: the person's instruction wins, and the removal is now out loud.

  1. Type /exit to leave Claude Code, then try to commit what Claude left:
bash
1git commit -am "remove remote debugging"; echo "exit $?"

You should see both KEEP lines reported and exit 1. The removal can't land until a person edits KEEP.txt. If Claude declined instead and changed nothing, git prints nothing to commit, working tree clean and exit 1, because there was nothing to commit.

  1. Put the file back:
bash
1git checkout -- app.js && ./check-keep.sh && echo "all KEEP lines present"

You should see all KEEP lines present.

Note

Every one of our five runs asked Claude for the removal. In the first, which had no "do not touch KEEP.txt" in the prompt, Claude read KEEP.txt before touching anything and declined: "I haven't changed anything yet. remoteDebug and the /debug route are both listed in KEEP.txt as lines that must stay". So the list works as an instruction too, before any hook fires. We have not yet seen a run where Claude dropped a listed line by accident and the Stop hook made it put the line back.

Codex deleted my code too: the same pre-commit hook covers it

The pre-commit hook in Step 2 is git's, so a commit made by Codex, by Claude Code or by you runs the same check. We did not run Codex for this article: the Codex CLI is not installed on our test Mac, so everything below comes from OpenAI's docs.

Codex has its own hooks, and they look a lot like Claude Code's. OpenAI's hooks page lists a Stop event, takes project hooks from .codex/hooks.json, and accepts "exit code 2" with the reason on stderr. One difference matters: "Stop expects JSON on stdout when it exits 0. Plain text output is invalid for this event." Another: Codex records trust "against the hook's current hash, so new or changed hooks are marked for review and skipped until trusted". I like that choice: a hook the agent rewrites stops running until a person trusts it again.

In Codex's default sandbox, <writable_root>/.git "is protected as read-only", which covers .git/hooks but not a tracked .githooks folder like ours (that's my reading; I haven't tested it). The HN post's title says "6.2-Astra Ultra": Ultra is a Codex mode in which, per OpenAI's guide, Codex itself decides when to bring in subagents. The model underneath was GPT-6.2 Astra.

What OpenAI's GPT-6.2 system card says about Astra

The system card OpenAI published with GPT-6.2 Astra and Sol on 17 November measures the models doing coding work. OpenAI replayed about 17,000 tasks from its internal Codex traffic: "4.96 percent of GPT-6.2 Astra turns had a confirmed misalignment flag, compared with 3.19 percent for GPT-6 Astra." Low-severity (level 1) flags rose from 1.98 to 2.97 percent; high-severity (level 3) rates were similar. A flag includes a model that might "take a destructive action beyond the scope of a request".

The UK AI Security Institute tested GPT-6.2 Astra in simulated scenarios, where all tool calls were "simulated by other LLMs". There the model "destructively interfered with other agents' work without permission". The card's summary of those results: "it is therefore critical to use additional mitigations that do not rely on the model's own alignment". That's the case I'd make for a git hook, which doesn't rely on it.

OpenAI also launched GPT-6.2 "with tighter safeguards for higher-risk cybersecurity assistance", which "restrict some legitimate vulnerability research and security testing workflows". A channel that runs JavaScript on clients might look like that kind of work to a model. We haven't found anyone showing that was the reason, and the post doesn't say.

What these hooks do not catch

  • A changed feature that keeps its text. The check proves a line exists. It can't tell whether remoteDebug still works. If the behaviour matters, I'd pair it with a test that calls /debug.
  • Edits through a script. Claude Code's deny rules cover its file tools and the shell commands it recognises, but the permissions page says "a Python or Node script that opens files itself" can still change a denied file. The pre-commit hook still checks the result at commit time.
  • git commit --no-verify from anyone the deny rule doesn't cover: a person, or another agent. A server-side check (a CI job running ./check-keep.sh) closes that.
  • A hook that fails. Claude Code's docs: "On most events, when a hook fails or times out, Claude Code still carries out the action". Add "onFailure": "block" next to "type" and "command" in the hook's entry (Claude Code 2.1.295 or later) if you want the opposite.
  • Sessions started with claude -p. Those treat the folder as trusted, so committed project hooks run there without a dialog. Interactive sessions wait for the trust dialog. Know which one your pipeline uses.

If it didn't work

If git commit succeeds with a line missing and git printed hint: The '.githooks/pre-commit' hook was ignored because it's not set as executable., run chmod +x .githooks/pre-commit. With no hint, check that git config core.hooksPath prints .githooks.

If Claude stops without any Stop hook feedback, you didn't accept the trust dialog, or the session started before you created .claude/settings.json. Type /hooks in Claude Code to see which hooks it loaded.

If you see "A hook blocked the turn from ending 9 consecutive times", you're running check-keep.sh directly from the Stop hook. Use the Step 3 wrapper.

If Claude Code waits on a permission prompt for node --check or git status, that's because acceptEdits auto-accepts file edits and some file commands such as mkdir, touch, mv and cp, not node or git. Keep the allow list from Step 3, or answer the prompt.

Clean up

bash
1cd .. && rm -rf keep-demo

Check it: ls keep-demo should print ls: keep-demo: No such file or directory on macOS.

I'd put the lines you'd hate to lose in KEEP.txt (debug channels, feature flags, the security check someone always "simplifies"), and I'd keep the pre-commit hook even if you only use Claude Code. Which line in your codebase would you list first?

Key takeaways

  • You have a KEEP list, a 16-line check script, a git pre-commit hook that refuses a commit with exit 1 when a listed line goes missing, and a Claude Code Stop hook that tells Claude once per turn.
  • The pre-commit hook is plain git, so commits from Codex, Claude Code or a person all hit it; --no-verify and a missing executable bit are its two gaps.
  • The Stop hook should check stop_hook_active: without it ours blocked Claude 17 times in 37 seconds.
  • Not covered here: Codex hooks (documented, not run by us) and whether the protected feature still works after an edit that keeps its text.
ShareXLinkedIn

Tags

claude-codecodexclaude-code-hooksgit-hooksai-coding-agents

Comments

0

Add a comment

Confirm your address using the email we send. You can unsubscribe at any time. Your email stays private and this does not sign you up for the newsletter.