[mod] Holds risky shell commands (rm -rf, git reset --hard, force push, git clean, migrations, find -delete, xargs rm, also inside bash -c / eval) and shows…

japan-da-man の Claude Code プラグイン(mods を含む)を管理するマーケットプレイス。
| 名前 | 内容 | | :- | :- | | japan-da-man-mods | まとめてインストール用。下のプラグインを全部入れる | | todo-mod | /todo で TODO パネルを開く。チェックを入れたタスクを Claude に依頼する | | token-weather | コンテキストの埋まり具合を天気でプロンプトの上に表示する(☀ Clear → ☁ Cloudy → ☂ Showers → ☇ Storm → ↯ Compact soon)。直近12ターンのグラフと、直前のターンの増減(▲ +98.3k last turn)付き。/weather で表示切り替え | | usage-stats | /stats で利用統計のパネルを開く。セッション数・メッセージ数・トークン数・利用日数・連続日数・よく使うモデル・日ごとのヒートマップ | | blast-radius | 危険なシェルコマンドを実行前に止め、何が消えるか・変わるかをペインに出して Proceed / Cancel で選ばせる(10分答えがなければ止める)。ターミナルのないデスクトップアプリなどでは、ペインの代わりに確認ダイアログ(AskUserQuestion)で聞き、聞けないときは待たずに止めて、Terminal で自分で実行するためのコマンドを Claude に渡す。rm -r/-f、git reset --hard、force push、git clean、変更の破棄、git branch -D(コミットがすべて HEAD にある、rebase マージ済みのブランチは止めない)、git stash drop/clear、マイグレーション、find -delete、xargs rm。bash -c / eval の中も調べる。/blast-radius で履歴 | | replay-theater | ターンの中で Claude が行ったファイル編集を記録する。ターンが終わるとプロンプトの上に ▶ Replay: N edits が出て、r か /replay でペインを開き、編集を 1 件ずつ差分で見られる(Prev / Next / Close) | | spec-flow | 「〇〇な機能が欲しい」と話しかけるか /spec-flow:spec <要望> で、要求整理 → 影響画面確認 → 要件定義 → 機能案・UI案 を 1 段階ずつ承認しながら進める。曖昧な点はヒアリングし、影響調査と案出しはサブエージェントが行う。成果物は docs/specs/<id>/(UI 案の HTML モックは Desktop なら Artifact にも公開。--local で公開しない)。/specs でチェックリストを開き、チェックで承認・修正依頼もできる | | dev-flow | 汎用の開発フロー。skills plan(小さなタスクに分けて承認をもらってから着手)・tdd(RED → GREEN → REFACTOR)・debug(再現 → 仮説 → 検証で原因を確かめてから直す)・review(重要度つきの差分レビュー)。サブエージェント code-explorer(横断調査)・test-runner(テスト結果の要約)・reviewer(別コンテキストでレビュー、修正はしない)が長い出力をメインに持ち込まない | | dev-extras | 他の OSS から選んで取り込んだ skill(すべて MIT、出典は各 README と licenses/)。ponytail(最小の実装に絞る)・ponytail-review(作り込みすぎだけを探す)・grill-me(質問攻めで計画を詰める)・handoff(バックグラウンドエージェントに引き継ぐ)・verification-before-completion(検証してから完了と言う)・security-audit(Cloudflare 製のセキュリティ監査) | | factory | AI のソフトウェアファクトリー(いまは iOS アプリ向け)。/factory:init で設定を作り、/factory:start <要望> で一問一答のインタビュー → 仕様 → 隠しシナリオの承認まで行うと、裏のラインが 実装(Sonnet, TDD)→ ビルドと全テスト → シミュレーターでの検証(agent-device)→ 判定(Opus) を回し、満足度が基準を超えたら PR を squash マージする。実装役からシナリオは見えない(deny とサンドボックス)。判定役とシナリオ作成役は、設定で Codex(codex exec)にもできる。実装の前に今のアプリでシナリオを流す陰性対照、検証したコミット(SHA)だけをマージする縛り、シナリオの XCUITest による速い検証、症状を返さない最終関門のシナリオ、テストの有無・変更行数・lint の品質関門、時間と費用の記録も持つ。/factory:status で進み具合と、人の評価と判定の一致率。設計は DESIGN.md | | design-system | アプリの見た目の決まり(デザインシステム)を、人が決めて先に作り、育てる(いまは iOS / SwiftUI)。/design-system:init で今のコードから色・文字・余白・部品・文言・画面の形を読み取り、決まっていない点を一問一答で決めて、design-system/ の文書と tokens.json、SwiftUI の部品(ボタン・入力・一覧・メッセージ・状態など 18 種類)とカタログ画面を置き、今の画面も書き換える。カタログはシミュレーターでライトとダークのスクリーンショットを撮って確かめる。node design-system/check.mjs が直書きの色・文字・余白や部品を通さないボタンをファイル:行つきで落とす(factory のゲートにも使える)。/design-system:update で変え、/design-system:check で調べる。Artifact の Design System に一方向で写す。設計は DESIGN.md | | mod-dev | skill add-mod。「〇〇する mod を作って」で雛形・テスト・登録まで行う。marketplace リポジトリでは marketplace.json / bundle / README も更新し、それ以外では単体の mod を作る |
claude plugin marketplace add japan-da-man/claude-code
claude plugin install japan-da-man-mods@japan-da-man
1つずつ入れる場合は claude plugin install <名前>@japan-da-man。
更新:
claude plugin marketplace update japan-da-man
claude plugin update <名前>@japan-da-man
bundle に増えたプラグインを入れるときは、update → install の順で実行する(update だけだと増えた分は入らず、bundle が failed to load になる):
claude plugin marketplace update japan-da-man
claude plugin update japan-da-man-mods@japan-da-man
claude plugin install japan-da-man-mods@japan-da-man
セッション内なら update のあと /reload-plugins でもよい。
インストールせずに作業中のディレクトリを読み込む(保存するとホットリロードされる):
claude --plugin-dir ./plugins/todo-mod
チェック:
claude plugin validate .
claude plugin validate ./plugins/todo-mod
テスト(tests/*.test.ts があるプラグイン):
cd plugins/<name> && claude plugin test
mod-dev を入れた状態でこのリポジトリを開き「〇〇する mod を追加して」と頼むと、skill add-mod が下の手順(雛形・テスト・marketplace / bundle / README 更新・validate)をまとめてやる。手でやる場合:
plugins/<name>/ に .claude-plugin/plugin.json と中身を置く.claude-plugin/marketplace.json の plugins にエントリを追加する(name は plugin.json と同じにする)plugins/japan-da-man-mods/.claude-plugin/plugin.json の dependencies にも名前を足すplugin.json に version を書いていないので、コミットごとに新しいバージョンとして扱われる。
mods は Claude Code v2.1.287 以降が必要。
token-weather・blast-radius・replay-theater は、Anthropic の claude-code-playground にある同名の mod(Apache-2.0)をもとに手を加えたもの。各プラグインに LICENSE を同梱し、各 hooks/register.js の先頭に元のコードの著作権表示と、こちらで変えた点を書いている。
hooks/register.js 868 lines1// 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. With no
8// terminal attached, ask in the engine's dialog instead (see askInDialog).
9// ui.render (Pane): draws the report. If the surface won't place the pane (a
10// narrow terminal), the same report is drawn in the AbovePrompt band instead.
11//
12// Holding: a hook has 10 s of its own time, but time spent inside a `$` call is
13// free. So the hold loop waits on a short `$.process.run(["sleep", ...])` until
14// a button's onPress sets the decision.
15//
16// The host reads `on(...)` and `$.noun.method(...)` from source, so they are
17// spelled literally, and helpers that take `$` are top-level functions.
18//
19// Based on mods/blast-radius in anthropics/claude-code-playground (Apache-2.0, see LICENSE).
20//
21// japan-da-man による変更:
22// - コマンドをクォートを考慮して区切る('a && b' のような引数の中の && で切らない)
23// - bash -c / sh -c / zsh -c / eval の中身も同じルールで調べる
24// - find -delete / find -exec rm(消える一覧は削除なしの find で下見)、xargs rm を捕まえる
25// - git branch -D、git stash drop / clear、パスを指定した git checkout -- / git restore を捕まえる
26// - rm の対象が変数のときや、ルート・ホーム・フォルダ全体のときは注意書きを出す
27// - ターミナルがないセッション(デスクトップアプリなど)ではペインが描かれないことがあるので、
28// エンジンの確認ダイアログ($.ui.ask、AskUserQuestion)で Proceed / Cancel を聞く。
29// 聞けない(claude -p など)ときは待たずに止め、ユーザーが Terminal で自分で実行するコマンドを Claude に返す
30// - git branch -D は git cherry で patch ごとに比べ、すべて HEAD にある(rebase マージ済み)なら止めない
31// - フック自体が失敗・時間切れになったときも止める(.catch)
32// - /blast-radius で、最近止めたコマンドとその結果を一覧する
33
34const PANE_ID = "blast-radius";
35const POLL_SECONDS = "0.25";
36const HOLD_LIMIT_MS = 10 * 60 * 1000;
37const LIST_MAX = 10;
38const HISTORY_MAX = 10;
39const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh"]);
40
41// 最近捕まえたコマンド(新しい順): { command, summary, outcome }
42let history = [];
43
44// The call being held, or null. One at a time: Bash calls in a turn run in order.
45let held = null;
46
47export function register(on) {
48 on("session.start", async ($, e, next) => {
49 const result = await next(e);
50 await $.command.register({ name: "blast-radius", description: "Blast Radius: commands it held recently, and what happened", immediate: true });
51 return result;
52 });
53
54 on("command.run", { command: "blast-radius" }, async () => {
55 if (history.length === 0) {
56 return { text: "Blast Radius hasn't held any command in this session." };
57 }
58 return { text: history.map((h) => `${h.outcome.padEnd(9)} ${h.command}\n ${h.summary}`).join("\n") };
59 });
60
61 on("tool.call", { tool: "Bash" }, async ($, e, next) => {
62 const risk = classify(String(e.command ?? ""));
63 if (risk === null) {
64 return next(e);
65 }
66 // One hold at a time. If another risky call is already held (a subagent's,
67 // say), wait until it is answered. `held` is claimed with no await between
68 // the check and the claim, so two waiting calls can't both get through.
69 while (held !== null) {
70 if (next.signal.aborted) {
71 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." };
72 }
73 await $.process.run(["sleep", POLL_SECONDS], { timeoutMs: 5000 });
74 }
75 const mine = { command: String(e.command), risk, report: null, decision: null, where: "pane", answer: null, sessionCwd: null };
76 held = mine;
77
78 let opened = { isPlaced: false };
79 let decision;
80 let summary = risk.label;
81 try {
82 // Measure where the command will run: the session folder, moved by any
83 // `cd dir &&` or `git -C dir` earlier in the same command line.
84 const sessionCwd = await $.session.cwd();
85 mine.sessionCwd = sessionCwd;
86 const cwd = risk.dir ? await resolveDir($, sessionCwd, risk.dir) : sessionCwd;
87 mine.report = cwd === null
88 ? { summary: `${risk.label} in ${risk.dir}`, lines: [], note: `Couldn't find the folder ${risk.dir}, so I couldn't measure what this would change.` }
89 : await measure($, risk, cwd);
90 summary = mine.report.summary;
91
92 if (mine.report.isHarmless) {
93 // 測った結果、失うものがない(patch がすべて HEAD にあるブランチの削除など)ので聞かない
94 mine.decision = "harmless";
95 } else if ((await $.session.surfaces()).includes("terminal")) {
96 opened = await $.ui.open({ id: PANE_ID, title: "Blast Radius", focus: true, rows: paneRows(mine.report) });
97 if (!opened.isPlaced) {
98 mine.where = "band";
99 }
100 $.ui.invalidate("ui.render");
101
102 const startedAt = await $.clock.now();
103 while (mine.decision === null) {
104 if (next.signal.aborted) {
105 mine.decision = "interrupted";
106 break;
107 }
108 if ((await $.clock.now()) - startedAt > HOLD_LIMIT_MS) {
109 mine.decision = "timeout";
110 break;
111 }
112 await $.process.run(["sleep", POLL_SECONDS], { timeoutMs: 5000 });
113 }
114 } else {
115 // ターミナルがない(デスクトップアプリ、claude -p など)。ペインは描かれないことがあるので、
116 // エンジン自身の確認ダイアログ(AskUserQuestion)で聞く。聞けなければすぐ断る
117 mine.where = "dialog";
118 await askInDialog($, mine, next.signal);
119 }
120 } catch {
121 mine.decision = "error"; // anything unexpected refuses the command
122 } finally {
123 decision = mine.decision;
124 // Close this call's pane before releasing the hold, so the next call's
125 // pane can't be the one that gets closed.
126 try {
127 if (opened.isPlaced) {
128 await $.ui.close({ id: PANE_ID });
129 }
130 } catch {
131 // the pane is already gone
132 }
133 if (held === mine) {
134 held = null;
135 }
136 $.ui.invalidate("ui.render");
137 }
138
139 remember(mine.command, summary, decision === "proceed" || decision === "harmless" ? "ran" : decision);
140 if (decision === "harmless") {
141 return next(e);
142 }
143 if (decision === "proceed") {
144 $.ui.toast("Blast Radius: running it");
145 return next(e);
146 }
147 const why = {
148 cancel: mine.where === "dialog" ? "the user chose Cancel" : "the user pressed Cancel",
149 other: `the user answered "${mine.answer}" instead of Proceed`,
150 unanswerable: "Blast Radius could not ask the user (this session can show neither its pane nor a question dialog)",
151 timeout: "no answer within 10 minutes",
152 interrupted: "the turn was interrupted",
153 error: "Blast Radius hit an error while holding it",
154 }[decision] ?? "no answer was recorded";
155 // 聞けなかった・答えがなかったときは、ユーザーが自分で実行できるコマンドを渡す
156 const yourself = (decision === "unanswerable" || decision === "timeout") && mine.sessionCwd !== null
157 ? ` If the user wants it run, give them this command to run themselves in Terminal:\n\n${terminalCommand(mine.sessionCwd, mine.command)}\n`
158 : "";
159 return {
160 deny: `Blast Radius held this command and did not run it: ${why}. It would have: ${summary}.${yourself} Do not retry it unless the user asks you to.`,
161 };
162 })
163 // このフック自体が失敗したり 10 秒の持ち時間を超えたりすると、Claude Code はフックを飛ばしてコマンドを実行してしまう。
164 // 安全装置なので、そのときも止める側に倒す
165 .catch(($, e, next) => ({
166 deny: next.called
167 ? `Blast Radius failed after the command had started (${next.error.message}). The command may have run.`
168 : `Blast Radius couldn't check this command (${next.error.message}), so it did not run it. Ask the user before retrying.`,
169 }));
170
171 on("ui.render", { component: "Pane" }, ($, e, next) => {
172 if (e.requestId !== PANE_ID || held === null || held.report === null) {
173 return next(e);
174 }
175 return draw($.ui.resolve(e), held);
176 });
177
178 on("ui.render", { component: "AbovePrompt" }, ($, e, next) => {
179 if (held === null || held.report === null || held.where !== "band") {
180 return next(e);
181 }
182 return draw($.ui.resolve(e), held);
183 });
184}
185
186function remember(command, summary, outcome) {
187 history = [{ command, summary, outcome }, ...history].slice(0, HISTORY_MAX);
188}
189
190// ---- Asking without a pane --------------------------------------------------
191
192const DIALOG_LINES = 5;
193
194/** The question for the engine's dialog: the command, then the report the pane would show. */
195function dialogQuestion(state) {
196 const { report } = state;
197 const lines = report.lines.slice(0, DIALOG_LINES);
198 const more = report.lines.length - lines.length + (report.more ?? 0);
199 return [
200 `Run this command? It would: ${report.summary}.`,
201 state.command,
202 lines.length > 0 ? lines.join("\n") + (more > 0 ? `\n+ ${more} more` : "") : null,
203 report.note || null,
204 ].filter(Boolean).join("\n\n");
205}
206
207// $.ui.ask は答えが来るまで返らないので、待つ間は時計と中断を見張る。
208// 閉じられた・聞けない(claude -p)ときは reject され、「聞けなかった」としてすぐ断る
209async function askInDialog($, state, signal) {
210 let settled = null;
211 $.ui.ask(dialogQuestion(state), { header: "Blast Radius", options: ["Proceed", "Cancel"] })
212 .then((answer) => { settled = { answer }; }, () => { settled = { answer: null }; });
213 const startedAt = await $.clock.now();
214 while (settled === null) {
215 if (signal.aborted) {
216 state.decision = "interrupted";
217 return;
218 }
219 if ((await $.clock.now()) - startedAt > HOLD_LIMIT_MS) {
220 state.decision = "timeout";
221 return;
222 }
223 await $.process.run(["sleep", POLL_SECONDS], { timeoutMs: 5000 });
224 }
225 if (settled.answer === null) {
226 state.decision = "unanswerable";
227 } else if (settled.answer === "Proceed" || settled.answer === "Cancel") {
228 state.decision = settled.answer.toLowerCase();
229 } else {
230 state.decision = "other"; // typed under Other
231 state.answer = settled.answer;
232 }
233}
234
235/** The command as the user would run it in their own Terminal: from the session folder. */
236function terminalCommand(cwd, command) {
237 return `cd ${shellQuote(cwd)} && ${command}`;
238}
239
240function shellQuote(text) {
241 return `'${text.replace(/'/g, `'\\''`)}'`;
242}
243
244// ---- What counts as risky -------------------------------------------------
245
246// sudo options that take a value, so the value isn't read as the command.
247const SUDO_VALUE_OPTIONS = new Set(["-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-T", "-U"]);
248// Commands that only read, so a bare word "migrate" in them isn't a migration.
249const READ_ONLY = new Set(["ls", "cat", "echo", "printf", "grep", "rg", "find", "less", "head", "tail", "cd", "git"]);
250
251/** A folder a later `cd arg` moves to, given the folder so far (null = the session folder). */
252function joinDir(dir, arg) {
253 if (arg === undefined || arg === "~" || arg.startsWith("/") || arg.startsWith("~/")) {
254 return arg ?? "~";
255 }
256 return dir ? `${dir}/${arg}` : arg;
257}
258
259/** Splits a command line on && || ; | & and newlines, outside quotes. Each segment keeps its own text. */
260export function splitSegments(command) {
261 const out = [];
262 let cur = "";
263 let quote = null;
264 for (let i = 0; i < command.length; i += 1) {
265 const c = command[i];
266 if (quote) {
267 cur += c;
268 if (c === "\\" && quote === '"' && i + 1 < command.length) {
269 cur += command[i + 1];
270 i += 1;
271 } else if (c === quote) {
272 quote = null;
273 }
274 continue;
275 }
276 if (c === "'" || c === '"') {
277 quote = c;
278 cur += c;
279 } else if (c === "\\" && i + 1 < command.length) {
280 cur += c + command[i + 1];
281 i += 1;
282 } else if (c === ";" || c === "\n" || c === "|" || (c === "&" && command[i + 1] === "&")) {
283 out.push(cur);
284 cur = "";
285 if ((c === "|" && command[i + 1] === "|") || c === "&") {
286 i += 1;
287 }
288 } else {
289 cur += c;
290 }
291 }
292 out.push(cur);
293 return out;
294}
295
296/** The first risky segment of a shell command, or null. startDir: the folder an enclosing bash -c already moved to. */
297export function classify(command, startDir = null) {
298 let dir = startDir; // where a `cd` earlier on the line moved to; null means the session folder
299 const scopes = []; // dir to restore when a ( subshell ) closes
300 const pushed = []; // pushd stack, for popd
301 for (const raw of splitSegments(command)) {
302 const opens = (raw.match(/^\s*\(+/)?.[0].trim().length) ?? 0;
303 // Trailing redirects and & don't hide a closing ) : `(cd sub && make) > log`.
304 const tail = raw.replace(/(?:\s*(?:\d*>>?|&>>?|<)\s*\S+|\s*&)+\s*$/, "");
305 const closes = (tail.match(/\)+\s*$/)?.[0].trim().length) ?? 0;
306 for (let k = 0; k < opens; k += 1) {
307 scopes.push(dir);
308 }
309 const risk = classifySegment(raw, dir, pushed);
310 if (risk !== null && risk.cd === undefined) {
311 return risk;
312 }
313 if (risk !== null) {
314 dir = risk.cd; // a cd, pushd or popd moved the folder
315 }
316 for (let k = 0; k < closes && scopes.length > 0; k += 1) {
317 dir = scopes.pop(); // a cd inside ( ... ) doesn't outlive it
318 }
319 }
320 return null;
321}
322
323// Words that can come before the real command without changing what it does.
324const PREFIXES = new Set(["command", "exec", "env", "nohup", "time", "then", "do", "else", "!"]);
325
326/** One segment: a risk, { cd } for a folder change, or null. */
327function classifySegment(segment, dir, pushed) {
328 {
329 const words = tokenize(segment.trim().replace(/^[({]+\s*/, "").replace(/\s*[)}]+$/, ""));
330 while (words.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) {
331 words.shift(); // leading VAR=value
332 }
333 if (words[0] === "sudo") {
334 words.shift();
335 while (words.length > 0 && words[0].startsWith("-")) {
336 const option = words.shift();
337 if (SUDO_VALUE_OPTIONS.has(option)) {
338 words.shift();
339 }
340 }
341 }
342 while (words.length > 0 && (PREFIXES.has(words[0]) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0]))) {
343 words.shift();
344 }
345 if (words[0] === "nice") {
346 words.shift();
347 if (words[0] === "-n") {
348 words.splice(0, 2);
349 } else if (/^-\d+$/.test(words[0] ?? "")) {
350 words.shift();
351 }
352 }
353 const [first, ...args] = words;
354 if (first === undefined) {
355 return null;
356 }
357 const cmd = first.replace(/^\\/, ""); // \rm skips aliases; it's still rm
358 if (cmd === "cd") {
359 return { cd: args[0] === "-" ? "-" : joinDir(dir, args[0]) };
360 }
361 if (cmd === "pushd") {
362 pushed.push(dir);
363 return { cd: joinDir(dir, args[0]) };
364 }
365 if (cmd === "popd") {
366 return { cd: pushed.length > 0 ? pushed.pop() : "-" };
367 }
368 // bash -c '...' と eval '...' は中身を同じルールで調べる
369 if (SHELLS.has(cmd) || [...SHELLS].some((sh) => cmd.endsWith(`/${sh}`))) {
370 const c = args.findIndex((a) => /^-[A-Za-z]*c[A-Za-z]*$/.test(a));
371 return c !== -1 && args[c + 1] !== undefined ? classify(args[c + 1], dir) : null;
372 }
373 if (cmd === "eval") {
374 return args.length > 0 ? classify(args.join(" "), dir) : null;
375 }
376 if (cmd === "find") {
377 const found = parseFindDelete(args);
378 if (found !== null) {
379 return { kind: "find-delete", label: `find ${found.via}`, args: found.dryRun, isUnfiltered: found.isUnfiltered, dir };
380 }
381 return null;
382 }
383 if (cmd === "xargs") {
384 let k = 0;
385 while (k < args.length && args[k].startsWith("-")) {
386 k += XARGS_OPTS_WITH_VALUE.has(args[k]) ? 2 : 1;
387 }
388 if ((args[k] ?? "").split("/").pop() === "rm") {
389 return { kind: "xargs-rm", label: "xargs rm", dir };
390 }
391 return null;
392 }
393 if (cmd === "rm" || cmd.endsWith("/rm")) {
394 const flags = args.filter((a) => a.startsWith("-"));
395 const recursive = flags.some((f) => f === "--recursive" || (/^-[^-]/.test(f) && /[rR]/.test(f)));
396 const force = flags.some((f) => f === "--force" || (/^-[^-]/.test(f) && f.includes("f")));
397 if (recursive || force) {
398 const targets = args.filter((a) => !a.startsWith("-") || a === "-");
399 return { kind: "rm", label: `rm ${flags.join(" ")}`.trim(), targets, dir };
400 }
401 }
402 if (cmd === "git") {
403 // Git's own options come before the subcommand; -C moves where it runs.
404 let gitDir = dir;
405 let i = 0;
406 while (i < args.length && args[i].startsWith("-")) {
407 if (args[i] === "-C" && i + 1 < args.length) {
408 gitDir = joinDir(gitDir, args[i + 1]);
409 i += 2;
410 } else if (args[i] === "-c" && i + 1 < args.length) {
411 i += 2;
412 } else {
413 i += 1;
414 }
415 }
416 const sub = args[i];
417 const rest = args.slice(i + 1);
418 if (sub === "reset" && rest.includes("--hard")) {
419 return { kind: "git-reset", label: "git reset --hard", args: rest, dir: gitDir };
420 }
421 if (sub === "clean") {
422 return { kind: "git-clean", label: "git clean", args: rest, dir: gitDir };
423 }
424 if (sub === "push" && rest.some((a) => a === "--force" || a === "-f" || a.startsWith("--force-with-lease") || /^\+/.test(a))) {
425 return { kind: "git-push-force", label: "git push --force", args: rest, dir: gitDir };
426 }
427 const stagedOnly = sub === "restore" && rest.includes("--staged") && !rest.includes("--worktree") && !rest.includes("-W");
428 // checkout は . か -- のあとのパス、restore はパスがあれば作業ツリーの変更を捨てる
429 const dash = rest.indexOf("--");
430 const paths = dash !== -1 ? rest.slice(dash + 1) : rest.filter((a) => !a.startsWith("-"));
431 const discards = sub === "restore" ? paths.length > 0 : rest.includes(".") || (dash !== -1 && paths.length > 0);
432 if ((sub === "checkout" || sub === "restore") && discards && !stagedOnly) {
433 const label = paths.length === 1 && paths[0] === "." ? `git ${sub} -- .` : `git ${sub} -- ${paths.join(" ")}`;
434 return { kind: "git-checkout", label, args: rest, paths, dir: gitDir };
435 }
436 if (sub === "branch" && (rest.includes("-D") || (rest.includes("--delete") && rest.includes("--force")))) {
437 const branches = withoutRedirects(rest).filter((a) => !a.startsWith("-"));
438 if (branches.length > 0) {
439 return { kind: "git-branch-delete", label: `git branch -D ${branches.join(" ")}`, branches, dir: gitDir };
440 }
441 }
442 if (sub === "stash" && (rest[0] === "drop" || rest[0] === "clear")) {
443 return { kind: "git-stash", label: `git stash ${rest[0]}`, action: rest[0], ref: rest[1] ?? null, dir: gitDir };
444 }
445 }
446 const joined = words.join(" ");
447 if (/\balembic\s+upgrade\b/.test(joined)) {
448 return { kind: "migrate", tool: "alembic", label: "alembic upgrade", dir };
449 }
450 if (/\bdb:migrate(?!:status\b)/.test(joined)) {
451 return { kind: "migrate", tool: "rails", label: "db:migrate", dir };
452 }
453 if (/\bprisma\s+migrate\b/.test(joined)) {
454 return { kind: "migrate", tool: "prisma", label: "prisma migrate", dir };
455 }
456 if (/\bmanage\.py\s+migrate\b/.test(joined)) {
457 return { kind: "migrate", tool: "django", label: "manage.py migrate", dir };
458 }
459 if (!READ_ONLY.has(cmd) && args.includes("migrate")) {
460 return { kind: "migrate", tool: "unknown", label: "migrate", dir };
461 }
462 }
463 return null;
464}
465
466const EXEC_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
467// 引数を 1 つとる find のグローバルオプションと、引数なしのもの。ファイルに書き出す動作は下見では外す
468const FIND_GLOBAL_OPTS = new Set(["-maxdepth", "-mindepth"]);
469const FIND_GLOBAL_FLAGS = new Set(["-depth", "-d", "-xdev", "-mount", "-follow", "-noleaf"]);
470const FIND_WRITE_ACTIONS = new Set(["-fprint", "-fprint0", "-fls", "-fprintf"]);
471// xargs のオプションのうち、引数を 1 つとるもの
472const XARGS_OPTS_WITH_VALUE = new Set(["-n", "-I", "-L", "-P", "-d", "-s", "-E", "-a"]);
473
474/** find の引数から -delete / -exec rm を見つけ、消えるものを下見する引数を作る。削除しない find は null */
475export function parseFindDelete(args) {
476 const del = args.indexOf("-delete");
477 const execRm = args.findIndex((a, i) => EXEC_ACTIONS.has(a) && (args[i + 1] ?? "").split("/").pop() === "rm");
478 if (del === -1 && execRm === -1) {
479 return null;
480 }
481 const dryRun = [];
482 for (let k = 0; k < args.length; k += 1) {
483 const a = args[k];
484 if (a === "-delete") {
485 continue;
486 }
487 if (EXEC_ACTIONS.has(a)) {
488 while (k < args.length && args[k] !== ";" && args[k] !== "+") {
489 k += 1;
490 }
491 continue;
492 }
493 if (FIND_WRITE_ACTIONS.has(a)) {
494 k += a === "-fprintf" ? 2 : 1;
495 continue;
496 }
497 dryRun.push(a);
498 }
499 // -delete より前に絞り込みの条件がない(find . -delete -name x など)と、たどったものが全部消える
500 let isUnfiltered = false;
501 if (del !== -1) {
502 let k = args.findIndex((a) => a.startsWith("-") || a === "(" || a === "!");
503 isUnfiltered = true;
504 while (k !== -1 && k < del) {
505 if (FIND_GLOBAL_OPTS.has(args[k])) {
506 k += 2;
507 } else if (FIND_GLOBAL_FLAGS.has(args[k])) {
508 k += 1;
509 } else {
510 isUnfiltered = false;
511 break;
512 }
513 }
514 }
515 return { dryRun, isUnfiltered, via: del !== -1 ? "-delete" : "-exec rm" };
516}
517
518// Resolves a `cd` target to an absolute folder, or null if it doesn't exist.
519// The target is passed as an argument, never as source.
520const CD_SCRIPT = `unset CDPATH; d="$1"; case "$d" in "~") d="$HOME";; "~/"*) d="$HOME/\${d#\\~/}";; esac; cd -- "$d" 2>/dev/null && pwd -P`;
521
522async function resolveDir($, sessionCwd, dir) {
523 if (dir === "-") {
524 return null; // `cd -` depends on the shell's history
525 }
526 const run = await $.process.run(["bash", "-c", CD_SCRIPT, "blast-radius", dir], { cwd: sessionCwd, timeoutMs: 5000 });
527 const out = run.stdout.trim();
528 return run.exitCode === 0 && out !== "" ? out : null;
529}
530
531/** Words without redirects: `2>&1` and `>/dev/null` go, and so does the file after a bare `>`. */
532function withoutRedirects(words) {
533 const out = [];
534 for (let k = 0; k < words.length; k += 1) {
535 if (/^(\d*|&)(>>?|<)$/.test(words[k])) {
536 k += 1;
537 } else if (!/^(\d*|&)(>>?|<)/.test(words[k])) {
538 out.push(words[k]);
539 }
540 }
541 return out;
542}
543
544/** Splits one segment into words, honouring quotes. Good enough to read flags and paths. */
545function tokenize(text) {
546 const words = [];
547 const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g;
548 let m;
549 while ((m = re.exec(text)) !== null) {
550 words.push(m[1] ?? m[2] ?? m[3]);
551 }
552 return words;
553}
554
555// ---- Measuring the blast radius -------------------------------------------
556
557/** { summary, lines, note } for the pane. Never throws: a failed read is said, not hidden. */
558async function measure($, risk, cwd) {
559 try {
560 if (risk.kind === "rm") {
561 return await measureRm($, risk, cwd);
562 }
563 if (risk.kind === "migrate") {
564 return await measureMigrations($, risk, cwd);
565 }
566 if (risk.kind === "find-delete") {
567 return await measureFind($, risk, cwd);
568 }
569 if (risk.kind === "xargs-rm") {
570 return { summary: "delete the files piped into it", lines: [], note: "xargs gets its file list when the command runs, so I can't list them beforehand." };
571 }
572 return await measureGit($, risk, cwd);
573 } catch (error) {
574 return { summary: `${risk.label} (could not measure it)`, lines: [], note: `Could not measure: ${String(error?.message ?? error).slice(0, 200)}` };
575 }
576}
577
578// The paths are passed to bash as arguments, never as source, so nothing in
579// them runs. compgen -G expands a glob without command substitution.
580const RM_SCRIPT = `
581shopt -s nullglob dotglob
582paths=()
583for p in "$@"; do
584 case "$p" in "~"|"~/"*) p="$HOME\${p#\\~}";; esac
585 if [[ "$p" == *[*?[]* ]]; then
586 while IFS= read -r m; do paths+=("$m"); done < <(compgen -G "$p")
587 elif [[ -e "$p" || -L "$p" ]]; then
588 paths+=("$p")
589 fi
590done
591if (( \${#paths[@]} == 0 )); then echo "0 0 0"; exit 0; fi
592# A relative path gets ./ in front, so find never reads a name like -delete as an action.
593for i in "\${!paths[@]}"; do case "\${paths[$i]}" in /*) ;; *) paths[$i]="./\${paths[$i]}";; esac; done
594files=$(find "\${paths[@]}" \\( -type f -o -type l \\) 2>/dev/null | wc -l | tr -d ' ')
595kb=$(du -skc "\${paths[@]}" 2>/dev/null | tail -n1 | cut -f1)
596echo "$files $(( \${kb:-0} * 1024 )) \${#paths[@]}"
597find "\${paths[@]}" \\( -type f -o -type l \\) 2>/dev/null | head -n ${LIST_MAX}
598`;
599
600const WHOLE_TREES = new Set(["/", "/*", "~", "~/", "~/*", ".", "./", "./*", "..", "../", "*"]);
601
602async function measureRm($, risk, cwd) {
603 const report = await measureRmPaths($, risk, cwd);
604 const warnings = [];
605 const variables = risk.targets.filter((t) => /[$`]/.test(t));
606 if (variables.length > 0) {
607 warnings.push(`${variables.join(" ")} ${variables.length === 1 ? "is a variable" : "are variables"}: what ${variables.length === 1 ? "it holds" : "they hold"} is only known when the command runs, so ${variables.length === 1 ? "it isn't" : "they aren't"} counted.`);
608 }
609 const wide = risk.targets.filter((t) => WHOLE_TREES.has(t));
610 if (wide.length > 0) {
611 warnings.push(`⚠ ${wide.join(" ")} is a whole folder tree.`);
612 }
613 if (warnings.length === 0) {
614 return report;
615 }
616 return { ...report, note: [...warnings, report.note].filter(Boolean).join(" ") };
617}
618
619async function measureRmPaths($, risk, cwd) {
620 if (risk.targets.length === 0) {
621 return { summary: "rm with no paths", lines: [], note: "No paths to expand." };
622 }
623 const run = await $.process.run(["bash", "-c", RM_SCRIPT, "blast-radius", ...risk.targets], { cwd, timeoutMs: 15000 });
624 const [head, ...rest] = run.stdout.split("\n").filter((l) => l !== "");
625 const [files, bytes, found] = (head ?? "0 0 0").split(" ").map(Number);
626 if (!found) {
627 return { summary: `delete nothing: no file matches ${risk.targets.join(" ")}`, lines: [], note: "The paths don't exist, so rm has nothing to remove." };
628 }
629 if (!files) {
630 return { summary: `delete ${found} ${found === 1 ? "path" : "paths"} with no files in ${found === 1 ? "it" : "them"}`, lines: [], note: `Paths: ${risk.targets.join(" ")}` };
631 }
632 return {
633 summary: `delete ${files} ${files === 1 ? "file" : "files"} (about ${size(bytes)})`,
634 lines: rest.map((l) => l.replace(/^\.\//, "")),
635 more: Math.max(0, files - rest.length),
636 note: `Paths: ${risk.targets.join(" ")}`,
637 };
638}
639
640async function measureGit($, risk, cwd) {
641 if (risk.kind === "git-push-force") {
642 return await measurePush($, risk, cwd);
643 }
644 if (risk.kind === "git-branch-delete") {
645 // git cherry は patch で比べるので、rebase マージで SHA が変わったコミットも「HEAD にある」と数える
646 const lines = [];
647 let total = 0;
648 let isReadable = true;
649 for (const branch of risk.branches) {
650 const cherry = await $.process.run(["git", "cherry", "-v", "HEAD", branch], { cwd, timeoutMs: 15000 });
651 if (cherry.exitCode !== 0) {
652 isReadable = false;
653 lines.push(`${branch}: no such branch`);
654 continue;
655 }
656 const rows = cherry.stdout.split("\n").filter((l) => l !== "");
657 const missing = rows.filter((l) => l.startsWith("+")).map((l) => l.slice(2).replace(/^([0-9a-f]{7})[0-9a-f]+/, "$1"));
658 total += missing.length;
659 lines.push(`${branch}: ${missing.length === 0 ? "every commit is in HEAD" : `${missing.length} ${missing.length === 1 ? "commit" : "commits"} not in HEAD`}`);
660 lines.push(...missing.slice(0, LIST_MAX).map((c) => ` ${c}`));
661 }
662 return {
663 summary: total === 0 ? "delete branches whose commits are all in HEAD" : `delete ${total} ${total === 1 ? "commit that is" : "commits that are"} not in HEAD`,
664 lines: lines.slice(0, LIST_MAX),
665 more: Math.max(0, lines.length - LIST_MAX),
666 note: "From git cherry HEAD branch, which counts a rebased commit as in HEAD. Commits not in HEAD can be hard to find again once the branch is gone.",
667 isHarmless: total === 0 && isReadable,
668 };
669 }
670 if (risk.kind === "git-stash") {
671 const list = await $.process.run(["git", "stash", "list"], { cwd, timeoutMs: 15000 });
672 const all = list.stdout.split("\n").filter((l) => l !== "");
673 const gone = risk.action === "clear" ? all : all.filter((l) => l.startsWith(`${risk.ref ?? "stash@{0}"}:`));
674 return {
675 summary: gone.length === 0 ? "drop no stash entries" : `drop ${gone.length} stash ${gone.length === 1 ? "entry" : "entries"}`,
676 lines: gone.slice(0, LIST_MAX),
677 more: Math.max(0, gone.length - LIST_MAX),
678 note: "From git stash list. A dropped stash is hard to get back.",
679 };
680 }
681 if (risk.kind === "git-clean") {
682 const flags = [];
683 const paths = [];
684 for (let i = 0; i < risk.args.length; i += 1) {
685 const a = risk.args[i];
686 if (a === "--") {
687 paths.push(...risk.args.slice(i + 1));
688 break;
689 }
690 if (a === "-e" || a === "--exclude") {
691 flags.push(a, risk.args[i + 1] ?? "");
692 i += 1;
693 } else if (a.startsWith("--exclude=") || /^-e./.test(a)) {
694 flags.push(a);
695 } else if (/^-[a-zA-Z]+$/.test(a)) {
696 const kept = a.replace(/[finq]/g, ""); // -n is added below; -f, -i and -q would change the dry run
697 if (kept !== "-") {
698 flags.push(kept);
699 }
700 } else if (!a.startsWith("-")) {
701 paths.push(a);
702 }
703 }
704 const run = await $.process.run(["git", "clean", "-n", ...flags, "--", ...paths], { cwd, timeoutMs: 15000 });
705 if (run.exitCode !== 0) {
706 return { summary: "git clean (could not dry-run it)", lines: [], note: run.stderr.trim().slice(0, 200) };
707 }
708 const gone = run.stdout.split("\n").filter((l) => l.startsWith("Would remove ")).map((l) => l.slice(13));
709 return {
710 summary: gone.length === 0 ? "remove nothing: no untracked files match" : `remove ${gone.length} untracked ${gone.length === 1 ? "path" : "paths"}`,
711 lines: gone.slice(0, LIST_MAX),
712 more: Math.max(0, gone.length - LIST_MAX),
713 note: "From git clean -n. Untracked files are not in git, so they can't be recovered.",
714 };
715 }
716 const scope = risk.kind === "git-checkout" && risk.paths?.length ? ["--", ...risk.paths] : [];
717 const status = await $.process.run(["git", "status", "--porcelain", ...scope], { cwd, timeoutMs: 15000 });
718 if (status.exitCode !== 0) {
719 return { summary: `${risk.label} (not a git repo here?)`, lines: [], note: status.stderr.trim().slice(0, 200) };
720 }
721 const rows = status.stdout.split("\n").filter((l) => l.length > 3 && !l.startsWith("??"));
722 // reset --hard drops staged and unstaged changes; checkout -- . drops unstaged ones.
723 const lost = risk.kind === "git-reset" ? rows : rows.filter((l) => l[1] !== " ");
724 const stat = await $.process.run(["git", "diff", "--shortstat", risk.kind === "git-reset" ? "HEAD" : "--"], { cwd, timeoutMs: 15000 });
725 return {
726 summary: lost.length === 0 ? "discard nothing: no uncommitted changes" : `discard uncommitted changes in ${lost.length} ${lost.length === 1 ? "file" : "files"}`,
727 lines: lost.slice(0, LIST_MAX).map((l) => `${l.slice(0, 2)} ${l.slice(3)}`),
728 more: Math.max(0, lost.length - LIST_MAX),
729 note: stat.stdout.trim() !== "" ? `${stat.stdout.trim()}. Uncommitted changes can't be recovered.` : "From git status --porcelain.",
730 };
731}
732
733// 削除の動作を外した find を、引数のまま(シェルを通さずに)実行して一覧にする
734async function measureFind($, risk, cwd) {
735 const run = await $.process.run(["find", ...risk.args], { cwd, timeoutMs: 15000 });
736 const found = run.stdout.split("\n").filter((l) => l !== "").map((l) => l.replace(/^\.\//, ""));
737 const note = risk.isUnfiltered
738 ? "⚠ -delete comes before any test, so everything find walks is deleted. From the same find without -delete."
739 : "From the same find without -delete or -exec rm.";
740 return {
741 summary: found.length === 0 ? "delete nothing: find matches no files" : `delete ${found.length} ${found.length === 1 ? "path" : "paths"}`,
742 lines: found.slice(0, LIST_MAX),
743 more: Math.max(0, found.length - LIST_MAX),
744 note,
745 };
746}
747
748async function measurePush($, risk, cwd) {
749 const positional = risk.args.filter((a) => !a.startsWith("-"));
750 const remote = positional[0] ?? "origin";
751 // A refspec is src:dst. With no colon, the local branch of the same name is pushed.
752 const spec = (positional[1] ?? "").replace(/^\+/, "");
753 let [source, branch] = spec.includes(":") ? spec.split(":") : [spec, spec];
754 branch = (branch ?? "").replace(/^refs\/heads\//, "");
755 if (!branch) {
756 const head = await $.process.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeoutMs: 10000 });
757 branch = head.stdout.trim();
758 source = "HEAD";
759 } else if (branch === "HEAD") {
760 // `git push origin HEAD` pushes the current branch to its namesake.
761 const head = await $.process.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeoutMs: 10000 });
762 branch = head.stdout.trim();
763 source = "HEAD";
764 }
765 source = source || "HEAD";
766 const ref = `${remote}/${branch}`;
767 const known = await $.process.run(["git", "rev-parse", "--verify", "--quiet", ref], { cwd, timeoutMs: 10000 });
768 if (known.exitCode !== 0) {
769 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.` };
770 }
771 const log = await $.process.run(["git", "log", "--oneline", "--no-decorate", `${source}..${ref}`], { cwd, timeoutMs: 15000 });
772 const dropped = log.stdout.split("\n").filter((l) => l !== "");
773 return {
774 summary: dropped.length === 0 ? `force-push to ${ref}: drops no commits` : `force-push to ${ref}: drops ${dropped.length} ${dropped.length === 1 ? "commit" : "commits"}`,
775 lines: dropped.slice(0, LIST_MAX),
776 more: Math.max(0, dropped.length - LIST_MAX),
777 note: `Commits on ${ref} that ${source} doesn't have, as of the last fetch.`,
778 };
779}
780
781const MIGRATION_LISTERS = {
782 django: { argv: ["python3", "manage.py", "showmigrations", "--plan"], pending: (l) => l.startsWith("[ ]"), strip: (l) => l.slice(4) },
783 alembic: { argv: ["alembic", "history", "-r", "current:head"], pending: (l) => l.includes("->"), strip: (l) => l },
784 rails: { argv: ["bin/rails", "db:migrate:status"], pending: (l) => /^\s*down\b/.test(l), strip: (l) => l.trim() },
785 prisma: { argv: ["npx", "--no-install", "prisma", "migrate", "status"], pending: (l) => /^\s{2}\S/.test(l), strip: (l) => l.trim() },
786};
787
788async function measureMigrations($, risk, cwd) {
789 const lister = MIGRATION_LISTERS[risk.tool];
790 if (lister === undefined) {
791 return { summary: "run migrations", lines: [], note: "I can't list the pending migrations for this tool, so the list is not shown." };
792 }
793 let run;
794 try {
795 run = await $.process.run(lister.argv, { cwd, timeoutMs: 20000 });
796 } catch (error) {
797 run = { exitCode: -1, stdout: "", stderr: String(error?.message ?? error) };
798 }
799 if (run.exitCode !== 0) {
800 return { summary: `run ${risk.label}`, lines: [], note: `Couldn't list pending migrations (${lister.argv.join(" ")} failed).` };
801 }
802 const pending = run.stdout.split("\n").filter(lister.pending).map(lister.strip);
803 return {
804 summary: pending.length === 0 ? `run ${risk.label}: nothing pending` : `apply ${pending.length} pending ${pending.length === 1 ? "migration" : "migrations"}`,
805 lines: pending.slice(0, LIST_MAX),
806 more: Math.max(0, pending.length - LIST_MAX),
807 note: `From ${lister.argv.join(" ")}.`,
808 };
809}
810
811function size(bytes) {
812 if (!Number.isFinite(bytes) || bytes < 1024) {
813 return `${bytes || 0} B`;
814 }
815 const units = ["KB", "MB", "GB", "TB"];
816 let n = bytes;
817 let i = -1;
818 while (n >= 1024 && i < units.length - 1) {
819 n /= 1024;
820 i += 1;
821 }
822 return `${n.toFixed(n < 10 ? 1 : 0)} ${units[i]}`;
823}
824
825// ---- Drawing --------------------------------------------------------------
826
827function paneRows(report) {
828 return Math.min(24, 9 + report.lines.length + (report.more ? 1 : 0));
829}
830
831function draw(t, state) {
832 const { Box, Text, Button } = t;
833 const { report } = state;
834 const list = report.lines.map((line, i) => Text({ key: `l${i}`, children: ` ${line}`, wrap: "truncate-end" }));
835 if (report.more) {
836 list.push(Text({ key: "more", dimColor: true, children: ` + ${report.more} more` }));
837 }
838 // The buttons answer the call this pane was drawn for, never whichever one is held now.
839 const decide = (choice) => () => {
840 if (state.decision === null) {
841 state.decision = choice;
842 }
843 };
844 return Box({
845 flexDirection: "column",
846 borderStyle: "round",
847 borderColor: "yellow",
848 paddingX: 1,
849 children: [
850 Text({ key: "title", bold: true, color: "yellow", children: `⚠ Blast Radius · ${state.risk.label}` }),
851 Text({ key: "cmd", children: [Text({ dimColor: true, children: "Command " }), Text({ bold: true, children: state.command })], wrap: "truncate-end" }),
852 Text({ key: "sum", children: [Text({ dimColor: true, children: "Would " }), Text({ color: "red", bold: true, children: report.summary })] }),
853 Box({ key: "list", flexDirection: "column", marginTop: 1, children: list }),
854 report.note ? Text({ key: "note", dimColor: true, italic: true, children: report.note, wrap: "wrap" }) : null,
855 Box({
856 key: "buttons",
857 marginTop: 1,
858 gap: 2,
859 children: [
860 Button({ key: "proceed", label: "Proceed", hotkey: "1", plain: true, onPress: decide("proceed") }),
861 Button({ key: "cancel", label: "Cancel", hotkey: "2", plain: true, autoFocus: true, onPress: decide("cancel") }),
862 Text({ key: "hint", dimColor: true, children: "Claude is waiting on your answer" }),
863 ],
864 }),
865 ],
866 });
867}
868