SLOPSHOPPER

blast-radius

Holds risky shell commands (rm -rf, git reset --hard, git clean, force push, migrations) and shows what they would change, with Proceed and Cancel buttons.

panebandguardtoastprocess
v0.1.1no licenseupdated 2026-10-22mlopian/claude-plugins/blast-radius
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · blast-radius
│ ┃ Blast Radius ✕ › fix the failing auth test and add an audit log call │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ⚠ Blast Radius · rm -rf ⏺ Read(src/auth.ts) │ ┃ │ Command rm -rf build && git push ⎿ Read 6 lines │ ┃ │ --force origin main ⏺ Update(src/auth.ts) │ ┃ │ Would delete nothing: no file matches ⎿ Added 2 lines, removed 1 line │ ┃ │ build ⏺ Bash(rm -rf build && git push --force origin main) │ ┃ │ ⎿ Denied by blast-radius: Blast Radius held this command an │ ┃ │ The paths don't exist, so rm has nothing │ ┃ │ to remove. ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ │ ┃ │ 1: Proceed 2: Cancel Claude is waiting o ✻ Worked for 42s · done 4:20 PM │ ┃ ╰─────────────────────────────────────────── │ │ │ ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ⚠ Blast Radius · rm -rf │ │ Command rm -rf build && git push --force origin main │ │ Would delete nothing: no file matches build │ │ │ │ The paths don't exist, so rm has nothing to remove. │ │ │ │ 1: Proceed 2: Cancel Claude is waiting on your answer │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ⚠ Blast Radius · rm -rf │ │ Command rm -rf build && git push --force origin main │ │ Would delete nothing: no file matches build │ │ │ │ The paths don't exist, so rm has nothing to remove. │ │ │ │ 1: Proceed 2: Cancel Claude is waiting on your answer │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
Pane · Blast Radius · while holding a tool call
╭──────────────────────────────────────────────────────────╮ │ ⚠ Blast Radius · rm -rf │ │ Command rm -rf build && git push --force origin main │ │ Would delete nothing: no file matches build │ │ │ │ The paths don't exist, so rm has nothing to remove. │ │ │ │ 1: Proceed 2: Cancel Claude is waiting on your answer │ ╰──────────────────────────────────────────────────────────╯
README

Blast Radius

A Claude Code mod that holds a risky shell command and shows you what it would change before it runs. We're sharing it as a small, complete example of a mod that pauses a tool call and asks you to decide.

What this shows

When Claude calls Bash with one of the commands below, Blast Radius stops the call, works out what the command would touch, and opens a pane with two buttons: Proceed runs the command, Cancel refuses it. Claude sees the refusal and the reason.

CommandWhat the pane shows
rm -r, rm -f, rm -rfThe files it would delete, with the count and total size. Globs and ~ are expanded.
git reset --hardThe files with uncommitted changes, from git status --porcelain, and git diff --shortstat.
git checkout -- ., git restore .The files with unstaged changes.
git cleanThe untracked paths it would remove, from git clean -n with the same flags.
find ... -delete, find ... -exec rm (also -execdir, -ok, unlink)The paths it would delete, from the same find with its actions swapped for -print. Other actions such as -fprint or -exec chmod don't run while measuring.
git push --force (also -f, --force-with-lease, +ref)The commits on the remote branch that your HEAD doesn't have, which the push would drop.
manage.py migrate, db:migrate, alembic upgrade, prisma migrateThe pending migrations, from the tool's own status command.
any other migrateA note that it can't list the pending migrations for that tool.

Every other command runs as normal. If the command line moves first, with cd dir &&, pushd/popd or git -C dir, Blast Radius measures in that folder. A cd inside ( ... ) only applies inside the parentheses, as in the shell.

The patterns it demonstrates:

  • Holding a tool.call until the user answers, and returning { deny } with a reason Claude can act on.
  • Drawing the same report in a Pane, or in the AbovePrompt band when the pane is not visible.
  • Measuring with $.process.run, passing paths as arguments so nothing in them runs as shell.

Demo

rm -rf build held, with the files it would delete:

Blast Radius holding rm -rf build in a pane

After Cancel, Claude reports that nothing was deleted:

Claude reports the command was cancelled

The second try, after Proceed:

Claude reports the folder was deleted after Proceed

git reset --hard in a 120-column terminal, where the report is drawn in the band above the prompt:

Blast Radius showing git reset --hard in the band above the prompt

How it was built

  • Model: built with Claude in Claude Code. The test runs and screenshots used Claude Sonnet 5. The mod itself doesn't call a model.
  • Prompt(s): the mod started as one of ten ideas Claude wrote for mods. This is the idea as written:

Blast Radius. See what a command will touch, before it runs. When Claude runs a risky shell command, like rm, git reset, or a migration, the mod opens a pane. The pane lists the files and branches the command would change. The developer presses Proceed, or Cancel. It uses tool.call to hold the call, and ui.render on Pane, with Button elements. It adds a safety check, and it doesn't remove any, so it's safe to show. A bigger project, because each command needs its own dry run.

