The blast radius principle: checking targets before destructive commands

An AI coding assistant proposes commands quickly and confidently, and neither quality says anything about what happens when a command is wrong. The human's side of the collaboration is making sure the worst case of any single command stays small.

Originally drafted in December 2025 as part of a longer best-practices guide; revised in August 2026: extracted as a standalone article, with incident examples generalized to their failure classes.

An AI coding assistant, asked to clean up a half-migrated JavaScript monorepo, proposes a tidy list:

# Proposed cleanup: inspect the targets; do not run this illustration.
rm -rf packages/
rm -f lerna.json tsconfig.json
rm -rf tests/ patches/ plan/ ~/

The third command ends with ~/. In a shell that expands it to your home directory, that argument reaches far beyond the project: local repositories, SSH keys, credentials, dotfiles, documents. What it could remove depends on permissions and the filesystem, but the requested scope is already unacceptable. The first two commands need review too. A directory called packages and a TypeScript configuration can contain work you still need.

Every command has a blast radius: the damage it can cause if something about it is wrong. Synthesis coding treats bounding that radius as engineering work, alongside getting the command right. One stray path should not turn a project cleanup into an account-wide loss.

Sizing the blast radius

I have used this lens before for calibrating code review to project risk. It applies one level down, to individual commands. Alongside “does this look correct?”, ask “what is the worst this can do if it is not?”

Command shapeWhat needs checkingA better safeguard
A recursive removal targeting ~/The target is your home, not a project artifactRefuse that target in an ordinary project-cleanup workflow
A recursive removal targeting shell-expanded *The shell selects children of the current directory; which names it selects depends on shell rules and optionsEnumerate exact targets; move them somewhere recoverable and verify what moved
git clean -fdxUntracked files and directories, including ignored files, can be removedInspect git clean -fdxn before authorizing the exact cleanup
DROP DATABASEThe connected server, database identity and authority to destroy itVerify the exact database, use a connection that cannot reach production for nonproduction work, and test restoration from a suitable backup

A literal . or .. operand is a different case from a glob selecting its children. POSIX specifies that rm refuse those final path components. That refusal does not protect the children selected by *. Similarly, Git's -x includes ignored files, while nested Git repositories have an additional force requirement. Git documents the flags and dry-run behavior.

The safer form of a recursive delete is usually not deleting yet. Move the target somewhere recoverable and inspect what actually moved. Check the destination and collisions before treating the move as a recovery plan. Spelling a path out helps a reviewer see it; the remaining problem is the path that reads correctly and resolves somewhere else.

A command whose worst case is one build directory deserves a glance. A command whose worst case is your home directory deserves a different mechanism, not a more careful glance.

Prevention, confirmation, recovery

A plausible cleanup list can contain one path outside the intended boundary. Parent paths, home shortcuts, unresolved variables and globs need checks that constrain what the command can reach.

Long approval lists also make it easy for a human to miss the one exceptional line. I want safeguards that keep catching named mistakes when attention lapses. I try to restrict a tool's reach before relying on a confirmation prompt, and arrange recovery before either is needed.

Later technical correction (September 2026): The preflight and exercise below check raw spelling, physical targets and intended targets separately.

Prevention restricts what the tool can reach. In a tool you control, validate the raw target spelling before normalization, require an existing trusted root, and resolve existing paths through the filesystem. The following POSIX Node.js example is a preflight. It never removes a file and returns pass, not a promise that deletion would be safe:

const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

