delete-guard-agent 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xinghe-labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ # blast-radius-guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/xinghe-labs/blast-radius-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/xinghe-labs/blast-radius-guard/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
+ [![hosts: ubuntu + windows + macos](https://img.shields.io/badge/tested%20on-ubuntu%20%7C%20windows%20%7C%20macos-blue)](.github/workflows/ci.yml)
6
+
7
+ **在破坏性命令执行之前,判定它在 Windows / Linux / macOS 上的真实爆炸半径。**
8
+
9
+ ![demo](docs/demo.svg)
10
+
11
+ 一个 [Agent Skill](https://agentskills.io):任何 agent(Claude Code / Codex / Cursor / pi)在跑 `rm -rf`、`rd /s /q`、`Remove-Item -Recurse -Force`、`sudo rm` 之前,先过一遍判定器,拿到 `allow / warn / block` 和带事故编号的理由。已经在真实 pi 会话里完成过端到端验证:模型发出的删除命令被扩展拦截,改写建议原样回到模型。
12
+
13
+ ## 调用方式:三层
14
+
15
+ **③ 硬拦截(推荐,装完就和)**
16
+
17
+ - pi:安装本包后,`src/extension.ts` 拦截所有 bash/powershell 删除命令,block 级在执行前拒绝,改写建议直接回给模型
18
+ - Claude Code:`hooks/pretooluse.py` 挂进 `PreToolUse`,exit 2 硬拦截
19
+ - fail-open 设计:判定器缺失/超时一律放行——安全工具因为误拦被用户禁用,比偶尔漏拦更糟
20
+
21
+ **② 软自动(装 skill 即得)**
22
+
23
+ agent 读到 SKILL.md 的 description 后,删除前自觉跑判定器。对携带 hook 机制的宿主,这只是后备。
24
+
25
+ **① 手动 CLI**
26
+
27
+ ```bash
28
+ python scripts/guard.py command 'rd /s /q "D:\★有些目录 with space"'
29
+ python scripts/guard.py command 'sudo rm -rf /usr'
30
+ python scripts/guard.py path "D:/old-outputs"
31
+ python scripts/guard.py command "rm -rf /mnt/d/data" --json
32
+ ```
33
+
34
+ 退出码:`0` = allow,`1` = warn(需人工确认),`2` = block(拒绝执行)。
35
+
36
+ `path` 模式只做**静态路径判定**(卷根 / 系统前缀 / 挂载点 / 大小写碰撞 / 链接计数),
37
+ 没有命令语境,因此 H8(递归+通配符)、H9(永久删除)、H10(提权)不适用——
38
+ 它们只能从命令文本推断。要完整判定请用 `command` 模式。
39
+
40
+ ## 为什么是这个方向
41
+
42
+ AI agent 静默销毁用户数据的公开事故记录已经成了一类,横跨三大平台:
43
+
44
+ | 事故 | 平台 | 根因 | 造成的损失 |
45
+ |---|---|---|---|
46
+ | [claude-code#56603](https://github.com/anthropics/claude-code/issues/56603) | Windows | PowerShell→cmd 引号链断裂,路径含 Unicode+空格 | 整个 worktree 目录被清空 |
47
+ | [cursor 论坛](https://forum.cursor.com/t/severe-data-loss-agents-mis-quoted-rmdir-command-recursively-deleted-my-entire-c-drive-had-to-reinstall-windows/163626) | Windows | `rmdir /s /q` 引号退化成 `rmdir /s /q C:\` | **整盘 C:\ 被删除,重装系统** |
48
+ | [cursor 论坛](https://forum.cursor.com/t/agent-autonomous-rd-s-q-wiped-the-entire-d-drive-windows/174156.md) | Windows | 引号解析错误,`rd /s /q` 落到盘根 | 微信记录+源码+应用全毁 |
49
+ | [claude-code#60442](https://github.com/anthropics/claude-code/issues/60442) | Windows | NTFS 大小写不敏感,`rm -rf "D:\CampusconnECT"` 解析到真实目录 | **9 个生产代码库被毁** |
50
+ | [claude-code#68343](https://github.com/anthropics/claude-code/issues/68343) | Windows | CJK 路径经 PowerShell/WSL2 静默返回空输出 | agent 误判"文件不存在",基于错误前提行动 |
51
+ | Claude Code v2.1.205 官方修复 | Windows | 删 worktree 穿透嵌套 NTFS junction,删到树外 | (官方 changelog 承认的 bug 类) |
52
+ | [codex#14487](https://github.com/openai/codex/issues/14487) | Windows | 默认权限下自主删除 D:\Photo,持续两天 | ~30MB×N 照片不可恢复 |
53
+ | Steam 2015 | Linux | `rm -rf "$STEAMROOT/"*` 变量为空退化成 `rm -rf /*` | **大量用户整盘 /usr 被删** |
54
+ | rsync 邮件列表 / 博客多人复述 | Linux | `rsync --delete` 作用于挂载点,误清备份卷 | 备份卷整卷数据消失 |
55
+ | macrumors#1176135 | macOS | `sudo rm -R / .Spotlight-v100` 多打一个空格 | 系统文件被删 |
56
+ | superuser#1925324 / macrumors#1192684 | macOS | 删 ~/Downloads / 家目录特殊目录 | iCloud/Time Machine/邮件数据链路损坏 |
57
+ | PocketOS / Railway([AID-2026-0106](https://mcscope.github.io/Alignment-Incident-Database/incidents/AID-2026-0106/)、[The Guardian](https://www.theguardian.com/technology/2026/apr/29/claude-ai-deletes-firm-database)) | 云 | agent 删 Railway volume | **9 秒清掉生产库+全部备份**,停机 30 小时 |
58
+ | [claude-code#27063](https://github.com/anthropics/claude-code/issues/27063) | 云 | `drizzle-kit push --force` 清生产 PostgreSQL | 60+ 表全清,不可恢复 |
59
+ | DataTalks.Club([Tom's Hardware](https://www.tomshardware.com/tech-industry/artificial-intelligence/claude-code-deletes-developers-production-setup-including-its-database-and-snapshots-2-5-years-of-records-were-nuked-in-an-instant)) | 云 | Claude Code 跑 `terraform destroy` | **2.5 年生产设施+快照全毁** |
60
+ | [claude-code#26913](https://github.com/anthropics/claude-code/issues/26913) | 云 | `alembic downgrade base` 清库 | 21 张表全清 |
61
+ | [claude-code#41357](https://github.com/anthropics/claude-code/issues/41357) | 容器 | `docker system prune -af --volumes` | 多个无关客户项目的镜像与卷被删 |
62
+ | [claude-code#14944](https://github.com/anthropics/claude-code/issues/14944) | 容器 | agent 自主 `docker volume rm` | 本地 Supabase 数据全丢 |
63
+ | [V2EX#1233011](https://www.v2ex.com/t/1233011) | Windows | Codex `wsl.exe bash -lc` 跨层删除 | C/D 盘两三百 GB、上百万文件 |
64
+ | [V2EX#1238217](https://www.v2ex.com/t/1238217) | Linux | GLM agent 删上上级目录 | 8 亿 token 的工作成果丢失 |
65
+ | [Replit Agent](https://www.theguardian.com/technology/2025/jul/18/replit-ai-agent-coding-deleted-production-database)(2025-07) | 云 | code freeze 期间删生产数据库 | SaaStr 创始人应用数据全丢,agent 称无法回滚 |
66
+ | [Claude Cowork](https://www.anthropic.com/news)(2026-02,Agent Incident Ledger) | macOS | "tidy desktop" 时 `rm -rf` 误判空目录 | **15 年家庭照片**被删 |
67
+ | [Gemini CLI](https://www.manifold.security/incidents)(2025-07,Agent Incident Ledger) | Linux | mkdir 失败后继续 `mv` 级联覆盖 | 用户文件被逐个覆盖至剩一个 |
68
+
69
+ 共同点:**这些命令文本在写作者的直觉里全都是"安全"的**。0.1 只覆盖 Windows;
70
+ 0.2 起同一条判定流水线也认得出 Linux 与 macOS 的失败路径;0.3 把
71
+ `find -delete` 与 git 子命令(clean / worktree remove)纳入判定;0.4 补上
72
+ 最大的空白——云/容器/ORM 工具的破坏性动词(H14)。
73
+
74
+ ## 项目原则
75
+
76
+ 1. **不可解析即拒绝。** 引号链断裂不是边界情况,它是事故本体。
77
+ 2. **无法验证就声明 unknown,不默认安全。** WSL 里看不到 NTFS reparse 属性,就说看不到。
78
+ 3. **每条规则对应一个已归档的公开事故。** 没有编号的规则不进代码。
79
+
80
+ ## 安装
81
+
82
+ ```bash
83
+ # agent skill(推荐,Claude Code / pi / Codex 通用)
84
+ npx skills add xinghe-labs/blast-radius-guard
85
+
86
+ # npm 包(npm 上的包名:delete-guard-agent)
87
+ npm install -g delete-guard-agent
88
+ python $(npm root -g)/delete-guard-agent/scripts/guard.py command "rm -rf /tmp/x"
89
+ ```
90
+
91
+ > npm 包名与本仓库不同名:`blast-radius-guard` 在 npm 上被相似名规则拦截
92
+ > (已有 `blastradius-guard`),故 npm 端使用 `delete-guard-agent`。GitHub /
93
+ > skill 安装 / 文档中的项目名统一为 blast-radius-guard。
94
+
95
+ 或克隆到任意 agent 的 skill 目录:
96
+
97
+ ```bash
98
+ git clone --depth 1 https://github.com/xinghe-labs/blast-radius-guard.git ~/.agents/skills/blast-radius-guard
99
+ ```
100
+
101
+ 零依赖,只要 Python 3.10+。
102
+
103
+ ## 直接使用(不经 agent)
104
+
105
+ ```bash
106
+ # 判定一条命令
107
+ python scripts/guard.py command 'rd /s /q "D:\★有些目录 with space"'
108
+ python scripts/guard.py command 'sudo rm -rf /etc'
109
+
110
+ # 判定一个路径
111
+ python scripts/guard.py path "/mnt/d/old-outputs"
112
+
113
+ # 机器可读输出
114
+ python scripts/guard.py command "rm -rf /mnt/d/data" --json
115
+ ```
116
+
117
+ 退出码:`0` = allow,`1` = warn(需人工确认),`2` = block(拒绝执行)。
118
+
119
+ ## 判定的危险(每条对应真实事故)
120
+
121
+ | 编号 | 危险 | 平台 | 级别 |
122
+ |---|---|---|---|
123
+ | H0 | 命令文本无法无歧义解析(引号未闭合、层间转义) | 全平台 | block |
124
+ | H1 | 跨 shell 引号链(cmd /c、powershell -Command)+ 空格/CJK 路径 | Windows | block |
125
+ | H2 | 目标是卷根(`D:\`、`/`、`/mnt/d`) | 全平台 | block |
126
+ | H3 | 路径大小写与磁盘实际不一致(NTFS/APFS 不敏感) | Win + macOS | block |
127
+ | H4 | 子树含 junction/符号链接,递归会穿透 | 全平台 | block |
128
+ | H5 | CJK 路径可能静默空输出(事故依据为 Windows;判定全平台保守触发) | Windows | warn |
129
+ | H6 | 目标在 `/mnt/` 下且处于 WSL 语境(跨文件系统语义) | WSL | warn |
130
+ | H7 | 目标是当前工作目录的祖先 | 全平台 | block |
131
+ | H8 | 递归+通配符(半径取决于运行时目录内容) | 全平台 | warn |
132
+ | H9 | 永久删除(不进回收站/废纸篓) | 全平台 | warn |
133
+ | H10 | sudo/doas 提权删除(root 绕过一切保护) | Linux/macOS | block |
134
+ | H11 | 目标是系统关键前缀(/usr /etc /bin /home…) | Linux | block |
135
+ | H12 | 目标是挂载点(删除作用于整个卷) | Linux/macOS | block |
136
+ | H13 | 目标是 macOS 家目录特殊目录(Documents/Library…) | macOS | block |
137
+ | H14 | 云/容器/ORM 工具破坏性动词(terraform destroy、prisma migrate reset、docker 卷删除、kubectl delete namespace、SQL DROP) | 全平台 | warn/block |
138
+
139
+ ## 代码结构(0.2 起拆包;0.3 起 find/git 意图在 core.py 内原生解析)
140
+
141
+ ```
142
+ scripts/
143
+ ├── guard.py # 兼容 shim:python guard.py ... 与旧 API 不变
144
+ └── delete_guard/ # 判定引擎包
145
+ ├── core.py # 分词、意图提取、磁盘核验、判定引擎
146
+ ├── paths.py # 路径形态/词表助手(纯函数)
147
+ ├── platform.py # 宿主探测(windows/linux/macos/WSL)、unknown 声明
148
+ ├── cli.py # command / path CLI,退出码 0/1/2
149
+ └── rules/
150
+ ├── common.py # H0/H1/H7/H8/H9/H10 跨平台规则
151
+ ├── windows.py # H2–H6 Windows 专属
152
+ ├── linux.py # H11/H12 Linux 专属
153
+ └── macos.py # H13 macOS 专属
154
+ ```
155
+
156
+ ## 测试
157
+
158
+ ```bash
159
+ python -m unittest discover tests -v
160
+ ```
161
+
162
+ 用例覆盖:tokenize / intent / path→hazard / 真实事故回归(Windows + Linux)/
163
+ 防"过度拦截"反例(普通 `rm -rf ./build` 不该 block)。
164
+
165
+ ## 真机边界(诚实清单)
166
+
167
+ 以下项已由 CI 的 `ubuntu-latest` / `windows-latest` / `macos-latest` runner
168
+ 或真机 E2E 覆盖:
169
+
170
+ - [x] 单元测试(101 个,含 H3/H4/H11-H14/find/git 断言、中文社区事故回归与过度拦截反例)在
171
+ ubuntu + windows + macos 三个 runner 上跑
172
+ - [x] macOS 真机回归(H3 APFS 大小写、H13 家目录特殊目录)——由
173
+ `macos-latest` runner 真机执行,不再是仅静态判定
174
+ - [x] pi 扩展端到端:加载 → tool_call 拦截 → block 理由回传模型(-e + 真实会话)
175
+ - [x] PreToolUse hook stdin 协议(多场景)
176
+ - [x] H12 挂载点判定在真实 WSL 真机上验证(/mnt/d)
177
+ - [x] CI actions 全部固定到 commit SHA(zizmor 审计无阻塞项)
178
+
179
+ 仍未覆盖、需要真实使用才能验证的:
180
+
181
+ - 判定器的迷你解析器与真实 cmd/PowerShell/zsh 解析在诡异转义交界处的分歧
182
+ (策略是 fail-safe:看不懂就 block,代价是可能拦住安全的怪命令)——需真实使用逐步调优
183
+ - 误报/漏报率:0 真实用户,规则集未经实战
184
+ - macOS 宿主上的 pi 扩展 / Claude Code hook 实机加载(CI 只覆盖了判定器与测试;
185
+ 扩展层的 Python 探测在 darwin 上未跑过端到端)
186
+ - Codex 无 hook 机制,只有 skill 层(宿主限制)
187
+ - MCP 工具调用与"agent 写脚本再执行"的间接删除(2026-09 的 48k 文件事故
188
+ 形态)原理上不在 shell 判定范围内 —— 防御依赖宿主 permission 配置与
189
+ 使用纪律,见 SKILL.md「判定器的原理边界」
190
+
191
+ ## 反馈误报 / 漏报
192
+
193
+ 规则集未经实战,你的真实使用是最有价值的数据源。遇到以下情况请开
194
+ [误报/漏报 issue](https://github.com/xinghe-labs/blast-radius-guard/issues/new?template=false-positive.yml):
195
+
196
+ - **误报**:安全的命令被 block(比如正常的清理脚本被拦)
197
+ - **漏报**:危险的命令被 allow/warn
198
+
199
+ 模板会引导你贴出命令原文、OS 和 `--json` 判定输出——这是调规则需要的全部信息。
200
+ 每个被确认的规则问题都会在 CHANGELOG 里带事故编号修复,就像已有的 15 条一样。
201
+
202
+ ## License
203
+
204
+ MIT
205
+
206
+ ---
207
+
208
+ 本项目积极参与并认可 [LINUX DO 社区](https://linux.do)
package/SKILL.md ADDED
@@ -0,0 +1,143 @@
1
+ ---
2
+ name: blast-radius-guard
3
+ description: Use before running ANY destructive file operation (rm -rf, rd /s /q, rmdir /s, Remove-Item -Recurse -Force, del, sudo rm, deleting /usr /etc or any system prefix, deleting a mount point, terraform destroy, prisma migrate reset, drizzle-kit push --force, alembic downgrade base, docker volume rm, docker compose down -v, docker system prune --volumes, kubectl delete namespace, psql DROP TABLE/TRUNCATE, mv across filesystems) on Windows, Linux, macOS, or WSL, or paths that contain spaces, CJK characters, quotes, drive letters, or /mnt mounts. Also use when the agent itself is about to delete a directory it did not create, when cleaning up before rewriting deliverables, or when a user asks to "清理/删除/清空" anything. Judges the true blast radius, catches NTFS/APFS junction and symlink traversal, case-insensitive path collisions, quote-chain degradation, sudo-escalated deletes, system-prefix wipes, mount-point deletions, and CJK silent failures - the platform-specific data-loss paths that POSIX safety habits do not cover. Converts permanent deletes into quarantine renames. Do not use for files inside a normal git worktree cleanup that the agent just created itself in a single-layer POSIX shell on ext4.
4
+ ---
5
+
6
+ # Blast Radius Guard
7
+
8
+ 你可以删错一个文件,但你不该删错一整个卷。这个 skill 存在的原因不是"删除危险",
9
+ 而是**删除命令的真实语义和 agent 写出来的命令文本经常不是一回事**。
10
+ 每一条规则下面都埋着一次真实的数据销毁事故。适用于 Windows、Linux、macOS 与 WSL。
11
+
12
+ ## 它怎么被调用(三层)
13
+
14
+ | 层 | 机制 | 可靠性 |
15
+ |---|---|---|
16
+ | ① 手动 CLI | 直接跑 `scripts/guard.py command ...` | 100%,但要自己记得 |
17
+ | ② 本 skill | agent 读到本文件后,删除前自觉跑判定器 | 高,但依赖模型自觉 |
18
+ | ③ 硬拦截 | 宿主 hook / 扩展在命令**执行前**强制判定 | **100%,不依赖自觉(推荐)** |
19
+
20
+ 安装硬拦截层:
21
+
22
+ - **pi**:把本仓库目录加入 pi 的 extensions(`package.json` 已含 `pi.extensions` 指向 `src/extension.ts`),扩展自动拦截 bash/powershell 删除命令,block 级直接拒绝并把改写建议回给模型
23
+ - **Claude Code**:把 `hooks/pretooluse.py` 挂进 `PreToolUse`(见该文件头部注释)
24
+ - **Codex**:无 hook 机制,只有 ② 层
25
+
26
+ ## 铁律(先于一切分析)
27
+
28
+ 1. **不把计算出的路径管道进 `cmd /c`。** 用 PowerShell 原生命令做文件操作
29
+ (`Remove-Item`、`Rename-Item`)。`cmd /c "rd /s /q ..."` 加上含空格或
30
+ Unicode 的路径,曾把引号退化成对整个盘符根的删除(cursor 论坛事故:
31
+ 整个 C 盘被删到要重装系统)。
32
+ 2. **永远不用 `rd /s /q` / `rm -rf` 作为第一步。** 第一步是 rename 进隔离区;
33
+ 第二步才是观察期;第三步才轮到真删除。隔离目录默认
34
+ `%USERPROFILE%\.delete-quarantine\<date>\`(POSIX:`~/.delete-quarantine/<date>/`),
35
+ 同卷 rename 瞬时完成且可撤销。
36
+ 3. **路径大小写必须从磁盘上核对,不能凭记忆。** NTFS(Windows)与 APFS/HFS+
37
+ (macOS,默认)大小写不敏感:`rm -rf "D:\CampusconnECT"` 会解析到真实存在的
38
+ `D:\CampusConnect`,一次毁掉九个生产仓库(claude-code#60442)。
39
+ 4. **CJK 路径的空输出不是"文件不存在"。** PowerShell/WSL2 对 CJK 路径可能
40
+ 静默返回空结果(claude-code#68343)。看到空输出先换
41
+ `Get-Item -LiteralPath` 复核,再决定下一步。
42
+ 5. **递归删除前必须检查子树里的 junction / 符号链接。** Claude Code 官方在
43
+ v2.1.205 修复的就是这个:删 worktree 时穿透嵌套 junction,删到了树外。
44
+ 6. **不用 sudo/doas 执行删除。** root 权限会绕过几乎所有文件系统保护
45
+ (macrumors#1176135:`sudo rm -R / .Spotlight-v100` 多打一个空格)。
46
+ 需要提权清理时,先以普通用户视角跑判定器确认目标。
47
+ 7. **先 `mount` / `/proc/mounts` 再删目录。** 看起来是"空目录"的可能是挂载点:
48
+ 删的是挂载进来的整个卷(rsync --delete 清空备份盘是运维最经典的整卷事故)。
49
+ 8. **非判定宿主的平台语义不算数。** 在 WSL 里看不到 NTFS reparse 属性、
50
+ 在 Linux 上验证不了 APFS 大小写语义。判定结果为"无法验证"时,去目标平台复跑。
51
+
52
+ ## 操作流程
53
+
54
+ ### 第 1 步 —— 执行任何删除/移动前,跑判定器
55
+
56
+ ```bash
57
+ python scripts/guard.py command "<你要执行的原命令>"
58
+ ```
59
+
60
+ 退出码:`0` 允许,`1` 需人工确认,`2` 拒绝。输出里每个 hazard 都带事故编号。
61
+ **退出码 2 时,改写命令后重跑,而不是向用户 begged permission 后原样执行**——
62
+ 工具拦的不是"用户没同意",是"命令文本表达不了你的意图"。
63
+
64
+ ### 第 2 步 —— 把永久删除降级为隔离 rename
65
+
66
+ 判定为 warn/block 时,第一个动作永远是改写成隔离 rename:
67
+
68
+ ```powershell
69
+ # Windows(PowerShell):
70
+ $q = "$env:USERPROFILE\.delete-quarantine\$(Get-Date -Format yyyyMMdd-HHmmss)"
71
+ New-Item -ItemType Directory -Force -Path $q | Out-Null
72
+ Rename-Item -LiteralPath "D:\bad-old-output" -NewName $q\bad-old-output
73
+ ```
74
+
75
+ ```bash
76
+ # POSIX(Linux/macOS/WSL):
77
+ q=~/.delete-quarantine/$(date +%Y%m%d-%H%M%S)
78
+ mkdir -p "$q"
79
+ mv -- "/path/bad-old-output" "$q/bad-old-output"
80
+ ```
81
+
82
+ `-LiteralPath`(Windows)不解释通配符,这是 CJK/特殊字符路径唯一可靠的选择。
83
+ 对跨卷移动(rename 会 COPY+DELETE):先复制到同卷隔离区再删原目录。
84
+
85
+ ### 第 3 步 —— 报告时给出爆炸半径,而不是"删除完成"
86
+
87
+ 用户需要看到:`N 文件 / M 目录 / X GB / K 个链接`,链接数不为零时要显式点名。
88
+ `guard.py command ... --json` 直接给出这些数字。超过 20,000 项会截断并声明。
89
+
90
+ ## 什么时候可以直接删
91
+
92
+ - 目标是**本会话内 agent 自己刚创建**的临时目录,路径是代码里写死的单层字符串,
93
+ 判定器返回 allow
94
+ - 用户显式给出精确目标、命令为单层 shell、全 ASCII 路径、非卷根、
95
+ 非系统前缀、非挂载点、爆炸半径里 reparse=0,且判定器返回 allow
96
+ - git clean 类操作:优先 `-n`(dry-run)看清单,再真执行
97
+
98
+ 这三种之外不要再给自己找"看起来安全"的理由。工具说 block,就 block。
99
+
100
+ ## 范围外形态(判定器不覆盖,需手动纪律)
101
+
102
+ `find -delete`、`git clean -f`、`git worktree remove` 已纳入判定器
103
+ (0.3 起);以下是仍需手动纪律的形态:
104
+
105
+ - **`find` 的 `-exec rm ... \;`**:判定器只认 `-delete` 谓词,
106
+ `-exec rm` 是任意命令执行,建议先 `-print` 预览。
107
+ - **`git clean` 的交互式路径参数**:`git clean -f <path>` 的路径会被
108
+ 判定,但交互式选择(无路径参数全目录清理)依赖 `-n` 预览纪律。
109
+ - **`git worktree remove` 的嵌套 junction**:判定器给 H9 警告,
110
+ 但 worktree 内的 junction 穿透(H4 事故原型)仍需先
111
+ `git worktree list` 核对目标。
112
+ - **删除逻辑写入脚本再执行**(2026-09 事故:Python 清理脚本经
113
+ os.walk 穿透 junction 删掉 48,218 个活文件):判定器只能看见
114
+ `python cleanup.py <dir>` 这行文本,脚本内部的删除行为不可见。
115
+ 删除操作必须以 shell 直接可见的命令执行(跑判定器),绝不封装进
116
+ 自己编写的脚本;批量删除先输出文件清单(dry-run)人工过目。
117
+
118
+ ## 判定器的原理边界(MCP / 脚本间接删除)
119
+
120
+ 判定器原理是**解析 shell 命令文本**。有两类数据销毁它原理上看不见:
121
+
122
+ 1. **MCP 工具调用**(filesystem delete、数据库工具的 drop 等):
123
+ 不经过 bash/powershell 工具,判定器无从介入。
124
+ 2. **脚本间接删除**(agent 写一个 Python 清理脚本再执行):
125
+ shell 命令只是 `python cleanup.py <dir>`,删除行为在脚本内部。
126
+
127
+ 对应的宿主层防御(判定器之外的第二道墙):
128
+
129
+ - **Claude Code**:permission 配置里对 `mcp__*` 的删除类工具加
130
+ `deny`/`ask` 规则;`bypassPermissions` 只在容器/VM 里用(官方文档
131
+ 明确警告)。PreToolUse hook 的 matcher 可以同时挂 `Bash|PowerShell|Task`。
132
+ - **pi**:扩展已拦截 bash/powershell;MCP 工具调用可另装权限类扩展。
133
+ - **通用纪律**:`bypassPermissions`/`never ask` 是绝大多数事故的共同前提
134
+ (L 站/V2EX 事故复盘共识)——交互式确认挡不住 agent 自主性失控,
135
+ 但至少把"每次执行"的知情权留给你。
136
+
137
+ ## 与宿主安全机制的分工
138
+
139
+ Claude Code 的 permission 系统、Codex 的 sandbox 管的是"这次工具调用能不能跑";
140
+ 本 skill 管的是"这条命令文本在目标平台上的真实语义"。两者不互替:
141
+ sandbox 拦不住引号链退化(它在单层里合法),permission 拦不住大小写碰撞
142
+ (命令文本本身"正确")。如果你的宿主有 PreToolUse hook,把
143
+ `guard.py command` 挂进去;没有的话,本 skill 的纪律就是最后一道防线。
@@ -0,0 +1,147 @@
1
+ #!/usr/bin/env python3
2
+ """Claude Code PreToolUse hook — 在 Bash/PowerShell 工具执行前调用 guard.py。
3
+
4
+ 安装(Claude Code 的 settings.json,~/.claude/settings.json):
5
+
6
+ {
7
+ "hooks": {
8
+ "PreToolUse": [
9
+ {
10
+ "matcher": "Bash",
11
+ "hooks": [
12
+ {
13
+ "type": "command",
14
+ "command": "python3 /path/to/blast-radius-guard/hooks/pretooluse.py"
15
+
16
+ Python 探测顺序:BRG_PYTHON 环境变量 > python3 > python > py -3;
17
+ 全部缺失时 fail-open 放行。
18
+ }
19
+ ]
20
+ }
21
+ ]
22
+ }
23
+ }
24
+
25
+ 协议:从 stdin 读 {"tool_name": "Bash", "tool_input": {"command": "..."}}
26
+ 退出码 2 = 拦截,stderr 会回给模型作为拒绝原因。
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import os
33
+ import subprocess
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ GUARD_TIMEOUT = 5
38
+ RELEVANT_TOOLS = {"Bash", "PowerShell"}
39
+
40
+ _PY_CACHE: list[str] | None = None
41
+
42
+
43
+ def resolve_python() -> list[str] | None:
44
+ """按序探测可用的 Python 解释器,返回命令前缀。
45
+
46
+ Windows 原生通常只有 `python`(`python3` 常是 Microsoft Store 假别名桩)
47
+ 或 `py -3` 启动器;WSL/Linux/macOS 通常是 `python3`。
48
+ 环境变量 BRG_PYTHON 可强制指定(如 conda 环境)。结果缓存一次。
49
+ """
50
+ global _PY_CACHE
51
+ if _PY_CACHE is not None:
52
+ return _PY_CACHE or None
53
+ env = os.environ.get("BRG_PYTHON")
54
+ if env:
55
+ _PY_CACHE = [env]
56
+ return _PY_CACHE
57
+ for candidate in (["python3"], ["python"], ["py", "-3"]):
58
+ try:
59
+ probe = subprocess.run(
60
+ candidate + ["-c", "pass"],
61
+ capture_output=True, timeout=3,
62
+ )
63
+ if probe.returncode == 0:
64
+ _PY_CACHE = candidate
65
+ return _PY_CACHE
66
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError):
67
+ continue
68
+ _PY_CACHE = []
69
+ return None
70
+ # 注:find -delete 形态不在判定范围(见 SKILL.md「范围外形态」),
71
+ # 预筛不含它,避免永不匹配的死条目。
72
+ QUICK_PREDICATE = (
73
+ "rm ", "rm -", "rmdir", "del ", "erase", "rd ", "unlink", "shred",
74
+ "remove-item", "move-item", " move ", "mv ", "sudo rm", "trash ",
75
+ "rmrf",
76
+ )
77
+
78
+
79
+ def guard_path() -> Path | None:
80
+ here = Path(__file__).resolve().parent.parent
81
+ p = here / "scripts" / "guard.py"
82
+ return p if p.exists() else None
83
+
84
+
85
+ def main() -> int:
86
+ try:
87
+ payload = json.loads(sys.stdin.read() or "{}")
88
+ except json.JSONDecodeError:
89
+ return 0
90
+
91
+ if payload.get("tool_name") not in RELEVANT_TOOLS:
92
+ return 0
93
+ command = (payload.get("tool_input") or {}).get("command")
94
+ if not isinstance(command, str) or not command.strip():
95
+ return 0
96
+
97
+ if "\x00" in command:
98
+ # NUL 无法被 shell 执行,但会让 subprocess/os 崩溃走 fail-open。
99
+ # 判定层对此返回 block,这里同步拒绝(exit 2)。
100
+ print(
101
+ "delete-guard 拦截:命令含 NUL 字节,无法被任何 shell 无歧义执行。",
102
+ file=sys.stderr,
103
+ )
104
+ return 2
105
+
106
+ low = command.lower()
107
+ if not any(tok in low for tok in QUICK_PREDICATE):
108
+ return 0
109
+
110
+ gp = guard_path()
111
+ if gp is None:
112
+ return 0 # fail-open
113
+
114
+ py = resolve_python()
115
+ if py is None:
116
+ return 0 # fail-open:环境里没有可用 Python
117
+ try:
118
+ proc = subprocess.run(
119
+ py + [str(gp), "command", command, "--json"],
120
+ capture_output=True, text=True, timeout=GUARD_TIMEOUT,
121
+ )
122
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError):
123
+ return 0 # fail-open
124
+
125
+ if proc.returncode != 2:
126
+ return 0 # allow / warn 时放行
127
+
128
+ try:
129
+ result = json.loads(proc.stdout)
130
+ reasons = "; ".join(
131
+ f"{h['code']}(依据: {h['evidence']})" for h in result.get("hazards", [])
132
+ )
133
+ except json.JSONDecodeError:
134
+ reasons = proc.stdout[:400]
135
+
136
+ print(
137
+ f"delete-guard 拦截该删除命令:{reasons}。"
138
+ "改写为单层 shell、绝对路径的目标(Windows 用 -LiteralPath);"
139
+ "或先 rename 进隔离目录观察后再删;"
140
+ "不要把算好的路径管道进 cmd /c 或嵌套引号链。",
141
+ file=sys.stderr,
142
+ )
143
+ return 2
144
+
145
+
146
+ if __name__ == "__main__":
147
+ sys.exit(main())
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "delete-guard-agent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "Blast-radius judge for destructive commands on Windows, Linux and macOS: blocks filesystem-root and volume-root deletes, quote-chain degradation, NTFS/APFS case collisions, junction and symlink traversal, sudo-escalated deletes, system-prefix wipes and mount-point deletions before the agent executes them.",
5
+ "license": "MIT",
6
+ "author": "xinghe-labs",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/xinghe-labs/blast-radius-guard.git"
10
+ },
11
+ "type": "module",
12
+ "pi": {
13
+ "extensions": [
14
+ "./src/extension.ts"
15
+ ]
16
+ },
17
+ "files": [
18
+ "src",
19
+ "scripts",
20
+ "hooks",
21
+ "SKILL.md",
22
+ "README.md",
23
+ "LICENSE",
24
+ "pyrightconfig.json"
25
+ ],
26
+ "peerDependencies": {
27
+ "@earendil-works/pi-coding-agent": "*"
28
+ },
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "scripts": {
33
+ "prepublishOnly": "find scripts -name __pycache__ -type d -exec rm -rf {} + 2>/dev/null; true"
34
+ }
35
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "extraPaths": ["./scripts"],
3
+ "include": ["scripts", "tests", "src"],
4
+ "exclude": ["**/__pycache__", ".ruff_cache"],
5
+ "typeCheckingMode": "standard"
6
+ }
@@ -0,0 +1,62 @@
1
+ """delete_guard — 破坏性命令的爆炸半径判定核心。
2
+
3
+ 三条设计原则,每条都是被真实事故逼出来的:
4
+
5
+ 1. **不可解析即拒绝。** 引号链断裂(PowerShell -> cmd -> rd)正是 Cursor 整盘被删的
6
+ 根因。解析不确定不是边界情况,它就是事故本体。
7
+ 2. **无法验证就标 unknown,不默认安全。** 在 WSL 上读不到 NTFS reparse point,
8
+ 就明说读不到,而不是报告"没有链接"。
9
+ 3. **每条规则对应一个已归档的公开事故。** 没有编号的规则不许进来。
10
+
11
+ 只用标准库。Python 3.10+。
12
+ """
13
+
14
+ from .core import ( # noqa: F401
15
+ VERDICT_ORDER,
16
+ BlastRadius,
17
+ Hazard,
18
+ Intent,
19
+ ParsedCommand,
20
+ Token,
21
+ detect_shell_layers,
22
+ extract_intent,
23
+ has_cjk,
24
+ human_bytes,
25
+ is_ancestor_of_cwd,
26
+ is_drive_root,
27
+ is_flag_token,
28
+ is_wsl_windows_mount,
29
+ judge_command,
30
+ judge_path,
31
+ tokenize,
32
+ unwrap_launcher_text,
33
+ walk_blast_radius,
34
+ )
35
+ from .platform import host_name, platform_rules, unknowns_for_host # noqa: F401
36
+ from .rules import RULES # noqa: F401
37
+
38
+ __all__ = [
39
+ "VERDICT_ORDER",
40
+ "BlastRadius",
41
+ "Hazard",
42
+ "Intent",
43
+ "ParsedCommand",
44
+ "Token",
45
+ "RULES",
46
+ "detect_shell_layers",
47
+ "extract_intent",
48
+ "has_cjk",
49
+ "host_name",
50
+ "human_bytes",
51
+ "is_ancestor_of_cwd",
52
+ "is_drive_root",
53
+ "is_flag_token",
54
+ "is_wsl_windows_mount",
55
+ "judge_command",
56
+ "judge_path",
57
+ "platform_rules",
58
+ "tokenize",
59
+ "unknowns_for_host",
60
+ "unwrap_launcher_text",
61
+ "walk_blast_radius",
62
+ ]