The build prompt, which picked this idea and two others by number:

implement 1,2,7. give me zips for them. test them in claude code and get me screenshots of what they look like when used.

  • Transcript: not shared. The build ran in an internal workspace.
  • Iterations:
  • A hook has a 10-second budget for its own code, which is far too short to wait for a person. Time spent inside a $ call doesn't count, so the hold is a loop that waits on $.process.run(["sleep", "0.25"]) until a button's onPress sets the decision.
  • A pane needs room. In a narrow terminal Claude Code doesn't place it, and a placed pane can be a tab behind another pane. While it holds a command, the mod reads $.ui.panes() on each poll and draws the report in the AbovePrompt band when its pane is not placed or not shown. Long lines wrap, so full paths stay readable in a narrow split.
  • Cancel has the focus when the pane opens, so pressing Enter refuses the command rather than running it.
  • An independent review before release found two problems in the measuring step, both fixed. A file named like a find action (for example -delete) that a glob matched could be read as an action while measuring, so relative paths now go to find with ./ in front. And a cd earlier on the command line was ignored, so the wrong folder was measured; the mod now follows cd and git -C. The same review led to smaller fixes: overlapping holds are queued, and the buttons always answer the command shown; an error while holding refuses the command; git clean -e, src:dst and HEAD force pushes are measured correctly; and sizes use du -k, which works on macOS as well as Linux.
  • Tested in Claude Code, before those fixes: rm -rf build was held for more than 30 seconds, Cancel kept the files and Proceed deleted them; git reset --hard listed the two changed files and Cancel kept them; git clean -fdx was held. Force pushes and migrations were checked against the command classifier only, not run. The fixes are covered by tests of the classifier, the measuring step and the hold queue, run with Node against a stand-in for Claude Code; they haven't been re-run in a live session.

Run it

Requirements:

  • Claude Code 2.1.287 or later, where mods load by default. The mod was built and tested on 2.1.280, and claude plugin validate passes on 2.1.285.
  • bash, git, find and du on your PATH. For migrations, the project's own tool (for example python3 manage.py showmigrations).
  • For the side pane, a terminal about 144 columns wide or more. Narrower terminals, and a pane hidden behind another tab, get the band above the prompt.

No environment variables or configuration.

Steps:

  1. Install it from this marketplace:
   /plugin install blast-radius --marketplace mlopian/claude-plugins

Or try it for one session from a local clone: claude --plugin-dir ./blast-radius.

  1. Start a new Claude Code session.
  1. Check it from the repository root: claude plugin validate blast-radius and claude plugin test blast-radius.
  1. Ask Claude to run something risky in a throwaway repo, for example "delete the build folder with rm -rf build".

Using the pane:

  • Press 1 for Proceed or 2 for Cancel. You can also click a button, or Tab to it and press Enter.
  • In the band above the prompt, 1 or 2 works while the input is empty.
  • If nobody answers within 10 minutes, the command is refused.
  • If you interrupt the turn (Esc), the command is refused.

Notes / limitations

  • It reads the command text. It doesn't parse shell fully: $(...), aliases, eval, bash -c "...", xargs rm, find -exec sh -c 'rm ...', scripts that call rm, and wrappers such as timeout 5 rm, doas rm, time -p rm or env -i rm aren't caught.
  • Only the first risky part of a command line is measured, and the pane shows the command on one line, cut off if it's long. Proceed runs the whole line as written.
  • It follows cd, pushd, popd and git -C on the same line. cd -, and a folder that doesn't exist, can't be measured; the pane says so and still holds the command. Otherwise it starts from the session's working folder.
  • In a narrow terminal the report is drawn in the band above the prompt, which only one mod can use at a time. If another mod that draws there (such as Replay Theater or Token Weather in this folder) takes the band, the Proceed and Cancel buttons may not show, and the command is refused after 10 minutes. Use a wider terminal, or turn the other mod off, when you rely on Blast Radius.
  • One command is held at a time. A second risky call, from a subagent for example, waits until the first is answered.
  • It only watches the Bash tool. File edits and other tools aren't held.
  • The rm count is approximate: a path matched twice is counted twice, and a file name with a line break is not counted. The list shows the first 10 files. Counts come from find and sizes from du -k, so a size is the space on disk, to the nearest kilobyte. A very large tree can take a few seconds to measure.
  • The force-push list uses your last fetch of the remote branch. Without one, it can't list the dropped commits, and it says so. When the push names no remote, it assumes origin.
  • To list pending migrations, it runs the tool's own status command (for example python3 manage.py showmigrations), which loads your project's code before you choose Proceed or Cancel. If that fails, the pane says it couldn't list them.
  • A few harmless commands are held too, such as a commit whose message contains ; rm -rf.
  • It checks one command at a time. It holds a call, but it doesn't sandbox it: after you press Proceed, the command runs as written.
  • This is a safety net, not a permission system. Use permission rules for a hard block.

