At 10:50am ET on October 16, 2026, an AI agent supervising a software build was tidying up. It had just remade 2 installer disk images and wanted the old copies gone, so it typed rm -f $L/$k.dmg. rm deletes files. $L and $k are variables, names the shell fills in only when the command runs. Had $L been empty, the path would have started at /, the top of the whole disk.

Claude Code, the program running the agent, stopped the command. Its safety check could not tell where the delete would land, because the answer did not exist until the command ran. The agent kept a note for itself: guard such variables. The note went into no rule and no instruction, and no later agent read it.

At 4:21pm ET on October 23, a different agent made the same mistake. Claude Code stopped it too. That evening, 2 more deletes ran where no check was looking, and one of them erased 13 apps from the Mac's Applications folder.

This paper tells what happened, what failed, and the safeguard that now checks every delete an agent types: a rule, a script and a hook. All 3 are printed in full, tested, so you can copy them. The lesson fits in the title.

The second agent repeated a mistake the first had already written down

The second agent was testing how the project handles a model too big to load. It made a temporary folder with a fake 500 GB model in it, ran its check, and cleaned up:

d=$(mktemp -d)/made-up-btc; mkdir -p $d; …; rm -rf $(dirname $d)

mktemp -d makes a new temporary folder and prints its name. rm -rf deletes a folder and everything in it. dirname drops the last part of a path, so rm -rf $(dirname $d) deletes the folder above d. The steps were joined with ;, which runs each step even when the one before it failed.

Claude Code stopped it with "Dangerous rm operation on statically-unresolvable target: command substitution output". The person running the session then stopped the agent.

Here is the arithmetic behind the danger. If mktemp -d fails, it prints nothing, so d becomes /made-up-btc, and the folder above that is /. That is an inference from how the shell works; the session record does not spell it out.

Both commands share one trait: nothing in their text says where they delete. In both, the delete was only cleanup of something the same command had just made. Cleanup is where nobody looks.

Kyberna's own check read 7 of 8 risky deletes as safe

Kyberna, the app these agents were building, runs AI agents for its users. Its Rogue Agent Protection holds a recursive delete outside a conversation's folders until the person approves it. The supervising agent measured that check against the second command. When it could not tell where a path pointed, it assumed the path was inside the conversation's folders, the one place it considered safe.

