delete-guard-agent 0.4.0 → 0.5.1
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/README.md +18 -2
- package/SKILL.md +24 -0
- package/hooks/pretooluse.py +18 -9
- package/package.json +1 -1
- package/scripts/delete_guard/core.py +66 -40
- package/scripts/delete_guard/paths.py +154 -7
- package/scripts/delete_guard/rules/common.py +10 -0
- package/src/extension.ts +13 -2
package/README.md
CHANGED
|
@@ -62,6 +62,9 @@ AI agent 静默销毁用户数据的公开事故记录已经成了一类,横
|
|
|
62
62
|
| [claude-code#14944](https://github.com/anthropics/claude-code/issues/14944) | 容器 | agent 自主 `docker volume rm` | 本地 Supabase 数据全丢 |
|
|
63
63
|
| [V2EX#1233011](https://www.v2ex.com/t/1233011) | Windows | Codex `wsl.exe bash -lc` 跨层删除 | C/D 盘两三百 GB、上百万文件 |
|
|
64
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` 级联覆盖 | 用户文件被逐个覆盖至剩一个 |
|
|
65
68
|
|
|
66
69
|
共同点:**这些命令文本在写作者的直觉里全都是"安全"的**。0.1 只覆盖 Windows;
|
|
67
70
|
0.2 起同一条判定流水线也认得出 Linux 与 macOS 的失败路径;0.3 把
|
|
@@ -77,9 +80,18 @@ AI agent 静默销毁用户数据的公开事故记录已经成了一类,横
|
|
|
77
80
|
## 安装
|
|
78
81
|
|
|
79
82
|
```bash
|
|
83
|
+
# agent skill(推荐,Claude Code / pi / Codex 通用)
|
|
80
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"
|
|
81
89
|
```
|
|
82
90
|
|
|
91
|
+
> npm 包名与本仓库不同名:`blast-radius-guard` 在 npm 上被相似名规则拦截
|
|
92
|
+
> (已有 `blastradius-guard`),故 npm 端使用 `delete-guard-agent`。GitHub /
|
|
93
|
+
> skill 安装 / 文档中的项目名统一为 blast-radius-guard。
|
|
94
|
+
|
|
83
95
|
或克隆到任意 agent 的 skill 目录:
|
|
84
96
|
|
|
85
97
|
```bash
|
|
@@ -123,6 +135,7 @@ python scripts/guard.py command "rm -rf /mnt/d/data" --json
|
|
|
123
135
|
| H12 | 目标是挂载点(删除作用于整个卷) | Linux/macOS | block |
|
|
124
136
|
| H13 | 目标是 macOS 家目录特殊目录(Documents/Library…) | macOS | block |
|
|
125
137
|
| H14 | 云/容器/ORM 工具破坏性动词(terraform destroy、prisma migrate reset、docker 卷删除、kubectl delete namespace、SQL DROP) | 全平台 | warn/block |
|
|
138
|
+
| H15 | 覆盖型销毁(通配 mv/cp 落入已存在目录、`>` 重定向清空非空文件) | 全平台 | warn |
|
|
126
139
|
|
|
127
140
|
## 代码结构(0.2 起拆包;0.3 起 find/git 意图在 core.py 内原生解析)
|
|
128
141
|
|
|
@@ -155,7 +168,7 @@ python -m unittest discover tests -v
|
|
|
155
168
|
以下项已由 CI 的 `ubuntu-latest` / `windows-latest` / `macos-latest` runner
|
|
156
169
|
或真机 E2E 覆盖:
|
|
157
170
|
|
|
158
|
-
- [x] 单元测试(
|
|
171
|
+
- [x] 单元测试(131 个,含 H3/H4/H11-H15/find/git 断言、中文社区与第四轮事故回归、预筛一致性比对、过度拦截反例)在
|
|
159
172
|
ubuntu + windows + macos 三个 runner 上跑
|
|
160
173
|
- [x] macOS 真机回归(H3 APFS 大小写、H13 家目录特殊目录)——由
|
|
161
174
|
`macos-latest` runner 真机执行,不再是仅静态判定
|
|
@@ -172,13 +185,16 @@ python -m unittest discover tests -v
|
|
|
172
185
|
- macOS 宿主上的 pi 扩展 / Claude Code hook 实机加载(CI 只覆盖了判定器与测试;
|
|
173
186
|
扩展层的 Python 探测在 darwin 上未跑过端到端)
|
|
174
187
|
- Codex 无 hook 机制,只有 skill 层(宿主限制)
|
|
188
|
+
- MCP 工具调用与"agent 写脚本再执行"的间接删除(2026-09 的 48k 文件事故
|
|
189
|
+
形态)原理上不在 shell 判定范围内 —— 防御依赖宿主 permission 配置与
|
|
190
|
+
使用纪律,见 SKILL.md「判定器的原理边界」
|
|
175
191
|
|
|
176
192
|
## 反馈误报 / 漏报
|
|
177
193
|
|
|
178
194
|
规则集未经实战,你的真实使用是最有价值的数据源。遇到以下情况请开
|
|
179
195
|
[误报/漏报 issue](https://github.com/xinghe-labs/blast-radius-guard/issues/new?template=false-positive.yml):
|
|
180
196
|
|
|
181
|
-
- **误报**:安全的命令被 block
|
|
197
|
+
- **误报**:安全的命令被 block(比如正常的清理脚本被拦,或 `rg "terraform destroy"` 被当成要执行)
|
|
182
198
|
- **漏报**:危险的命令被 allow/warn
|
|
183
199
|
|
|
184
200
|
模板会引导你贴出命令原文、OS 和 `--json` 判定输出——这是调规则需要的全部信息。
|
package/SKILL.md
CHANGED
|
@@ -109,6 +109,30 @@ mv -- "/path/bad-old-output" "$q/bad-old-output"
|
|
|
109
109
|
- **`git worktree remove` 的嵌套 junction**:判定器给 H9 警告,
|
|
110
110
|
但 worktree 内的 junction 穿透(H4 事故原型)仍需先
|
|
111
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
|
+
但至少把"每次执行"的知情权留给你。
|
|
112
136
|
|
|
113
137
|
## 与宿主安全机制的分工
|
|
114
138
|
|
package/hooks/pretooluse.py
CHANGED
|
@@ -30,6 +30,7 @@ from __future__ import annotations
|
|
|
30
30
|
|
|
31
31
|
import json
|
|
32
32
|
import os
|
|
33
|
+
import re
|
|
33
34
|
import subprocess
|
|
34
35
|
import sys
|
|
35
36
|
from pathlib import Path
|
|
@@ -37,6 +38,21 @@ from pathlib import Path
|
|
|
37
38
|
GUARD_TIMEOUT = 5
|
|
38
39
|
RELEVANT_TOOLS = {"Bash", "PowerShell"}
|
|
39
40
|
|
|
41
|
+
# 快速预筛(与 src/extension.ts 的同名模式保持逐字一致,测试会比对两边):
|
|
42
|
+
# 不含删除/移动/破坏性工具动词的命令直接放行,省掉一次 Python 子进程。
|
|
43
|
+
# 0.5.1 修:旧版只认 shell 删除动词,H14(云/容器/ORM/SQL)与 H15(> 重定向)
|
|
44
|
+
# 的 block 判定永远到不了 hook —— 硬拦截层对这两类规则形同虚设。
|
|
45
|
+
QUICK_PREDICATE_SRC = (
|
|
46
|
+
r"(?:\b(?:rm|rmdir|del|erase|rd|unlink|shred|trash|remove-item|ri|move-item|"
|
|
47
|
+
r"mv|move|sudo|doas|su)\b)"
|
|
48
|
+
r"|(?:\bgit\s+(?:clean|worktree|rm)\b)"
|
|
49
|
+
r"|(?:\bfind\b[^|;]*?-delete\b)"
|
|
50
|
+
r"|(?:\b(?:docker|terraform|pulumi|kubectl|prisma|alembic|drizzle|railway|"
|
|
51
|
+
r"gcloud|supabase|neon|kiro|psql|mysql|mariadb|sqlite3|sqlcmd|aws)\b)"
|
|
52
|
+
r"|>>?"
|
|
53
|
+
)
|
|
54
|
+
QUICK_PREDICATE = re.compile(QUICK_PREDICATE_SRC, re.IGNORECASE)
|
|
55
|
+
|
|
40
56
|
_PY_CACHE: list[str] | None = None
|
|
41
57
|
|
|
42
58
|
|
|
@@ -69,13 +85,6 @@ def resolve_python() -> list[str] | None:
|
|
|
69
85
|
return None
|
|
70
86
|
# 注:find -delete 形态不在判定范围(见 SKILL.md「范围外形态」),
|
|
71
87
|
# 预筛不含它,避免永不匹配的死条目。
|
|
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
88
|
def guard_path() -> Path | None:
|
|
80
89
|
here = Path(__file__).resolve().parent.parent
|
|
81
90
|
p = here / "scripts" / "guard.py"
|
|
@@ -103,8 +112,8 @@ def main() -> int:
|
|
|
103
112
|
)
|
|
104
113
|
return 2
|
|
105
114
|
|
|
106
|
-
low = command
|
|
107
|
-
if not
|
|
115
|
+
low = command
|
|
116
|
+
if not QUICK_PREDICATE.search(low):
|
|
108
117
|
return 0
|
|
109
118
|
|
|
110
119
|
gp = guard_path()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "delete-guard-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
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
5
|
"license": "MIT",
|
|
6
6
|
"author": "xinghe-labs",
|
|
@@ -13,28 +13,32 @@ import re
|
|
|
13
13
|
from dataclasses import dataclass, field
|
|
14
14
|
|
|
15
15
|
from .paths import (
|
|
16
|
+
_CMD_FLAG_RE,
|
|
17
|
+
_REPARSE_ATTR,
|
|
18
|
+
_SHELL_VAR_RE,
|
|
16
19
|
DELETE_VERBS_POSIX,
|
|
17
20
|
DELETE_VERBS_PS,
|
|
18
21
|
DELETE_VERBS_WIN,
|
|
22
|
+
FORCE_LONG,
|
|
23
|
+
FORCE_SHORT,
|
|
19
24
|
MOVE_VERBS,
|
|
20
25
|
PRIVILEGE_ESCALATORS,
|
|
21
26
|
RECURSIVE_LONG,
|
|
22
27
|
RECURSIVE_SHORT,
|
|
23
|
-
FORCE_LONG,
|
|
24
|
-
FORCE_SHORT,
|
|
25
28
|
SHELL_LAUNCHERS,
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
analysis_path,
|
|
30
|
+
cloud_tool_match,
|
|
31
|
+
glob_base_dir,
|
|
29
32
|
has_cjk,
|
|
30
33
|
human_bytes,
|
|
31
34
|
is_ancestor_of_cwd,
|
|
32
35
|
is_drive_root,
|
|
33
|
-
|
|
34
|
-
glob_base_dir,
|
|
36
|
+
is_windows_style_path,
|
|
35
37
|
is_wsl_windows_mount,
|
|
36
38
|
macos_home_special,
|
|
39
|
+
overwrite_risk,
|
|
37
40
|
posix_system_prefix,
|
|
41
|
+
same_path,
|
|
38
42
|
)
|
|
39
43
|
from .platform import host_name, is_wsl, unknowns_for_host
|
|
40
44
|
from .rules import RULES, VERDICT_ORDER
|
|
@@ -267,11 +271,11 @@ def is_flag_token(v: str, cmd_verb: bool = False) -> bool:
|
|
|
267
271
|
return False
|
|
268
272
|
if v.startswith("-") and not re.match(r"^-\d", v):
|
|
269
273
|
return True
|
|
274
|
+
# 单字母 cmd flag(/s /q /d)与多字母一样需要 cmd 系动词语境:
|
|
275
|
+
# POSIX 删除动词下的 /d /x 是真实路径(目录名恰好单字母合法存在)
|
|
270
276
|
if _CMD_FLAG_RE.match(v):
|
|
271
|
-
return
|
|
272
|
-
|
|
273
|
-
return True
|
|
274
|
-
return False
|
|
277
|
+
return cmd_verb
|
|
278
|
+
return bool(_CMD_LONG_FLAG_RE.match(v) and cmd_verb)
|
|
275
279
|
|
|
276
280
|
|
|
277
281
|
@dataclass
|
|
@@ -390,9 +394,7 @@ def extract_intent(parsed: ParsedCommand) -> Intent:
|
|
|
390
394
|
force = True
|
|
391
395
|
if tok in {"/purge", "--prune-empty-dirs"}:
|
|
392
396
|
force = True
|
|
393
|
-
if tok in {f.lower() for f in RECURSIVE_LONG}:
|
|
394
|
-
recursive = True
|
|
395
|
-
elif tok in RECURSIVE_LONG:
|
|
397
|
+
if tok in {f.lower() for f in RECURSIVE_LONG} or tok in RECURSIVE_LONG:
|
|
396
398
|
recursive = True
|
|
397
399
|
elif tok.startswith("-") and not tok.startswith("--"):
|
|
398
400
|
body = tok.lstrip("-")
|
|
@@ -462,34 +464,39 @@ def case_collision(path: str, windows_layout: bool | None = None) -> str | None:
|
|
|
462
464
|
NTFS/APFS 大小写不敏感 —— 这正是 D:\\CampusconnECT 删掉
|
|
463
465
|
D:\\CampusConnect 的原因(claude-code#60442)。
|
|
464
466
|
|
|
465
|
-
windows_layout 为 None
|
|
467
|
+
windows_layout 为 None 时按目标形态推断(盘符路径走 Windows 布局,
|
|
468
|
+
绝对 POSIX 路径走 macOS 布局)。刻意**不**用 os.name 推断:那样
|
|
469
|
+
macOS 分支在 Linux 上永远不可测,测试无法覆盖 APFS 路径(0.5.1 修)。
|
|
470
|
+
仅用于测试显式指定布局。
|
|
466
471
|
"""
|
|
467
472
|
if not path or not case_insensitive_host():
|
|
468
473
|
return None
|
|
469
474
|
if windows_layout is None:
|
|
470
|
-
windows_layout =
|
|
475
|
+
windows_layout = is_windows_style_path(path)
|
|
471
476
|
# 逐级比对大小写:Windows 走盘符/反斜杠布局,macOS 走 POSIX 布局
|
|
477
|
+
# 回归(0.5.1):POSIX 分支曾用 os.path.join("", seg) 丢掉根目录,
|
|
478
|
+
# 路径退化成相对,逐级核对在第二段就 listdir 失败 → macOS 上 H3 永不触发
|
|
472
479
|
if windows_layout:
|
|
473
480
|
drive, tail = ntpath.splitdrive(path)
|
|
474
481
|
segments = [s for s in tail.replace("/", "\\").split("\\") if s]
|
|
475
|
-
cur = drive + "\\" if drive else ""
|
|
476
|
-
|
|
482
|
+
cur = drive + "\\" if drive else "."
|
|
483
|
+
joiner = ntpath.join
|
|
477
484
|
else:
|
|
478
485
|
segments = [s for s in path.replace("\\", "/").split("/") if s]
|
|
479
|
-
cur = ""
|
|
480
|
-
|
|
486
|
+
cur = "/"
|
|
487
|
+
joiner = os.path.join
|
|
481
488
|
for seg in segments:
|
|
482
489
|
try:
|
|
483
|
-
entries = os.listdir(cur
|
|
490
|
+
entries = os.listdir(cur)
|
|
484
491
|
except OSError:
|
|
485
492
|
return None
|
|
486
493
|
match = next((e for e in entries if e == seg), None)
|
|
487
494
|
if match is None:
|
|
488
495
|
ci = next((e for e in entries if e.lower() == seg.lower()), None)
|
|
489
496
|
if ci is not None:
|
|
490
|
-
return
|
|
497
|
+
return joiner(cur, ci)
|
|
491
498
|
return None
|
|
492
|
-
cur =
|
|
499
|
+
cur = joiner(cur, match)
|
|
493
500
|
return None
|
|
494
501
|
|
|
495
502
|
|
|
@@ -553,9 +560,7 @@ def _is_reparse(entry: os.DirEntry, st: os.stat_result) -> bool:
|
|
|
553
560
|
if entry.is_symlink():
|
|
554
561
|
return True
|
|
555
562
|
attrs = getattr(st, "st_file_attributes", 0)
|
|
556
|
-
|
|
557
|
-
return True
|
|
558
|
-
return False
|
|
563
|
+
return bool(attrs & _REPARSE_ATTR)
|
|
559
564
|
|
|
560
565
|
|
|
561
566
|
def is_mount_point(path: str) -> bool:
|
|
@@ -573,7 +578,7 @@ def is_mount_point(path: str) -> bool:
|
|
|
573
578
|
fields = line.split()
|
|
574
579
|
if len(fields) >= 2:
|
|
575
580
|
mp = fields[1].replace("\\040", " ").replace("\\011", "\t")
|
|
576
|
-
if mp
|
|
581
|
+
if mp in (real, path):
|
|
577
582
|
return True
|
|
578
583
|
except OSError:
|
|
579
584
|
return False
|
|
@@ -629,6 +634,17 @@ def judge_command(
|
|
|
629
634
|
add("H0_AMBIGUOUS", parsed.ambiguous_reason or "")
|
|
630
635
|
return _result(hazards, [], unknowns)
|
|
631
636
|
|
|
637
|
+
# find <path> ... -exec <cmd> {} \; —— 内层命令递归判定
|
|
638
|
+
# (候选 13/0.6:-exec rm 是嵌套删除,判定器必须能看见)
|
|
639
|
+
layers_from_parse = parsed.shell_layers # parse 阶段已检出的跳转层
|
|
640
|
+
exec_match = re.search(r"-exec\s+(.+?)\s*\{\}\s*(?:\\;|\+)", command)
|
|
641
|
+
if exec_match and not layers_from_parse:
|
|
642
|
+
inner = exec_match.group(1).replace("{}", "<matched-file>")
|
|
643
|
+
inner_r = judge_command(inner, cwd, wsl_context, privileged_context)
|
|
644
|
+
# 容器危险:-exec 作用于 find 命中的每个文件(批量语义)
|
|
645
|
+
add("H8_GLOB_RECURSIVE", "-exec 批量执行:作用于 find 命中的所有文件")
|
|
646
|
+
return _merge_inner(hazards, unknowns, inner_r, ["find -exec"])
|
|
647
|
+
|
|
632
648
|
# 跨层执行:提取内层命令文本,递归判定,危险按层级累加。
|
|
633
649
|
inner_text, layers = unwrap_launcher_text(command, parsed.tokens)
|
|
634
650
|
if layers:
|
|
@@ -643,7 +659,7 @@ def judge_command(
|
|
|
643
659
|
f"目标带引号且含空格/CJK,经 {' -> '.join(layers)} 跳转时"
|
|
644
660
|
"参数会在层间被重新解释",
|
|
645
661
|
)
|
|
646
|
-
lower_layers = [
|
|
662
|
+
lower_layers = [layer.lower() for layer in layers]
|
|
647
663
|
inner_wsl = (
|
|
648
664
|
wsl_context
|
|
649
665
|
if wsl_context is not None
|
|
@@ -652,7 +668,7 @@ def judge_command(
|
|
|
652
668
|
inner_priv = (
|
|
653
669
|
privileged_context
|
|
654
670
|
if privileged_context is not None
|
|
655
|
-
else any(
|
|
671
|
+
else any(layer in PRIVILEGE_ESCALATORS for layer in lower_layers)
|
|
656
672
|
)
|
|
657
673
|
return _merge_inner(
|
|
658
674
|
hazards,
|
|
@@ -695,9 +711,14 @@ def judge_command(
|
|
|
695
711
|
# 原生 Linux 上 /mnt 下可能是任意普通挂载,交由 H12 按真实挂载表判定。
|
|
696
712
|
if wsl_context is None:
|
|
697
713
|
wsl_context = is_wsl() or "wsl" in [
|
|
698
|
-
|
|
714
|
+
layer.lower() for layer in parsed.shell_layers
|
|
699
715
|
]
|
|
700
716
|
|
|
717
|
+
# H15 覆盖型销毁(命令级判定;需要目标存在性核对,仅在真实 FS 上有效)
|
|
718
|
+
ow_hit = overwrite_risk(command)
|
|
719
|
+
if ow_hit:
|
|
720
|
+
add("H15_OVERWRITE", ow_hit)
|
|
721
|
+
|
|
701
722
|
# H14 云/容器/ORM/SQL 工具的破坏性动词(命令级判定)
|
|
702
723
|
cloud_hit = cloud_tool_match(command)
|
|
703
724
|
if cloud_hit:
|
|
@@ -708,6 +729,7 @@ def judge_command(
|
|
|
708
729
|
"kubectl delete namespace", "kubectl delete ns",
|
|
709
730
|
"terraform destroy", "pulumi destroy",
|
|
710
731
|
"sql drop/truncate",
|
|
732
|
+
"kiro environment delete",
|
|
711
733
|
)
|
|
712
734
|
# 级别:block 形态通过独立 Hazard 覆盖 severity(RULES 表里 H14 默认 warn)
|
|
713
735
|
detail = (
|
|
@@ -736,12 +758,15 @@ def judge_command(
|
|
|
736
758
|
radii: list[BlastRadius] = []
|
|
737
759
|
for target in intent.targets:
|
|
738
760
|
radii.append(walk_blast_radius(target))
|
|
761
|
+
# 判定用的归一形态:展开 ~ / $HOME、合并 .. 与 .(不跟链接)
|
|
762
|
+
ap = analysis_path(target)
|
|
739
763
|
|
|
740
|
-
if is_drive_root(
|
|
764
|
+
if is_drive_root(ap):
|
|
741
765
|
add("H2_DRIVE_ROOT", f"目标 {target!r} 是卷根")
|
|
742
766
|
|
|
743
767
|
real = case_collision(target)
|
|
744
|
-
|
|
768
|
+
# 不能用 normcase 比较:Windows 上它把大小写抹平,等于把 H3 关掉
|
|
769
|
+
if real and not same_path(real, target):
|
|
745
770
|
add("H3_CASE_COLLISION", f"{target!r} 实际指向已存在的 {real!r}")
|
|
746
771
|
|
|
747
772
|
br = radii[-1]
|
|
@@ -802,16 +827,16 @@ def judge_command(
|
|
|
802
827
|
)
|
|
803
828
|
|
|
804
829
|
# H11 系统关键前缀(含变量退化形态,如空变量后剩余的 /*)
|
|
805
|
-
sys_prefix = posix_system_prefix(
|
|
830
|
+
sys_prefix = posix_system_prefix(ap)
|
|
806
831
|
if sys_prefix and intent.recursive:
|
|
807
832
|
add("H11_SYSTEM_PREFIX", f"{target!r} 命中系统前缀 {sys_prefix}")
|
|
808
833
|
|
|
809
834
|
# H12 挂载点
|
|
810
|
-
if intent.recursive and is_mount_point(
|
|
835
|
+
if intent.recursive and is_mount_point(ap):
|
|
811
836
|
add("H12_MOUNT_POINT", f"{target!r} 是挂载点,删除作用于整个卷")
|
|
812
837
|
|
|
813
|
-
# H13 macOS
|
|
814
|
-
special = macos_home_special(
|
|
838
|
+
# H13 macOS 家目录特殊目录(~/Downloads 这类形态归一后也要命中)
|
|
839
|
+
special = macos_home_special(ap)
|
|
815
840
|
if special:
|
|
816
841
|
add("H13_MACOS_HOME_SPECIAL", f"{target!r} 命中 macOS 家目录特殊目录 {special}")
|
|
817
842
|
|
|
@@ -839,7 +864,7 @@ def judge_path(path: str, cwd: str | None = None) -> dict:
|
|
|
839
864
|
if is_drive_root(path):
|
|
840
865
|
add("H2_DRIVE_ROOT", f"{path!r} 是卷根")
|
|
841
866
|
real = case_collision(path)
|
|
842
|
-
if real and
|
|
867
|
+
if real and not same_path(real, path):
|
|
843
868
|
add("H3_CASE_COLLISION", f"{path!r} 实际指向已存在的 {real!r}")
|
|
844
869
|
if has_cjk(path):
|
|
845
870
|
add("H5_CJK_SILENT_FAIL", f"路径含 CJK:{path!r}")
|
|
@@ -852,12 +877,13 @@ def judge_path(path: str, cwd: str | None = None) -> dict:
|
|
|
852
877
|
if br.reparse_points:
|
|
853
878
|
add("H4_REPARSE_TRAVERSAL", f"{path!r} 子树内有 {br.reparse_points} 个链接")
|
|
854
879
|
|
|
855
|
-
|
|
880
|
+
ap = analysis_path(path)
|
|
881
|
+
sys_prefix = posix_system_prefix(ap)
|
|
856
882
|
if sys_prefix:
|
|
857
883
|
add("H11_SYSTEM_PREFIX", f"{path!r} 命中系统前缀 {sys_prefix}")
|
|
858
|
-
if is_mount_point(
|
|
884
|
+
if is_mount_point(ap):
|
|
859
885
|
add("H12_MOUNT_POINT", f"{path!r} 是挂载点")
|
|
860
|
-
special = macos_home_special(
|
|
886
|
+
special = macos_home_special(ap)
|
|
861
887
|
if special:
|
|
862
888
|
add("H13_MACOS_HOME_SPECIAL", f"{path!r} 命中 macOS 家目录特殊目录 {special}")
|
|
863
889
|
|
|
@@ -91,6 +91,8 @@ CLOUD_CLI_DESTRUCTIVE = {
|
|
|
91
91
|
"aws s3 rb",
|
|
92
92
|
"gcloud sql instances delete",
|
|
93
93
|
"supabase db reset",
|
|
94
|
+
"kiro environment delete", # AWS Kiro 2025-12:删环境重建致 13h 故障(FT 报道)
|
|
95
|
+
"neon db sql", # GPT-5.6 Sol 经 neon CLI TRUNCATE users 表(2026-07)
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
# macOS 家目录特殊目录(H13):Finder / Time Machine / iCloud / 应用依赖
|
|
@@ -199,6 +201,42 @@ def has_cjk(s: str) -> bool:
|
|
|
199
201
|
return False
|
|
200
202
|
|
|
201
203
|
|
|
204
|
+
def same_path(a: str, b: str) -> bool:
|
|
205
|
+
"""大小写敏感的字面比较(H3 用)。
|
|
206
|
+
|
|
207
|
+
os.path.normcase 在 Windows 上会 lowercase 整条路径 —— 用它比较
|
|
208
|
+
"目标 vs 磁盘真实路径" 等于把 H3 在唯一真正需要它的平台上关掉:
|
|
209
|
+
D:\\CampusconnECT 与 D:\\CampusConnect 会被判成同一个路径。
|
|
210
|
+
normpath 只做分隔符/.. 归一,保留大小写。
|
|
211
|
+
"""
|
|
212
|
+
try:
|
|
213
|
+
return os.path.normpath(os.path.expanduser(a)) == os.path.normpath(
|
|
214
|
+
os.path.expanduser(b)
|
|
215
|
+
)
|
|
216
|
+
except (TypeError, ValueError, OSError):
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def analysis_path(target: str) -> str:
|
|
221
|
+
"""把目标归一成"判定用的绝对形态":展开 ~ 与 $HOME、合并 .. / .、
|
|
222
|
+
统一分隔符,但**不做存在性检查也不做 realpath**(realpath 会跟掉
|
|
223
|
+
junction,H4 需要看到链接本身)。
|
|
224
|
+
|
|
225
|
+
目的:让 `~/Downloads`、`/Users/me/../me/Documents`、`D:\\a\\..\\`
|
|
226
|
+
这类形态在 H2/H11/H13 面前与它们的绝对形态等价。
|
|
227
|
+
"""
|
|
228
|
+
p = target.strip().strip("'\"")
|
|
229
|
+
if not p:
|
|
230
|
+
return p
|
|
231
|
+
try:
|
|
232
|
+
p = os.path.expanduser(os.path.expandvars(p))
|
|
233
|
+
except (TypeError, ValueError):
|
|
234
|
+
return p
|
|
235
|
+
if is_windows_style_path(p) and not p.startswith("/"):
|
|
236
|
+
return ntpath.normpath(p)
|
|
237
|
+
return os.path.normpath(p) if p.startswith("/") else p
|
|
238
|
+
|
|
239
|
+
|
|
202
240
|
def is_ancestor_of_cwd(target: str, cwd: str) -> bool:
|
|
203
241
|
try:
|
|
204
242
|
t = os.path.abspath(os.path.expanduser(target))
|
|
@@ -225,10 +263,102 @@ def human_bytes(n: int) -> str:
|
|
|
225
263
|
return f"{size:.1f} TB"
|
|
226
264
|
|
|
227
265
|
|
|
266
|
+
def overwrite_risk(command: str) -> str | None:
|
|
267
|
+
"""H15:覆盖型销毁检测(Gemini CLI move 级联 / vscode 覆写 / PS 编码清空)。
|
|
268
|
+
|
|
269
|
+
三种命中形态,全部要求"覆盖已存在内容"这个前提:
|
|
270
|
+
1. 通配符 mv/cp 批量落入已存在目录(Gemini 事故:mkdir 失败仍继续)
|
|
271
|
+
2. > 重定向目标文件已存在且非空(PowerShell 编码清空事故)
|
|
272
|
+
3. mv/cp 不带 -n/-i 且目标为已存在目录下的同名路径(vscode 覆写)
|
|
273
|
+
单文件改名、写新文件、mkdir 后首次写入:放行(噪声控制)。
|
|
274
|
+
返回形态描述,不命中 None。
|
|
275
|
+
"""
|
|
276
|
+
import os as _os
|
|
277
|
+
# 保留大小写:目标路径要做真实存在性核对,lowercase 后
|
|
278
|
+
# 在大小写敏感的 FS(ext4/APFS 敏感卷)上会永远查不到
|
|
279
|
+
# (0.5.1 修:`> Src.Main.PY` 曾被判成 allow)
|
|
280
|
+
norm = _norm_cmd_preserve_case(command)
|
|
281
|
+
|
|
282
|
+
# 形态 1/3:mv / cp 批量覆盖(通配符源 + 已存在目标目录)
|
|
283
|
+
# 允许 -r/-rf/-a 等旗标夹在动词与源之间
|
|
284
|
+
m = re.search(
|
|
285
|
+
r"\b(mv|cp)\s+(?:-[a-zA-Z]+\s+)?(\S*\*[\S\s]*?)\s+(\S+)$",
|
|
286
|
+
norm,
|
|
287
|
+
re.IGNORECASE,
|
|
288
|
+
)
|
|
289
|
+
if m and "*?" not in m.group(3):
|
|
290
|
+
dest = m.group(3).strip("'\"")
|
|
291
|
+
if _os.path.isdir(dest):
|
|
292
|
+
return (
|
|
293
|
+
f"批量覆盖:{m.group(1)} 通配源 → 已存在目录 {dest!r}"
|
|
294
|
+
"(同名文件将被无声覆盖)"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
# 形态 2:> 重定向到已存在非空文件(>> 追加不拦:负向前瞻排除 >>)
|
|
298
|
+
m = re.search(
|
|
299
|
+
r"(?:^|&&|;)\s*[^&;]*?(?<!>)>(?!>)\s*(\S+)\s*(?:2>|&|$)",
|
|
300
|
+
norm,
|
|
301
|
+
)
|
|
302
|
+
if m:
|
|
303
|
+
target = m.group(1).strip("'\"")
|
|
304
|
+
if _os.path.isfile(target):
|
|
305
|
+
try:
|
|
306
|
+
if _os.path.getsize(target) > 0:
|
|
307
|
+
return f"重定向覆盖:> {target!r}(文件已存在且非空,内容将被清空重写)"
|
|
308
|
+
except OSError:
|
|
309
|
+
pass
|
|
310
|
+
return None
|
|
311
|
+
|
|
312
|
+
|
|
228
313
|
def _norm_cmd(text: str) -> str:
|
|
229
314
|
return " ".join(text.lower().split())
|
|
230
315
|
|
|
231
316
|
|
|
317
|
+
def _norm_cmd_preserve_case(text: str) -> str:
|
|
318
|
+
"""只归一空白,不动大小写(路径要拿去核磁盘)。"""
|
|
319
|
+
return " ".join(text.split())
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# 只读勘察类命令:它们出现在命令行时,命中词很可能只是被搜索/打印的
|
|
323
|
+
# 文本,而不是要执行的动词(`rg "docker volume rm" docs/`、
|
|
324
|
+
# `git log --grep="terraform destroy"`、`echo "不要跑 terraform destroy"`)。
|
|
325
|
+
_READONLY_HEADS = {
|
|
326
|
+
"grep", "rg", "ag", "ack", "egrep", "fgrep", "ack-grep",
|
|
327
|
+
"echo", "printf", "cat", "head", "tail", "less", "more", "bat",
|
|
328
|
+
"man", "which", "whereis", "type", "history", "ls", "dir", "stat",
|
|
329
|
+
"file", "diff", "wc",
|
|
330
|
+
}
|
|
331
|
+
# git 只读子命令(其余 git 子命令仍按原样匹配)
|
|
332
|
+
_READONLY_GIT_SUBS = {
|
|
333
|
+
"log", "show", "grep", "diff", "blame", "status", "branch",
|
|
334
|
+
"remote", "tag", "rev-parse", "ls-files", "describe", "shortlog",
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _readonly_head(norm: str) -> bool:
|
|
339
|
+
"""命令首段(跳过 cd … &&)是否为只读勘察类命令。"""
|
|
340
|
+
body = norm.strip()
|
|
341
|
+
for _ in range(4):
|
|
342
|
+
stripped = re.sub(r"^cd\s+[^&;|]+\s*(?:&&|;|\|\|)\s*", "", body)
|
|
343
|
+
if stripped == body:
|
|
344
|
+
break
|
|
345
|
+
body = stripped
|
|
346
|
+
tokens = body.split()
|
|
347
|
+
if not tokens:
|
|
348
|
+
return False
|
|
349
|
+
head = tokens[0].lstrip("(").lower()
|
|
350
|
+
if head == "git":
|
|
351
|
+
sub = tokens[1].lower() if len(tokens) > 1 else ""
|
|
352
|
+
return sub in _READONLY_GIT_SUBS
|
|
353
|
+
return head in _READONLY_HEADS
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _inside_quotes(norm: str, pos: int) -> bool:
|
|
357
|
+
"""pos 处是否处于引号内(单引号或双引号奇数个即在内)。"""
|
|
358
|
+
before = norm[:pos]
|
|
359
|
+
return (before.count('"') % 2 == 1) or (before.count("'") % 2 == 1)
|
|
360
|
+
|
|
361
|
+
|
|
232
362
|
def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
233
363
|
"""H14:命令是否命中云/容器/ORM 工具的破坏性形态。
|
|
234
364
|
|
|
@@ -236,6 +366,22 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
|
236
366
|
先做直接前缀/包含匹配;SQL 破坏语句经引号内提取二次检测。
|
|
237
367
|
"""
|
|
238
368
|
norm = _norm_cmd(command)
|
|
369
|
+
# 只读勘察命令(grep/rg/echo/git log …)里的命中词只是被搜索的文本,
|
|
370
|
+
# 不是要执行的动词 —— 否则 `rg "docker volume rm" docs/` 会被 warn,
|
|
371
|
+
# `echo "不要跑 terraform destroy"` 会直接 block(0.5.1 修)
|
|
372
|
+
if _readonly_head(norm):
|
|
373
|
+
return None
|
|
374
|
+
if "--help" in norm or " -h " in norm:
|
|
375
|
+
return None
|
|
376
|
+
# SQL 破坏语句优先于工具表匹配(TRUNCATE/DROP 的破坏语义精确,block 级)
|
|
377
|
+
sql_stmt = re.search(r"\b(drop\s+(table|database|schema)\b|truncate\b)", norm)
|
|
378
|
+
sql_client = re.search(
|
|
379
|
+
r"\b(psql|mysql|mariadb|sqlite3|sqlcmd|neon|supabase)\b"
|
|
380
|
+
r"|\b(npx|yarn|pnpm)\s+\w+\s+db\b",
|
|
381
|
+
norm,
|
|
382
|
+
)
|
|
383
|
+
if sql_stmt and sql_client:
|
|
384
|
+
return "sql drop/truncate", "prisma blog 2026-07, claude-code Neon truncate 2026-07"
|
|
239
385
|
tables = [
|
|
240
386
|
(DOCKER_DESTRUCTIVE, "claude-code#14944/#41357, deedglass compose-down-v"),
|
|
241
387
|
(K8S_DESTRUCTIVE, "deedglass kubectl-delete, agenticcontrolplane 2026-04"),
|
|
@@ -246,13 +392,14 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
|
246
392
|
for shape in table:
|
|
247
393
|
# 包含式匹配:python -m alembic downgrade base、cd x && terraform
|
|
248
394
|
# destroy 等前缀形态也要命中(形状本身是多词短语,误配风险低)
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
395
|
+
idx = norm.find(shape)
|
|
396
|
+
if idx < 0:
|
|
397
|
+
continue
|
|
398
|
+
# 引号内的命中交给上层:psql -c "DROP …" 是真执行,
|
|
399
|
+
# 而 echo "terraform destroy" 已被 _readonly_head 拦在上面
|
|
400
|
+
if _inside_quotes(norm, idx):
|
|
401
|
+
continue
|
|
402
|
+
return shape, evidence
|
|
256
403
|
return None
|
|
257
404
|
|
|
258
405
|
|
|
@@ -29,6 +29,16 @@ RULES_COMMON: dict[str, tuple[str, str, str]] = {
|
|
|
29
29
|
"永久删除而非移入隔离区,删除通常不进回收站/废纸篓",
|
|
30
30
|
"codex#14487, cursor-forum#174156",
|
|
31
31
|
),
|
|
32
|
+
# H15:覆盖型销毁 —— 动词是 mv/cp/echo(非删除),但效果是既有数据
|
|
33
|
+
# 被无声覆盖。Gemini CLI 级联覆盖 + PowerShell 编码清空 + vscode 覆写
|
|
34
|
+
# 三个独立事故源(INCIDENTS.md 候选 2/12/14)。
|
|
35
|
+
"H15_OVERWRITE": (
|
|
36
|
+
"warn",
|
|
37
|
+
"覆盖型销毁:批量 mv/cp 落入已存在目录、> 重定向清空非空文件 ——"
|
|
38
|
+
"既有数据被无声覆盖,且常见于 mkdir 失败后 agent 继续执行的场景",
|
|
39
|
+
"Agent Incident Ledger (Gemini CLI 2025-07), linux.do#2402993 "
|
|
40
|
+
"(PS 编码清空), microsoft/vscode#298393",
|
|
41
|
+
),
|
|
32
42
|
# H14:云/容器/ORM/SQL 工具的破坏性动词 —— 动词不在 shell 删除词表里,
|
|
33
43
|
# 但破坏力等同 rm -rf(PocketOS 9 秒清掉生产库+备份;terraform destroy
|
|
34
44
|
# 毁掉 2.5 年生产设施)。完整动词表与事故背书见 INCIDENTS.md 候选 7-10。
|
package/src/extension.ts
CHANGED
|
@@ -22,6 +22,17 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
22
22
|
|
|
23
23
|
const GUARD_TIMEOUT_MS = 5_000;
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* 快速预筛(与 hooks/pretooluse.py 的 QUICK_PREDICATE_SRC 逐字一致,
|
|
27
|
+
* tests/test_guard.py 会比对两边):不含破坏性动词的命令直接放行。
|
|
28
|
+
*
|
|
29
|
+
* 0.5.1 修:旧版只认 shell 删除动词,H14(云/容器/ORM/SQL)与
|
|
30
|
+
* H15(> 重定向)的 block 判定永远到不了扩展 —— 硬拦截层对这两类规则
|
|
31
|
+
* 形同虚设,而它们恰好是唯一 block 级的云/数据层保护。
|
|
32
|
+
*/
|
|
33
|
+
const QUICK_PREDICATE =
|
|
34
|
+
/(?:\b(?:rm|rmdir|del|erase|rd|unlink|shred|trash|remove-item|ri|move-item|mv|move|sudo|doas|su)\b)|(?:\bgit\s+(?:clean|worktree|rm)\b)|(?:\bfind\b[^|;]*?-delete\b)|(?:\b(?:docker|terraform|pulumi|kubectl|prisma|alembic|drizzle|railway|gcloud|supabase|neon|kiro|psql|mysql|mariadb|sqlite3|sqlcmd|aws)\b)|>>?/i;
|
|
35
|
+
|
|
25
36
|
function guardScript(): string | null {
|
|
26
37
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
27
38
|
const p = join(here, "..", "scripts", "guard.py");
|
|
@@ -99,8 +110,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
99
110
|
const command = typeof input?.command === "string" ? input.command : undefined;
|
|
100
111
|
if (!command || !command.trim()) return undefined;
|
|
101
112
|
|
|
102
|
-
//
|
|
103
|
-
if (
|
|
113
|
+
// 快速预筛:不含破坏性动词时不启动子进程(省掉 python 探测和 ~50ms)
|
|
114
|
+
if (!QUICK_PREDICATE.test(command)) {
|
|
104
115
|
return undefined;
|
|
105
116
|
}
|
|
106
117
|
|