Dependencies

NameVersionLicense (SPDX)Source
None

The mod has no packages to install. It calls tools that are already on the machine (listed under Requirements).

Third-party notices

Git is a trademark of Software Freedom Conservancy. Python is a registered trademark of the Python Software Foundation. npm is a trademark of npm, Inc. Django is a registered trademark of the Django Software Foundation. Rails and Ruby on Rails are trademarks of David Heinemeier Hansson. Prisma is a trademark of Prisma Data, Inc. Alembic is an open-source project of the SQLAlchemy authors. Use of these names here is descriptive and implies no endorsement.


Based on the Blast Radius example from anthropics/claude-code-playground (Apache-2.0), changed to also hold find -delete and find -exec rm.

Source 1 files
hooks/blast-radius.mjs 596 lines
1// Copyright 2026 Anthropic PBC
2// SPDX-License-Identifier: Apache-2.0
3//
4// Blast Radius: holds a risky Bash command and shows what it would change.
5//
6// tool.call (Bash): if the command is risky, work out its blast radius, open a
7// pane with Proceed and Cancel, and hold the call until one is pressed.
8// ui.render (Pane): draws the report. If the surface won't place the pane (a
9// narrow terminal), the same report is drawn in the AbovePrompt band instead.
10//
11// Holding: a hook has 10 s of its own time, but time spent inside a `$` call is
12// free. So the hold loop waits on a short `$.process.run(["sleep", ...])` until
13// a button's onPress sets the decision.
14//
15// The host reads `on(...)` and `$.noun.method(...)` from source, so they are
16// spelled literally, and helpers that take `$` are top-level functions.
17
18const PANE_ID = "blast-radius";
19const POLL_SECONDS = "0.25";
20const HOLD_LIMIT_MS = 10 * 60 * 1000;
21const LIST_MAX = 10;
22
23// The call being held, or null. One at a time: Bash calls in a turn run in order.
24let held = null;
25
26export function register(on) {
27  on("tool.call", { tool: "Bash" }, async ($, e, next) => {
28    const risk = classify(String(e.command ?? ""));
29    if (risk === null) {
30      return next(e);
31    }
32    // One hold at a time. If another risky call is already held (a subagent's,
33    // say), wait until it is answered. `held` is claimed with no await between
34    // the check and the claim, so two waiting calls can't both get through.
35    while (held !== null) {
36      if (next.signal.aborted) {
37        return { deny: "Blast Radius held this command and did not run it: the turn was interrupted. Do not retry it unless the user asks you to." };
38      }
39      await $.process.run(["sleep", POLL_SECONDS], { timeoutMs: 5000 });
40    }
41    const mine = { command: String(e.command), risk, report: null, decision: null, where: "pane" };
42    held = mine;
43
44    let opened = { isPlaced: false };
45    let decision;
46    let summary = risk.label;
47    let failure = "";
48    try {
49      // Measure where the command will run: the session folder, moved by any
50      // `cd dir &&` or `git -C dir` earlier in the same command line.
51      const sessionCwd = await $.session.cwd();
52      const cwd = risk.dir ? await resolveDir($, sessionCwd, risk.dir) : sessionCwd;
53      mine.report = cwd === null
54        ? { summary: `${risk.label} in ${risk.dir}`, lines: [], note: `Couldn't find the folder ${risk.dir}, so I couldn't measure what this would change.` }
55        : await measure($, risk, cwd);
56      summary = mine.report.summary;
57
58      opened = await $.ui.open({ id: PANE_ID, title: "Blast Radius", focus: true, rows: paneRows(mine.report) });
59      if (!opened.isPlaced) {
60        mine.where = "band";
61      }
62      $.ui.invalidate("ui.render");
63
64      const startedAt = await $.clock.now();
65      while (mine.decision === null) {
66        const pane = (await $.ui.panes()).find((p) => p.id === PANE_ID);
67        const where = pane?.isPlaced && pane.isShown ? "pane" : "band";
68        if (where !== mine.where) {
69          mine.where = where;
70          $.ui.invalidate("ui.render");
71        }
72        if (next.signal.aborted) {
73          mine.decision = "interrupted";
74          break;
75        }
76        if ((await $.clock.now()) - startedAt > HOLD_LIMIT_MS) {
77          mine.decision = "timeout";
78          break;
79        }
80        await $.process.run(["sleep", POLL_SECONDS], { timeoutMs: 5000 });
81      }
82    } catch (error) {
83      failure = String(error?.message ?? error);
84      $.ui.log(`blast-radius: ${failure}`);
85      mine.decision = "error"; // anything unexpected refuses the command
86    } finally {
87      decision = mine.decision;
88      // Close this call's pane before releasing the hold, so the next call's
89      // pane can't be the one that gets closed.
90      try {
91        await $.ui.close({ id: PANE_ID });
92      } catch {
93        // the pane is already gone
94      }
95      if (held === mine) {
96        held = null;
97      }
98      $.ui.invalidate("ui.render");
99    }
100
101    if (decision === "proceed") {
102      $.ui.toast("Blast Radius: running it");
103      return next(e);
104    }
105    const why = {
106      cancel: "the user pressed Cancel",
107      timeout: "no answer within 10 minutes",
108      interrupted: "the turn was interrupted",
109      error: `Blast Radius hit an error while holding it (${failure})`,
110    }[decision] ?? "no answer was recorded";
111    return {
112      deny: `Blast Radius held this command and did not run it: ${why}. It would have: ${summary}. Do not retry it unless the user asks you to.`,
113    };
114  });
115
116  on("ui.render", { component: "Pane" }, ($, e, next) => {
117    if (e.requestId !== PANE_ID || held === null || held.report === null) {
118      return next(e);
119    }
120    return draw($.ui.resolve(e), held);
121  });
122
123  on("ui.render", { component: "AbovePrompt" }, ($, e, next) => {
124    if (held === null || held.report === null || held.where !== "band") {
125      return next(e);
126    }
127    return draw($.ui.resolve(e), held);
128  });
129}
130
131// ---- What counts as risky -------------------------------------------------
132
133// sudo options that take a value, so the value isn't read as the command.
134const SUDO_VALUE_OPTIONS = new Set(["-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-T", "-U"]);
135// Commands that only read, so a bare word "migrate" in them isn't a migration.
136const READ_ONLY = new Set(["ls", "cat", "echo", "printf", "grep", "rg", "find", "less", "head", "tail", "cd", "git"]);
137
138/** A folder a later `cd arg` moves to, given the folder so far (null = the session folder). */
139function joinDir(dir, arg) {
140  if (arg === undefined || arg === "~" || arg.startsWith("/") || arg.startsWith("~/")) {
141    return arg ?? "~";
142  }
143  return dir ? `${dir}/${arg}` : arg;
144}
145
146/** The first risky segment of a shell command, or null. */
147export function classify(command) {
148  let dir = null; // where a `cd` earlier on the line moved to; null means the session folder
149  const scopes = []; // dir to restore when a ( subshell ) closes
150  const pushed = []; // pushd stack, for popd
151  for (const raw of command.split(/&&|\|\||;|\||\n/)) {
152    const opens = (raw.match(/^\s*\(+/)?.[0].trim().length) ?? 0;
153    // Trailing redirects and & don't hide a closing ) : `(cd sub && make) > log`.
154    const tail = raw.replace(/(?:\s*(?:\d*>>?|&>>?|<)\s*\S+|\s*&)+\s*$/, "");
155    const closes = (tail.match(/\)+\s*$/)?.[0].trim().length) ?? 0;
156    for (let k = 0; k < opens; k += 1) {
157      scopes.push(dir);
158    }
159    const risk = classifySegment(raw, dir, pushed);
160    if (risk !== null && risk.cd === undefined) {
161      return risk;
162    }
163    if (risk !== null) {
164      dir = risk.cd; // a cd, pushd or popd moved the folder
165    }
166    for (let k = 0; k < closes && scopes.length > 0; k += 1) {
167      dir = scopes.pop(); // a cd inside ( ... ) doesn't outlive it
168    }
169  }
170  return null;
171}
172
173// Words that can come before the real command without changing what it does.
174const PREFIXES = new Set(["command", "exec", "env", "nohup", "time", "then", "do", "else", "!"]);
175
176/** One segment: a risk, { cd } for a folder change, or null. */
177function classifySegment(segment, dir, pushed) {
178  {
179    const words = tokenize(segment.trim().replace(/^[({]+\s*/, "").replace(/\s*[)}]+$/, ""));
180    while (words.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) {
181      words.shift(); // leading VAR=value
182    }
183    if (words[0] === "sudo") {
184      words.shift();
185      while (words.length > 0 && words[0].startsWith("-")) {
186        const option = words.shift();
187        if (SUDO_VALUE_OPTIONS.has(option)) {
188          words.shift();
189        }
190      }
191    }
192    while (words.length > 0 && (PREFIXES.has(words[0]) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0]))) {
193      words.shift();
194    }
195    if (words[0] === "nice") {
196      words.shift();
197      if (words[0] === "-n") {
198        words.splice(0, 2);
199      } else if (/^-\d+$/.test(words[0] ?? "")) {
200        words.shift();
201      }
202    }
203    const [first, ...args] = words;
204    if (first === undefined) {
205      return null;
206    }
207    const cmd = first.replace(/^\\/, ""); // \rm skips aliases; it's still rm
208    if (cmd === "cd") {
209      return { cd: args[0] === "-" ? "-" : joinDir(dir, args[0]) };
210    }
211    if (cmd === "pushd") {
212      pushed.push(dir);
213      return { cd: joinDir(dir, args[0]) };
214    }
215    if (cmd === "popd") {
216      return { cd: pushed.length > 0 ? pushed.pop() : "-" };
217    }
218    if (cmd === "rm" || cmd.endsWith("/rm")) {
219      const flags = args.filter((a) => a.startsWith("-"));
220      const recursive = flags.some((f) => f === "--recursive" || (/^-[^-]/.test(f) && /[rR]/.test(f)));
221      const force = flags.some((f) => f === "--force" || (/^-[^-]/.test(f) && f.includes("f")));
222      if (recursive || force) {
223        const targets = args.filter((a) => !a.startsWith("-") || a === "-");
224        return { kind: "rm", label: `rm ${flags.join(" ")}`.trim(), targets, dir };
225      }
226    }
227    if (cmd === "find" || cmd.endsWith("/find")) {
228      const dryRun = findDryRun(args);
229      if (dryRun !== null) {
230        return { kind: "find", label: dryRun.label, args: dryRun.args, dir };
231      }
232    }
233    if (cmd === "git") {
234      // Git's own options come before the subcommand; -C moves where it runs.
235      let gitDir = dir;
236      let i = 0;
237      while (i < args.length && args[i].startsWith("-")) {
238        if (args[i] === "-C" && i + 1 < args.length) {
239          gitDir = joinDir(gitDir, args[i + 1]);
240          i += 2;
241        } else if (args[i] === "-c" && i + 1 < args.length) {
242          i += 2;
243        } else {
244          i += 1;
245        }
246      }
247      const sub = args[i];
248      const rest = args.slice(i + 1);
249      if (sub === "reset" && rest.includes("--hard")) {
250        return { kind: "git-reset", label: "git reset --hard", args: rest, dir: gitDir };
251      }
252      if (sub === "clean") {
253        return { kind: "git-clean", label: "git clean", args: rest, dir: gitDir };
254      }
255      if (sub === "push" && rest.some((a) => a === "--force" || a === "-f" || a.startsWith("--force-with-lease") || /^\+/.test(a))) {
256        return { kind: "git-push-force", label: "git push --force", args: rest, dir: gitDir };
257      }
258      const stagedOnly = sub === "restore" && rest.includes("--staged") && !rest.includes("--worktree") && !rest.includes("-W");
259      if ((sub === "checkout" || sub === "restore") && rest.includes(".") && !stagedOnly) {
260        return { kind: "git-checkout", label: `git ${sub} -- .`, args: rest, dir: gitDir };
261      }
262    }
263    const joined = words.join(" ");
264    if (/\balembic\s+upgrade\b/.test(joined)) {
265      return { kind: "migrate", tool: "alembic", label: "alembic upgrade", dir };
266    }
267    if (/\bdb:migrate(?!:status\b)/.test(joined)) {
268      return { kind: "migrate", tool: "rails", label: "db:migrate", dir };
269    }
270    if (/\bprisma\s+migrate\b/.test(joined)) {
271      return { kind: "migrate", tool: "prisma", label: "prisma migrate", dir };
272    }
273    if (/\bmanage\.py\s+migrate\b/.test(joined)) {
274      return { kind: "migrate", tool: "django", label: "manage.py migrate", dir };
275    }
276    if (!READ_ONLY.has(cmd) && args.includes("migrate")) {
277      return { kind: "migrate", tool: "unknown", label: "migrate", dir };
278    }
279  }
280  return null;
281}
282
283const FIND_RUNS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
284const FIND_OUTPUTS = new Map([["-print", 0], ["-print0", 0], ["-ls", 0], ["-printf", 1], ["-fprint", 1], ["-fprint0", 1], ["-fls", 1], ["-fprintf", 2]]);
285
286function isRemover(word) {
287  const tool = (word ?? "").replace(/^\\/, "");
288  return tool === "rm" || tool.endsWith("/rm") || tool === "unlink" || tool.endsWith("/unlink");
289}
290
291export function findDryRun(args) {
292  const out = [];
293  const actions = new Set();
294  for (let i = 0; i < args.length; i += 1) {
295    const a = args[i];
296    if (a === "-delete") {
297      actions.add("-delete");
298      out.push("-print");
299    } else if (FIND_RUNS.has(a)) {
300      let end = i + 1;
301      while (end < args.length && !/^\\?;$/.test(args[end]) && args[end] !== "+") {
302        end += 1;
303      }
304      const removes = isRemover(args[i + 1]);
305      if (removes) {
306        actions.add(`${a} rm`);
307      }
308      out.push(removes ? "-print" : "-true");
309      i = end;
310    } else if (FIND_OUTPUTS.has(a)) {
311      out.push("-true");
312      i += FIND_OUTPUTS.get(a);
313    } else {
314      out.push(a);
315    }
316  }
317  return actions.size === 0 ? null : { label: `find ${[...actions].join(" ")}`, args: out };
318}
319
320// Resolves a `cd` target to an absolute folder, or null if it doesn't exist.
321// The target is passed as an argument, never as source.
322const CD_SCRIPT = `unset CDPATH; d="$1"; case "$d" in "~") d="$HOME";; "~/"*) d="$HOME/\${d#\\~/}";; esac; cd -- "$d" 2>/dev/null && pwd -P`;
323
324async function resolveDir($, sessionCwd, dir) {
325  if (dir === "-") {
326    return null; // `cd -` depends on the shell's history
327  }
328  const run = await $.process.run(["bash", "-c", CD_SCRIPT, "blast-radius", dir], { cwd: sessionCwd, timeoutMs: 5000 });
329  const out = run.stdout.trim();
330  return run.exitCode === 0 && out !== "" ? out : null;
331}
332
333/** Splits one segment into words, honouring quotes. Good enough to read flags and paths. */
334function tokenize(text) {
335  const words = [];
336  const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g;
337  let m;
338  while ((m = re.exec(text)) !== null) {
339    words.push(m[1] ?? m[2] ?? m[3]);
340  }
341  return words;
342}
343
344// ---- Measuring the blast radius -------------------------------------------
345
346/** { summary, lines, note } for the pane. Never throws: a failed read is said, not hidden. */
347async function measure($, risk, cwd) {
348  try {
349    if (risk.kind === "rm") {
350      return await measureRm($, risk, cwd);
351    }
352    if (risk.kind === "migrate") {
353      return await measureMigrations($, risk, cwd);
354    }
355    if (risk.kind === "find") {
356      return await measureFind($, risk, cwd);
357    }
358    return await measureGit($, risk, cwd);
359  } catch (error) {
360    return { summary: `${risk.label} (could not measure it)`, lines: [], note: `Could not measure: ${String(error?.message ?? error).slice(0, 200)}` };
361  }
362}
363
364// The paths are passed to bash as arguments, never as source, so nothing in
365// them runs. compgen -G expands a glob without command substitution.
366const RM_SCRIPT = `
367shopt -s nullglob dotglob
368paths=()
369for p in "$@"; do
370  case "$p" in "~"|"~/"*) p="$HOME\${p#\\~}";; esac
371  if [[ "$p" == *[*?[]* ]]; then
372    while IFS= read -r m; do paths+=("$m"); done < <(compgen -G "$p")
373  elif [[ -e "$p" || -L "$p" ]]; then
374    paths+=("$p")
375  fi
376done
377if (( \${#paths[@]} == 0 )); then echo "0 0 0"; exit 0; fi
378# A relative path gets ./ in front, so find never reads a name like -delete as an action.
379for i in "\${!paths[@]}"; do case "\${paths[$i]}" in /*) ;; *) paths[$i]="./\${paths[$i]}";; esac; done
380files=$(find "\${paths[@]}" \\( -type f -o -type l \\) 2>/dev/null | wc -l | tr -d ' ')
381kb=$(du -skc "\${paths[@]}" 2>/dev/null | tail -n1 | cut -f1)
382echo "$files $(( \${kb:-0} * 1024 )) \${#paths[@]}"
383find "\${paths[@]}" \\( -type f -o -type l \\) 2>/dev/null | head -n ${LIST_MAX}
384`;
385
386async function measureRm($, risk, cwd) {
387  if (risk.targets.length === 0) {
388    return { summary: "rm with no paths", lines: [], note: "No paths to expand." };
389  }
390  const run = await $.process.run(["bash", "-c", RM_SCRIPT, "blast-radius", ...risk.targets], { cwd, timeoutMs: 15000 });
391  const [head, ...rest] = run.stdout.split("\n").filter((l) => l !== "");
392  const [files, bytes, found] = (head ?? "0 0 0").split(" ").map(Number);
393  if (!found) {
394    return { summary: `delete nothing: no file matches ${risk.targets.join(" ")}`, lines: [], note: "The paths don't exist, so rm has nothing to remove." };
395  }
396  if (!files) {
397    return { summary: `delete ${found} ${found === 1 ? "path" : "paths"} with no files in ${found === 1 ? "it" : "them"}`, lines: [], note: `Paths: ${risk.targets.join(" ")}` };
398  }
399  return {
400    summary: `delete ${files} ${files === 1 ? "file" : "files"} (about ${size(bytes)})`,
401    lines: rest.map((l) => l.replace(/^\.\//, "")),
402    more: Math.max(0, files - rest.length),
403    note: `Paths: ${risk.targets.join(" ")}`,
404  };
405}
406
407async function measureFind($, risk, cwd) {
408  const run = await $.process.run(["find", ...risk.args], { cwd, timeoutMs: 15000 });
409  const paths = run.stdout.split("\n").filter((l) => l !== "");
410  if (run.exitCode !== 0 && paths.length === 0) {
411    return { summary: `${risk.label} (could not dry-run it)`, lines: [], note: run.stderr.trim().slice(0, 200) };
412  }
413  return {
414    summary: paths.length === 0 ? "delete nothing: find matches no paths" : `delete ${paths.length}${run.isStdoutTruncated ? "+" : ""} ${paths.length === 1 ? "path" : "paths"}`,
415    lines: paths.slice(0, LIST_MAX).map((l) => l.replace(/^\.\//, "")),
416    more: Math.max(0, paths.length - LIST_MAX),
417    note: "From the same find with its actions swapped for -print. Deleted files can't be recovered.",
418  };
419}
420
421async function measureGit($, risk, cwd) {
422  if (risk.kind === "git-push-force") {
423    return await measurePush($, risk, cwd);
424  }
425  if (risk.kind === "git-clean") {
426    const flags = [];
427    const paths = [];
428    for (let i = 0; i < risk.args.length; i += 1) {
429      const a = risk.args[i];
430      if (a === "--") {
431        paths.push(...risk.args.slice(i + 1));
432        break;
433      }
434      if (a === "-e" || a === "--exclude") {
435        flags.push(a, risk.args[i + 1] ?? "");
436        i += 1;
437      } else if (a.startsWith("--exclude=") || /^-e./.test(a)) {
438        flags.push(a);
439      } else if (/^-[a-zA-Z]+$/.test(a)) {
440        const kept = a.replace(/[finq]/g, ""); // -n is added below; -f, -i and -q would change the dry run
441        if (kept !== "-") {
442          flags.push(kept);
443        }
444      } else if (!a.startsWith("-")) {
445        paths.push(a);
446      }
447    }
448    const run = await $.process.run(["git", "clean", "-n", ...flags, "--", ...paths], { cwd, timeoutMs: 15000 });
449    if (run.exitCode !== 0) {
450      return { summary: "git clean (could not dry-run it)", lines: [], note: run.stderr.trim().slice(0, 200) };
451    }
452    const gone = run.stdout.split("\n").filter((l) => l.startsWith("Would remove ")).map((l) => l.slice(13));
453    return {
454      summary: gone.length === 0 ? "remove nothing: no untracked files match" : `remove ${gone.length} untracked ${gone.length === 1 ? "path" : "paths"}`,
455      lines: gone.slice(0, LIST_MAX),
456      more: Math.max(0, gone.length - LIST_MAX),
457      note: "From git clean -n. Untracked files are not in git, so they can't be recovered.",
458    };
459  }
460  const status = await $.process.run(["git", "status", "--porcelain"], { cwd, timeoutMs: 15000 });
461  if (status.exitCode !== 0) {
462    return { summary: `${risk.label} (not a git repo here?)`, lines: [], note: status.stderr.trim().slice(0, 200) };
463  }
464  const rows = status.stdout.split("\n").filter((l) => l.length > 3 && !l.startsWith("??"));
465  // reset --hard drops staged and unstaged changes; checkout -- . drops unstaged ones.
466  const lost = risk.kind === "git-reset" ? rows : rows.filter((l) => l[1] !== " ");
467  const stat = await $.process.run(["git", "diff", "--shortstat", risk.kind === "git-reset" ? "HEAD" : "--"], { cwd, timeoutMs: 15000 });
468  return {
469    summary: lost.length === 0 ? "discard nothing: no uncommitted changes" : `discard uncommitted changes in ${lost.length} ${lost.length === 1 ? "file" : "files"}`,
470    lines: lost.slice(0, LIST_MAX).map((l) => `${l.slice(0, 2)} ${l.slice(3)}`),
471    more: Math.max(0, lost.length - LIST_MAX),
472    note: stat.stdout.trim() !== "" ? `${stat.stdout.trim()}. Uncommitted changes can't be recovered.` : "From git status --porcelain.",
473  };
474}
475
476async function measurePush($, risk, cwd) {
477  const positional = risk.args.filter((a) => !a.startsWith("-"));
478  const remote = positional[0] ?? "origin";
479  // A refspec is src:dst. With no colon, the local branch of the same name is pushed.
480  const spec = (positional[1] ?? "").replace(/^\+/, "");
481  let [source, branch] = spec.includes(":") ? spec.split(":") : [spec, spec];
482  branch = (branch ?? "").replace(/^refs\/heads\//, "");
483  if (!branch) {
484    const head = await $.process.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeoutMs: 10000 });
485    branch = head.stdout.trim();
486    source = "HEAD";
487  } else if (branch === "HEAD") {
488    // `git push origin HEAD` pushes the current branch to its namesake.
489    const head = await $.process.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeoutMs: 10000 });
490    branch = head.stdout.trim();
491    source = "HEAD";
492  }
493  source = source || "HEAD";
494  const ref = `${remote}/${branch}`;
495  const known = await $.process.run(["git", "rev-parse", "--verify", "--quiet", ref], { cwd, timeoutMs: 10000 });
496  if (known.exitCode !== 0) {
497    return { summary: `force-push to ${ref}`, lines: [], note: `No local copy of ${ref}, so I can't tell which commits the push would drop. Run git fetch first.` };
498  }
499  const log = await $.process.run(["git", "log", "--oneline", "--no-decorate", `${source}..${ref}`], { cwd, timeoutMs: 15000 });
500  const dropped = log.stdout.split("\n").filter((l) => l !== "");
501  return {
502    summary: dropped.length === 0 ? `force-push to ${ref}: drops no commits` : `force-push to ${ref}: drops ${dropped.length} ${dropped.length === 1 ? "commit" : "commits"}`,
503    lines: dropped.slice(0, LIST_MAX),
504    more: Math.max(0, dropped.length - LIST_MAX),
505    note: `Commits on ${ref} that ${source} doesn't have, as of the last fetch.`,
506  };
507}
508
509const MIGRATION_LISTERS = {
510  django: { argv: ["python3", "manage.py", "showmigrations", "--plan"], pending: (l) => l.startsWith("[ ]"), strip: (l) => l.slice(4) },
511  alembic: { argv: ["alembic", "history", "-r", "current:head"], pending: (l) => l.includes("->"), strip: (l) => l },
512  rails: { argv: ["bin/rails", "db:migrate:status"], pending: (l) => /^\s*down\b/.test(l), strip: (l) => l.trim() },
513  prisma: { argv: ["npx", "--no-install", "prisma", "migrate", "status"], pending: (l) => /^\s{2}\S/.test(l), strip: (l) => l.trim() },
514};
515
516async function measureMigrations($, risk, cwd) {
517  const lister = MIGRATION_LISTERS[risk.tool];
518  if (lister === undefined) {
519    return { summary: "run migrations", lines: [], note: "I can't list the pending migrations for this tool, so the list is not shown." };
520  }
521  let run;
522  try {
523    run = await $.process.run(lister.argv, { cwd, timeoutMs: 20000 });
524  } catch (error) {
525    run = { exitCode: -1, stdout: "", stderr: String(error?.message ?? error) };
526  }
527  if (run.exitCode !== 0) {
528    return { summary: `run ${risk.label}`, lines: [], note: `Couldn't list pending migrations (${lister.argv.join(" ")} failed).` };
529  }
530  const pending = run.stdout.split("\n").filter(lister.pending).map(lister.strip);
531  return {
532    summary: pending.length === 0 ? `run ${risk.label}: nothing pending` : `apply ${pending.length} pending ${pending.length === 1 ? "migration" : "migrations"}`,
533    lines: pending.slice(0, LIST_MAX),
534    more: Math.max(0, pending.length - LIST_MAX),
535    note: `From ${lister.argv.join(" ")}.`,
536  };
537}
538
539function size(bytes) {
540  if (!Number.isFinite(bytes) || bytes < 1024) {
541    return `${bytes || 0} B`;
542  }
543  const units = ["KB", "MB", "GB", "TB"];
544  let n = bytes;
545  let i = -1;
546  while (n >= 1024 && i < units.length - 1) {
547    n /= 1024;
548    i += 1;
549  }
550  return `${n.toFixed(n < 10 ? 1 : 0)} ${units[i]}`;
551}
552
553// ---- Drawing --------------------------------------------------------------
554
555function paneRows(report) {
556  return Math.min(24, 9 + report.lines.length + (report.more ? 1 : 0));
557}
558
559function draw(t, state) {
560  const { Box, Text, Button } = t;
561  const { report } = state;
562  const list = report.lines.map((line, i) => Text({ key: `l${i}`, children: `  ${line}`, wrap: "wrap" }));
563  if (report.more) {
564    list.push(Text({ key: "more", dimColor: true, children: `  + ${report.more} more` }));
565  }
566  // The buttons answer the call this pane was drawn for, never whichever one is held now.
567  const decide = (choice) => () => {
568    if (state.decision === null) {
569      state.decision = choice;
570    }
571  };
572  return Box({
573    flexDirection: "column",
574    borderStyle: "round",
575    borderColor: "yellow",
576    paddingX: 1,
577    children: [
578      Text({ key: "title", bold: true, color: "yellow", children: `⚠ Blast Radius · ${state.risk.label}` }),
579      Text({ key: "cmd", children: [Text({ dimColor: true, children: "Command  " }), Text({ bold: true, children: state.command })], wrap: "wrap" }),
580      Text({ key: "sum", children: [Text({ dimColor: true, children: "Would    " }), Text({ color: "red", bold: true, children: report.summary })] }),
581      Box({ key: "list", flexDirection: "column", marginTop: 1, children: list }),
582      report.note ? Text({ key: "note", dimColor: true, italic: true, children: report.note, wrap: "wrap" }) : null,
583      Box({
584        key: "buttons",
585        marginTop: 1,
586        gap: 2,
587        children: [
588          Button({ key: "proceed", label: "Proceed", hotkey: "1", plain: true, onPress: decide("proceed") }),
589          Button({ key: "cancel", label: "Cancel", hotkey: "2", plain: true, autoFocus: true, onPress: decide("cancel") }),
590          Text({ key: "hint", dimColor: true, children: "Claude is waiting on your answer" }),
591        ],
592      }),
593    ],
594  });
595}
596