7 commands read as safe:

  • rm -rf $(dirname $d)

  • rm -rf "$L/"

  • rm -rf $L/*

  • rm -rf `pwd`/..

  • cd work && rm -rf .

  • rm -f $L/$k.dmg

  • rm -rf of the conversation's own folder

Only rm -rf .. read as dangerous. A second check, which grades the risk of each command but did not yet act on its grade, let a recursive delete outside the folders through without asking.

Then the supervising agent looked at its own house. The project's scripts held 67 lines that delete a folder named by a variable, with nothing to stop the delete when the variable is empty.

The flaw was not one agent's slip. It was the house style.

The safeguard has 3 parts: a rule, a script and a hook

A rule says what to do. A script makes the safe delete the easy one. A hook refuses the unsafe one, so nobody has to remember.

Part 1: the rule tells every agent how to delete

The project's delete rule has 4 points, given here as they stand on October 25, 2026.

  1. Through 1 script. Every delete goes through Scripts/lib/remove.sh PATH, 1 absolute path per call. The path is written out, or held in a variable that the same command set from mktemp -d and passes as "${var:?}", which stops the command when the variable is empty. It is never a command substitution, a pattern, dirname or the parent of what the command made. A command that makes a path and then removes it joins its steps with &&, which stops at the first failure.

  2. In tests and scripts. This point is quoted in full: "A test makes its temporary folders with its language's own facility (Python's tempfile, Swift's FileManager.default.temporaryDirectory with a UUID) and removes only those. A script in the repository removes a path held in a variable only as rm -rf -- "${var:?}" or "${var:?}/name", never from a substitution, a pattern or dirname. A test never runs a real delete from a repository script; it replaces the delete with a stand-in that records what it would remove. When a test runs one of the repository's scripts, it still puts each delete's target 2 folders deep inside a folder it made, and gives the script that folder as its temporary folder and its home folder, so even a delete of the target's parent removes only what the test made."

  3. In every instruction. Every instruction to a helper agent carries the rule and a Deletions line, and forbids running a test against any copy of the project but the agent's own. The hook refuses an instruction without the rule.

  4. When a delete is stopped. It is reported to the person with what made it unsafe, and recorded the same day.

The Deletions line every instruction carries:

Deletions: every file or folder is deleted with `Scripts/lib/remove.sh PATH`, 1 absolute path per call, never a substitution, a pattern, `dirname` or a parent of what you made; steps that make and remove a path join with `&&`; tests remove only the temporary folders their own language's facility made; a test never runs a real delete from a repository script, and never runs the repository's statements against any tree but your own worktree.

Points 1 to 3 can be copied as they are. Point 4 is this project's reporting step; replace it with yours.

Part 2: the script removes exactly 1 path, and only one an agent made

Scripts/lib/remove.sh removes 1 path. It refuses with exit code 2, and removes nothing, when the path could reach past what the caller made.

It refuses 7 kinds of input:

  • no argument, or more than 1

  • an empty path

  • a relative path

  • a path holding *, ?, [, $ or a backtick

  • a path with . or .. as a part

  • /

  • any path outside the allowed places

It resolves symbolic links in the path's parent first, so a link cannot carry the path outside. A path inside the allowed places that is already gone exits 0.

The allowed places are this project's own. Replace them with the folders your agents create, and nothing else:

  • The temporary folders mktemp uses: $TMPDIR, /private/tmp and the user's own temporary folder. Inside a Claude Code sandbox, $TMPDIR points at a folder Claude Code shares with its own files, and those are refused.

  • ~/Library/Caches/swiftpm-scratch/NAME, the build folders, except the 2 kept ones, kyberna and kyberna-relay*.

  • ~/Developer/kyb-agents/NAME/…, at least 2 levels inside an agent's working copy.

The script is written for zsh on macOS. It uses zsh's :A, :h and :t path modifiers and the macOS paths /private/tmp and /private/var/folders. On another system, replace those with their equivalents. The 2 checks that do not depend on your list are the refused path forms and the symbolic-link resolution. Keep both.

The version first printed here, on October 23, refused a folder made by a plain mktemp -d inside a Claude Code sandbox, because the sandbox sets $TMPDIR to one place while mktemp writes to another. The version below fixes that. It is the project's script as of October 25, 2026, with 2 project-only places and the project's item numbers taken out. The full text, 62 lines:

#!/bin/zsh
# Removes exactly 1 path, and only one a session or agent made for itself.
# Usage: Scripts/lib/remove.sh PATH
# Refuses (exit 2, nothing removed) an empty, relative or patterned path, `.` or `..` in it, and anything outside the
# places below, whether or not it exists; a path inside them that is already gone exits 0. The places:
#   $TMPDIR, /private/tmp and this user's own temporary folder (mktemp's folders); under /private/tmp/claude-*, only
#   inside a session's own folders (/private/tmp/claude-UID/PROJECT/SESSION/FOLDER/…), or, when it is $TMPDIR, a folder
#   there that is not Claude Code's own
#   ~/Library/Caches/swiftpm-scratch/NAME (never kyberna or kyberna-relay*, which are kept)
#   ~/Developer/kyb-agents/NAME/… (a file or folder inside a worktree; a worktree goes with `git worktree remove`)
set -u
refuse() { print -u2 -- "remove.sh: refused, $1; nothing removed"; exit 2 }

(( $# == 1 )) || refuse "give exactly 1 path, not $#"
p=$1
[[ -n $p ]] || refuse "the path is empty"
[[ $p == /* ]] || refuse "the path is not absolute: $p"
[[ $p == *[\*\?\[\$\`]* ]] && refuse "the path holds a pattern or an expansion: $p"
[[ /$p/ == */./* || /$p/ == */../* ]] && refuse "the path holds . or ..: $p"
while [[ $p == */ && $p != / ]]; do p=${p%/}; done
[[ $p != / ]] || refuse "the path is /"