// This spelling contract runs before any normalization or filesystem lookup.
function unambiguousPath(value) {
  if (typeof value !== 'string') return false;
  if (value.trim() === '') return false;
  if (/[\x00-\x1f\x7f~$`*?\[\]{}\\]/.test(value)) return false;
  if (value.startsWith('//')) return false;
  const spelling = value.startsWith('./') ? value.slice(2) : value;
  if (value === './') return false;
  return !spelling.split('/').some(part => part === '.' || part === '..');
}

function preflight(targetPath, projectRoot) {
  const refuse = reason => ({ pass: false, reason });
  if (process.platform === 'win32') return refuse('POSIX paths required');
  if (!unambiguousPath(targetPath)) return refuse('ambiguous target spelling');
  if (!unambiguousPath(projectRoot) || !path.isAbsolute(projectRoot)) {
    return refuse('explicit absolute root required');
  }
  try {
    const root = fs.realpathSync.native(projectRoot);
    if (!fs.statSync(root).isDirectory()) return refuse('root is not a directory');
    const home = fs.realpathSync.native(os.homedir());
    const broadRoots = ['/', '/usr', '/etc', '/var', '/Users', '/home', '/tmp',
      '/private', '/System', '/Library', '/Applications', '/opt', '/bin',
      '/sbin', '/lib', '/lib64'];
    const protectedRoots = new Set([home]);
    for (const entry of broadRoots) {
      try { protectedRoots.add(fs.realpathSync.native(entry)); } catch {}
    }
    if (protectedRoots.has(root)) return refuse('root is too broad');

    // The target must exist. Do not invent a path from its nearest ancestor.
    const target = fs.realpathSync.native(targetPath);
    const cwd = fs.realpathSync.native(process.cwd());
    if (target === root || target === home || target === cwd) {
      return refuse('protected target');
    }
    const relative = path.relative(root, target);
    const outside = relative === '..' || relative.startsWith('..' + path.sep)
      || path.isAbsolute(relative);
    if (outside) return refuse('target resolves outside root');
    const kind = fs.statSync(target);
    if (!kind.isFile() && !kind.isDirectory()) return refuse('unsupported target type');
    return { pass: true, root, target };
  } catch (error) {
    return refuse(`cannot resolve existing paths: ${error.code || error.name}`);
  }
}

module.exports = { unambiguousPath, preflight };

The spelling rules are deliberately restrictive. They reject missing or empty input, shell shortcuts, variables, glob characters and parent components. They allow one leading ./, spaces within a name, and an ordinary child named ..cache. A legitimate filename containing a rejected character needs a separately designed interface; silently treating shell syntax as a literal filename would undermine this contract.

The root must be explicit, absolute and already present. The target must exist too. Resolving the nearest existing ancestor can be useful when planning creation, but it is the wrong default for this removal preflight: an absent target is a reason to stop and recheck the request.

I got the symlink, sibling-prefix, parent-segment and trust-root checks wrong in earlier versions. The published example also had a more subtle ordering error: it called path.resolve before following symlinks. Node's path operations normalize strings; that is different from following the filesystem's links.

The exercise creates this synthetic layout:

fixture/
  trusted/
    victim                 # INSIDE_SYNTHETIC_ROOT
    escape -> ../outside/branch
  outside/
    branch/
    victim                 # OUTSIDE_SYNTHETIC_ROOT

Reading the raw path trusted/escape/../victim follows escape to outside/branch, then its parent to outside, and reads the outside marker. Lexically normalizing that spelling first produces trusted/victim, a different file. A check can therefore approve the normalized path while a later consumer receives an escaping raw path. This mismatch exists even without a concurrent filesystem change.

The repaired preflight refuses parent components before normalization. For the accepted spellings, it uses Node's native real-path lookup on the supplied path. A plain link pointing outside the root is rejected after resolution. A link whose resolved target is inside can pass this containment check; that does not grant permission to act on it.

Comparing strings with startsWith(root) introduces a separate sibling bug: /project-backup shares the prefix /project. The relative-path check uses whole path segments. Testing only relative.startsWith('..') would go too far in the other direction by rejecting ..cache, an ordinary child name. The existing root, physical current directory and home are checked separately, with common broad system roots refused as trust anchors.

Run the checks without removing anything

Download the complete path-preflight exercise. It includes the exact function above, literal expectations, a fixture constructor, eight deliberate implementation faults, shell-printing checks and an anchored text-edit example. The path and intent expectations include literal root and target locations, separate from the function's answers. The fixture creates new directories, links and marker files under the example folder and retains them for inspection.

From the extracted folder, with Node.js and Python 3 installed:

node test.cjs
node mutations.cjs
node shell-printing.cjs
python3 -B edit-demo.py

The path run checks 70 outcomes: raw-input rules, real filesystem targets, the two different symlink/parent marker reads, exact intent matches and mismatches, and marker contents before and after the probes. Seven checks compare the full successful result, including the expected root and target. Its positive cases include ..cache directly under the root and inside a nested directory, a directory containing a space and an in-root symlink. A check that simply rejects every request fails those cases.

The mutation run changes one implementation mistake at a time while keeping the tests and expectations unchanged. They detect missing raw-empty rejection, prefix-based containment, omitted symlink resolution, normalization before spelling validation, refusal of every target, an incorrect successful root, an incorrect successful target, and overbroad rejection of ..cache. The empty-input control tests the raw-input rule specifically; the later current-directory check can still refuse that input. Detecting that mutation is not evidence that the full function would otherwise approve it.

These source and clean-download runs are local synthetic evidence. They do not test an AI assistant, a removal command or a concurrent attacker. The shell-printing runner requires Bash and zsh and sets the zsh option it is comparing explicitly.

Containment does not establish intent

A target resolving inside your project can still be the one directory you needed. The exercise deliberately passes a contained directory named valuable through the preflight while refusing it against the separately authorized target, child. Both results are correct: containment passes; permission to perform the proposed operation does not.

The function also trusts the root supplied by its caller. Rejecting several broad roots does not identify every overly broad ancestor. If the caller chooses a directory containing several projects, the check cannot infer which project was authorized.

Finally, the check and any later operation occur at different moments. Another process can replace a directory with a symlink after validation. Passing the canonical target to a later path-based operation does not eliminate that race. This is why the function is named preflight and the download contains no deletion function.

For operations whose consequences justify stronger filesystem controls, descriptor-relative APIs are an engineering direction. POSIX openat and unlinkat can work relative to an open directory descriptor. O_NOFOLLOW protects the final component of an openat path; it does not make a multi-component traversal safe by itself. A component-by-component design opens directories using O_NOFOLLOW and O_DIRECTORY, holding the descriptor for each parent, then supplies only the final name to the operation. POSIX documents openat; Linux documents its no-follow boundary.

Portable unlinkat uses AT_REMOVEDIR when removing a directory. Removing a final symbolic-link name removes the link, not its target. That does not excuse an unchecked intermediate path. Recursive removal and authorization still require careful design; the API names alone do not supply it. The POSIX unlink contract describes those operations. This article's JavaScript does not implement or test a descriptor-based removal tool.

Confirmation requires a decision about concrete evidence. Print the exact resolved targets, the proposed operation and its effects. A typed confirmation tied to that preview is more useful than a reflexive yes/no response. If the target set or environment changes, the earlier decision no longer describes the same operation.

Recovery needs a tested restoration path. Commit work that belongs in Git, use an appropriate trash or quarantine workflow, and keep versioned backups whose restoration you have tested. Git reflogs record reference updates and can help locate retained commits; they do not preserve arbitrary untracked files or promise recovery after objects expire. Multiple layers reduce the chance of permanent loss when their assumptions hold. A broken backup and a mistaken approval can fail together.

The quiet variants

Home-directory removal is the dramatic case. Text replacement and path spelling can cause less conspicuous damage.

I adopted a Python-only rule for complex file edits after watching a sed replacement match inside URLs and code blocks, not just the prose it was aimed at. The useful discipline is an inspected, bounded transformation. Python can make the same careless replacement as a stream editor. For structured formats, use an appropriate parser; for a textual patch, verify a unique anchor and inspect the entire diff.

The download's in-memory example changes the retention sentence “Keep artifacts for 7 days” to 14 days. Its literal expected result leaves ?days=7 in a URL and const days = 7 in a code block untouched. Missing and duplicate anchors are refused. An unbounded replacement fails the expected result. The script prints the diff without writing an existing document.

Heredocs need their own quoting decision. In Bash, a quoted delimiter such as <<'TEXT' suppresses parameter, command and arithmetic expansion in the body. An unquoted delimiter permits those expansions. Bash specifies the distinction. The exercise prints ${fixture_word} $(printf command) $((2 + 3)) literally in the quoted case and VALUE command 5 in the unquoted case. A heredoc is not inherently corrupting; choosing the wrong expansion behavior is the problem.

The tilde trap depends on the shell and its options. Consider the argument in the original example:

node tool.js --output-dir=~/projects/site/content

For this argument spelling, Bash passes the tilde literally. zsh does so with MAGIC_EQUAL_SUBST disabled, but expands it with that option enabled. zsh documents expansion after the equals sign. The exercise compares those cases using printf; it never runs tool.js. A receiving program may interpret the literal path itself, so the argument alone does not prove what directory it would create.

If a program did create a child literally named ~, a later shell command using unquoted ~ would refer to the home directory instead. ./~ identifies the child; "$HOME" expresses an intended home path. Neither spelling establishes permission to remove anything. The target and the operation still need checking.

A hardcoded absolute path adds another failure mode: it may be absent on a colleague's machine, or, worse, name an unintended location there. Use an explicitly selected project root and paths relative to it when that is the intended scope. Portability and authorization are separate questions; substituting a different username does not answer either one well.

Write the rules where the assistant reads them

Correcting a dangerous command fixes one session. Persistent guidance works on the pattern. I keep destructive-command guidance in my CLAUDE.md files. Check how your particular tool loads its instruction files; the guidance needs to reach the session doing the work. This reusable guidance expresses the intended boundaries:

### Destructive command safeguards

Refuse broad or ambiguous cleanup targets:
- Home shortcuts and home-wide patterns: ~, $HOME, /Users/*, /home/*
- Root, current and parent targets: /, ., ..
- Broad system locations: /usr, /etc, /var
- Globs whose selected targets have not been enumerated and authorized
- Empty input, unresolved variables, and parent path components

Before any destructive operation, list the exact target set and effects.
Require an existing, explicitly authorized project root. Validate raw
spelling before normalization, then resolve existing targets physically.
Refuse targets that cannot be resolved or that escape the root. Check
that the resolved targets are also the ones the user actually authorized.
A contained path alone is not permission.

Prefer an authorized move to a recoverable location over permanent
removal; verify what moved and how to restore it. Recheck after changes
to the target set or environment. A path preflight is not a race-free
filesystem operation.

For complex edits, use structural parsing or unique, verified anchors,
inspect the resulting diff, and preserve a recoverable original.
Quote heredoc delimiters when literal body text is intended.

Guidance remains a soft layer. It reduces how often dangerous commands get proposed and gives a reviewer a concrete standard when one appears anyway. Tool checks enforce only the conditions they actually examine. Keep the instruction, the executable boundary and the human decision aligned.

An assistant that can execute in seconds what used to take an afternoon deserves an environment where the worst case of any single command is small. Building that environment is not overhead on the collaboration. It is the human half of it.


This article is one of a set drawn from my production best-practices notes. Its companions cover orthogonal verification (checking results through a different mechanism than the one that produced them) and behavioral contracts for AI collaborators (recommend A, implement A).

This is part of a series on synthesis coding, the practice of building software through human-AI collaboration where the human provides direction, judgment and domain expertise while the AI provides execution speed and breadth.