# The parent with symbolic links resolved, so a link cannot carry the path outside the places.
parent=${p:h}
if [[ -d $parent ]]; then full=${parent:A}/${p:t}; else full=$p; fi

[[ -n ${HOME:-} && $HOME == /?* ]] || refuse "HOME is not set"
home=${HOME:A}
below() {  # below ROOT N: $full lies at least N components inside ROOT
  local root=${1:A}
  local -a parts
  [[ $full == $root/* ]] || return 1
  parts=(${(s:/:)${full#$root/}})
  (( $#parts >= $2 ))
}
ok=0
tmp=${${TMPDIR:-/private/tmp}%/}
[[ ${tmp:A} == /private/var/folders/?*/T || ${tmp:A} == /private/tmp || ${tmp:A} == /private/tmp/claude-<-> ]] || tmp=/private/tmp
# Claude Code's sandbox sets $TMPDIR to /private/tmp/claude-UID, beside its own entries there (project folders named
# -PATH, bash-edit-diff, cache-break-state-*, claude-*), which are refused
top=${${full#${tmp:A}/}%%/*}
# A bare mktemp writes to this user's own temporary folder even when the sandbox sets $TMPDIR elsewhere
utmp=${$(getconf DARWIN_USER_TEMP_DIR 2>/dev/null)%/}
[[ -n $utmp && ${utmp:A} == /private/var/folders/?*/T ]] || utmp=
if [[ ${tmp:A} == /private/tmp/claude-<-> ]] && below "$tmp" 1 && [[ $top != [-.]* && $top != bash-edit-diff && $top != cache-break-state-* && $top != claude-* ]]; then
  ok=1
elif below /private/tmp 1 && [[ ${${full#/private/tmp/}%%/*} == claude-* ]]; then
  below /private/tmp 5 && ok=1
elif below "$tmp" 1 || below /private/tmp 1 || { [[ -n $utmp ]] && below "$utmp" 1; }; then
  ok=1
fi
if below "$home/Library/Caches/swiftpm-scratch" 1; then
  name=${${full#$home/Library/Caches/swiftpm-scratch/}%%/*}
  [[ $name == kyberna || $name == kyberna-relay* ]] && refuse "$name is a kept build folder: $p"
  ok=1
fi
below "$home/Developer/kyb-agents" 2 && ok=1
(( ok )) || refuse "the path is outside the places this script removes from: $p"
[[ -e $full || -L $full ]] || { print -- "remove.sh: nothing at $p"; exit 0 }

rm -rf -- "$full" || exit 1
print -- "remove.sh: removed $full"

It was run on October 25, 2026, on macOS inside a Claude Code sandbox. It removed a folder made by a plain mktemp -d and one made under $TMPDIR. It refused, with exit code 2, 20 unsafe paths: no argument, an empty one, 2 arguments, a relative path, /, //, *, $(x), a backtick, ?, .., ., the home folder, ~/Developer, ~/Library/Caches, Claude Code's own bash-edit-diff folder, the kept build folder, /Applications and /Applications/, and a symbolic link into ~/Developer, whose target stayed. With HOME empty, it removed nothing.

Part 3: the hook refuses every delete that skips the script

A PreToolUse hook is a program Claude Code runs before each tool call. Claude Code's hooks page says that on PreToolUse, exit code 2 "Blocks the tool call", and "The message that comes with the block is your hook's stderr". The hook reads the call as JSON; for a Bash call, the command is at tool_input.command. The page also says that when a helper agent calls a tool, the events "fire the same configured hooks as in the main conversation", so helper agents are checked too. Any other exit code is a non-blocking error, and the action goes ahead, unless the hook sets onFailure to "block".

So the hook must exit 2 on purpose, and its own faults must not. Leave onFailure unset.

Register it in .claude/settings.json:

"hooks": {
  "PreToolUse": [
    {
      "matcher": "Bash",
      "hooks": [
        { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/Scripts/hooks/delete_hook.py", "timeout": 15 }
      ]
    }
  ]
}

A matcher made only of letters is read as an exact tool name, so Bash matches only the Bash tool. Run the script as an executable, not as python3 <path>. If the file is missing, the shell exits 127, a non-blocking error. python3 would exit 2 for a missing file, which would block every call.

The hook works in 5 steps:

  1. strip_heredocs removes the bodies of here-documents (text fed to a command inline), so text inside one is not read as a command.

  2. segments splits the line at ;, &&, ||, |, &, parentheses and newlines.

  3. unwrap skips variable assignments and wrappers such as env, time and nohup.

  4. commands also reads inside sh -c, bash -c and zsh -c, up to 3 levels deep.

  5. deletes is true for rm, rmdir, unlink and srm by name, so /bin/rm counts. It is also true for find with -delete, and for xargs running one of those.

When deletes is true, the hook refuses with 1 line that tells the agent what to run instead. The agent reads that line as the tool's error and writes the corrected call.

The project's hook file also checks this project's other rules. The version below keeps only the delete check. The splitting and delete functions are the project's own, unchanged. check_bash and main are cut down to the delete check, and the refusal and fault messages are reworded without the project's rule numbers. Setting DELETE_HOOK=off turns it off, and any fault inside it exits 1, so a bug in the hook never blocks work. The full text, 117 lines:

#!/usr/bin/env python3
"""A Claude Code PreToolUse hook: refuses every delete in a Bash call that does not go through Scripts/lib/remove.sh."""
import json
import os
import re
import shlex
import sys

SWITCH = "DELETE_HOOK"

SHELLS = {"sh", "bash", "zsh"}
DELETERS = {"rm", "rmdir", "unlink", "srm"}
WRAPPERS = {"time", "nohup", "command", "exec", "xcrun", "caffeinate", "nice", "timeout", "gtimeout", "env"}
HEREDOC = re.compile(r"<<-?[ \t]*(['\"]?)(\w+)\1[^\n]*\n.*?\n[ \t]*\2[ \t]*(?=\n|$)", re.S)
SEPARATORS = {";", "&&", "||", "|", "&", "(", ")", "\n", ";;", "|&"}


def refuse(message):
    sys.stderr.write(message + "\n")
    sys.exit(2)

def strip_heredocs(command):
    return HEREDOC.sub("\n", command)


def segments(command):
    """The simple commands of a shell line, each as its words, split at ; && || | & ( ) and newlines."""
    lexer = shlex.shlex(strip_heredocs(command), posix=True, punctuation_chars=";&|()\n")
    lexer.whitespace = " \t\r"
    lexer.whitespace_split = True
    lexer.commenters = "#"
    out, current = [], []
    for token in lexer:
        if token in SEPARATORS or (token and set(token) <= set(";&|()\n")):
            if current:
                out.append(current)
            current = []
        else:
            current.append(token)
    if current:
        out.append(current)
    return out


def unwrap(words):
    """The words from the program on, past variable assignments and wrappers such as `env`, `time` and `xcrun`."""
    i = 0
    while i < len(words):
        word = words[i]
        if re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", word):
            i += 1
        elif os.path.basename(word) in WRAPPERS:
            i += 1
            while i < len(words) and (words[i].startswith("-") or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[i])
                                      or re.match(r"^\d+[smhd]?$", words[i])):
                i += 1
        else:
            return words[i:]
    return []


def commands(command, depth=0):
    """Each simple command, unwrapped, including those inside `sh -c`, `bash -c` and `zsh -c` strings."""
    for words in segments(command):
        words = unwrap(words)
        if not words:
            continue
        if os.path.basename(words[0]) in SHELLS and depth < 3:
            for j, word in enumerate(words[1:-1], start=1):
                if word.startswith("-") and "c" in word.lstrip("-") and not word.startswith("--"):
                    yield from commands(words[j + 1], depth + 1)
                    break
            else:
                yield words
            continue
        yield words


def deletes(words):
    """True for a delete the shell runs directly: `rm`, `rmdir`, `unlink`, `srm`, `find … -delete`, or one behind `xargs`."""
    program = os.path.basename(words[0])
    if program == "xargs":
        return any(os.path.basename(w) in DELETERS for w in words[1:])
    return program in DELETERS or (program == "find" and "-delete" in words[1:])


def check_bash(data):
    tool_input = data.get("tool_input")
    if not isinstance(tool_input, dict) or not isinstance(tool_input.get("command"), str):
        raise ValueError("the Bash call's tool_input has no command")
    for words in commands(tool_input["command"]):
        if deletes(words):
            refuse("Deletions go through Scripts/lib/remove.sh, 1 absolute path per call, which refuses a path "
                   "that could reach past what you made; run \"Scripts/lib/remove.sh /absolute/path\" instead of `"
                   + " ".join(words)[:80] + "`.")


def main():
    if os.environ.get(SWITCH, "").strip().lower() in ("off", "0", "false", "no"):
        return 0
    try:
        data = json.loads(sys.stdin.read())
        if not isinstance(data, dict):
            raise ValueError("the input is not a JSON object")
        if data.get("hook_event_name") == "PreToolUse" and data.get("tool_name") == "Bash":
            check_bash(data)
    except SystemExit:
        raise
    except Exception as error:  # a fault here must never block work
        sys.stderr.write("the delete hook could not check this call, so it goes through: "
                         + type(error).__name__ + ": " + str(error) + "\n")
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())

It was run on October 25, 2026, by feeding it each command as Claude Code would. These 11 commands exited 2, refused:

  • rm -rf $(dirname $d)

  • d=$(mktemp -d)/x; mkdir -p $d; rm -rf $(dirname $d)

  • rm -f /tmp/a.txt

  • /bin/rm -r build

  • cd /tmp && rmdir x

  • unlink /tmp/a

  • find . -name '*.o' -delete

  • ls | xargs -n 1 rm

  • bash -c 'rm -rf x'

  • env A=1 rm x

  • true && rm -rf "${L:?}"

The last one is guarded and still refused. Only the script runs deletes.

These 7 exited 0, allowed: Scripts/lib/remove.sh /tmp/x, git rm -r --cached x, grep -n 'rm -rf' Scripts/a.sh, git commit -m 'rm -rf is refused', find . -name '*.o', trash a.txt, and a Python here-document whose body calls os.system('rm -rf x'). With DELETE_HOOK=off, the first delete went through. Fed text that is not JSON, the hook exited 1.

The project's own test suites for the full script and hook passed the same day. The script's suite ran 10 tests, 1 of them skipped, and the hook's ran 47. No model took part in any of these runs.

The guard's own test then ran 2 deletes no check could see

The 67 unguarded lines needed fixing, and a test to prove each fix held. The agent given that job on the evening of October 23 was thorough. Rather than read each line, it ran each delete in a scratch folder with the variable left empty, to watch it do nothing.

At 7:46pm ET, one of those runs deleted from the Mac's shared temporary folder for up to 60 seconds, until the test's time limit stopped it. What it removed is not known; macOS keeps no record of a delete.

At 7:48pm ET, the same test, run on a copy of the old scripts, reached the line that installs one of the project's apps: rm -rf "/Applications/$(basename "$APP")". The test had left APP empty, so the line became rm -rf "/Applications/". It erased 13 apps, including the Claude app that was running the agent's own session. The companion paper, Claude Built a Delete Guard, Then Deleted Claude, tells that story in full.

Neither Claude Code's check nor the hook saw either delete. Both read the command an agent types, and the agent typed only "run the Python test". The deletes ran inside it.

That is why point 2 of the rule now says a test never runs a real delete from a repository script. It swaps in a stand-in that writes down what it would remove, and the test checks that list. On October 25, the project's scan test still runs the deletes for real; its change to a stand-in is scheduled, not yet built.

What the hook cannot see

A hook reads text. It cannot see:

  • a delete inside a here-document body;

  • a delete in a program's own code, such as Python's shutil.rmtree or Swift's FileManager.removeItem;

  • a delete inside a script that a test or another program starts;

  • what a variable holds when the command runs.

Rule point 2 covers the first 3: a test or program removes only the temporary folders it made, and a test makes every delete pretend. The last is why the script, not the hook, decides which paths are allowed.

What Kyberna now does, and what is still coming

Kyberna is the product where this lesson matters most, because its users run agents on their own Macs. The first 3 items below are built in a test build of Kyberna 0.3.2 that is not released yet. The rest are planned.

  • Built: hold what cannot be resolved. Rogue Agent Protection holds a delete whose folder is known only when the command runs (a $(…), a backtick, or a variable the command does not set), and a delete of a conversation's folder itself or of a folder that holds one. The card shows the command as written.

  • Built: grade the risk honestly. The risk check now grades a recursive delete outside the conversation's folders as one to ask about, and a delete of /, the home folder or a conversation's folder as one to block.

  • Partly built: Safe Rewrite. Before holding such a delete, Kyberna sends it back to the agent, asking it to name the folder's full path and run the delete again, as this project's hook does, instead of asking you about shell quoting. It does this at most 2 times in a reply, and the conversation shows a line for each. A 3rd waits for you on the card. A delete of /, your home folder or a conversation's folder waits for you at once.

  • Planned: 7 more rewrites. sudo, a download piped into a shell, an encoded payload run as a command, a redirect into a hidden settings file or a system folder, open with a web address, a personal detail inside a web address, and git push --force. Each is measured on a local model first, and ships only if that check passes.

  • Planned: Dangerous Delete Guard. Kyberna will check a delete when it runs, after the shell has filled in every variable. The shells Kyberna starts will find Kyberna's own rm, rmdir and unlink first, and each will refuse /, your home folder, a conversation's folder itself and anything outside the folders. It will not see /bin/rm named by its full path, find -delete, or a program's own deletes, so each agent's own sandbox stays the last layer.

  • Being built: Tell the Agent. When Kyberna asks you to approve a step or holds one, you will be able to refuse it and write the agent a sentence. On a held step, Kyberna itself explains the danger, because the agent is the one in question.

What this paper does not show

It reports 4 deletes in one project on one Mac over 8 days. Claude Code's check flagged 2, and 2 ran unseen. That shows the mistake recurs, that a remembered note did not stop it, and that a hook cannot see a delete inside a test. It does not say how often agents run such commands.

The measurements of Kyberna's own checks came from temporary tests, removed after the run, and are reported as the project's records give them. The hook was tested with the input Claude Code's hooks page documents, not in a live session. No peer-reviewed paper is cited, because this paper makes no claim about agents in general.

If you run coding agents, copy the script and the hook, and put the Deletions line in every instruction. If you write tests for a safety check, make the dangerous step pretend. If you supervise agents, read what they ran, not only what they report.

Agents forget rules. Hooks don't. But a hook sees only what an agent types, so make everything else pretend.

Sources

The Kyberna repository is private; the files below are named for the reader with access, and every file the safeguard needs is printed above.

  • The 4 incidents and the rule's history: docs/claude-md-cleanup/rules-history.md, section R-67, which dates the first incident October 16, 2026, from the session record (this paper said October 15 until October 25). The Applications delete: docs/backlog/rules.md, rules 8, and the companion paper.

  • Kyberna's checks measured: docs/backlog/guard.md, guard 77 and guard 78, with the reader at Sources/GatewayKit/TurnLedger.swift:444 at commit 84b2a9793. The 67 script lines and the scan test: docs/backlog/rules.md, rules 7, and Scripts/test_unguarded_deletes.py.

  • The rule: R-67 in CLAUDE.md, and the Deletions line in .claude/skills/kyberna-writing/agent-brief.md, item 9, at commit a5e95b91f.

  • The script and hook: Scripts/lib/remove.sh and Scripts/hooks/claude/rule_hooks.py at commit a5e95b91f (the October 23 edition printed them at commit 84b2a9793), with docs/plans/rule-hooks.md; their suites Scripts/test_remove.py and Scripts/test_claude_hooks.py.

  • What Kyberna does and plans: docs/features.md, KF-088 (Rogue Agent Protection), KF-158 (Safe Rewrite), KF-159 (Dangerous Delete Guard) and KF-160 (Tell the Agent); items guard 77 to guard 80 and console 518.

  • Claude Code's hooks page, https://code.claude.com/docs/en/hooks, read October 25, 2026.