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.
@@ -0,0 +1,924 @@
1
+ """Platform-neutral judging core: tokenizer, intent extraction, disk probing.
2
+
3
+ Split from windows-delete-guard 0.1.0 guard.py; rule tables live in the
4
+ rules/ subpackage, host differences in platform.py. Chinese user-facing
5
+ text is preserved verbatim from the original module.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ntpath
11
+ import os
12
+ import re
13
+ from dataclasses import dataclass, field
14
+
15
+ from .paths import (
16
+ DELETE_VERBS_POSIX,
17
+ DELETE_VERBS_PS,
18
+ DELETE_VERBS_WIN,
19
+ MOVE_VERBS,
20
+ PRIVILEGE_ESCALATORS,
21
+ RECURSIVE_LONG,
22
+ RECURSIVE_SHORT,
23
+ FORCE_LONG,
24
+ FORCE_SHORT,
25
+ SHELL_LAUNCHERS,
26
+ _CMD_FLAG_RE,
27
+ _REPARSE_ATTR,
28
+ _SHELL_VAR_RE,
29
+ has_cjk,
30
+ human_bytes,
31
+ is_ancestor_of_cwd,
32
+ is_drive_root,
33
+ cloud_tool_match,
34
+ glob_base_dir,
35
+ overwrite_risk,
36
+ is_wsl_windows_mount,
37
+ macos_home_special,
38
+ posix_system_prefix,
39
+ )
40
+ from .platform import host_name, is_wsl, unknowns_for_host
41
+ from .rules import RULES, VERDICT_ORDER
42
+
43
+ # cmd 多字母 flag(/MIR /PURGE /E /S /XD 等)。排除单字母白名单已覆盖的,
44
+ # 避免与 _CMD_FLAG_RE 语义重叠;/mnt、/usr 这类以元音开头的常见目录前缀
45
+ # 仍可能被误收 —— 但 is_flag_token 仅在删除/移动动词之后消费,且误收
46
+ # flag 只是把 flag 从 targets 里排除(不改变爆炸半径),方向是安全的。
47
+ _CMD_LONG_FLAG_RE = re.compile(r"^/[A-Za-z]{1,8}$")
48
+
49
+ # 大小写不敏感宿主:Windows(NTFS)与 macOS(APFS/HFS+ 默认不敏感)。
50
+ # Linux 通常敏感,但挂载的 Windows/macOS 卷除外 —— 后者声明为 unknown。
51
+ _CASE_INSENSITIVE_HOSTS = ("windows", "macos")
52
+
53
+
54
+ def case_insensitive_host() -> bool:
55
+ """当前宿主是否大小写不敏感。
56
+
57
+ 刻意做成函数而非模块常量:导入时求值会让 macOS 的 POSIX 逐级核对
58
+ 分支在本机永久不可测,也让测试无法模拟其他宿主。
59
+ """
60
+ return host_name() in _CASE_INSENSITIVE_HOSTS
61
+
62
+
63
+ @dataclass
64
+ class Token:
65
+ value: str
66
+ quoted: bool
67
+ quote_char: str | None = None
68
+
69
+
70
+ @dataclass
71
+ class ParsedCommand:
72
+ tokens: list[Token]
73
+ ambiguous: bool
74
+ ambiguous_reason: str | None = None
75
+ shell_layers: list[str] = field(default_factory=list)
76
+
77
+
78
+ @dataclass
79
+ class Hazard:
80
+ code: str
81
+ severity: str
82
+ why: str
83
+ evidence: str
84
+ detail: str = ""
85
+
86
+ def as_dict(self) -> dict:
87
+ return {
88
+ "code": self.code,
89
+ "severity": self.severity,
90
+ "why": self.why,
91
+ "evidence": self.evidence,
92
+ "detail": self.detail,
93
+ }
94
+
95
+
96
+ @dataclass
97
+ class BlastRadius:
98
+ target: str
99
+ exists: bool = False
100
+ is_dir: bool = False
101
+ files: int = 0
102
+ dirs: int = 0
103
+ bytes: int = 0
104
+ reparse_points: int = 0
105
+ truncated: bool = False
106
+ unreadable: int = 0
107
+ note: str = ""
108
+
109
+ def as_dict(self) -> dict:
110
+ return {
111
+ "target": self.target,
112
+ "exists": self.exists,
113
+ "is_dir": self.is_dir,
114
+ "files": self.files,
115
+ "dirs": self.dirs,
116
+ "bytes": self.bytes,
117
+ "bytes_human": human_bytes(self.bytes),
118
+ "reparse_points": self.reparse_points,
119
+ "truncated": self.truncated,
120
+ "unreadable": self.unreadable,
121
+ "note": self.note,
122
+ }
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # 命令解析
127
+ # ---------------------------------------------------------------------------
128
+
129
+
130
+ def tokenize(command: str) -> ParsedCommand:
131
+ """最小 shell 分词器。
132
+
133
+ 只做一件事:判断「能不能无歧义地认出目标」。认不出就报 ambiguous——
134
+ 这是刻意的,因为真实事故里,目标恰恰是在引号层间被悄悄改写的。
135
+ """
136
+ tokens: list[Token] = []
137
+ buf: list[str] = []
138
+ quoted = False
139
+ quote_char: str | None = None
140
+ i = 0
141
+ n = len(command)
142
+
143
+ def flush() -> None:
144
+ nonlocal buf, quoted, quote_char
145
+ if buf or quoted:
146
+ tokens.append(Token("".join(buf), quoted, quote_char))
147
+ buf = []
148
+ quoted = False
149
+ quote_char = None
150
+
151
+ while i < n:
152
+ ch = command[i]
153
+
154
+ if quote_char is None and ch in "\"'":
155
+ # 进入引号:如果前面已经有内容(非空且未加引号),视为同 token 内嵌引号
156
+ if buf and not quoted:
157
+ # 形如 D:\a"b c" —— 引号嵌在未加引号 token 中,属于歧义温床
158
+ pass
159
+ quote_char = ch
160
+ quoted = True
161
+ i += 1
162
+ continue
163
+
164
+ if quote_char is not None:
165
+ if ch == "\\" and quote_char == '"' and i + 1 < n and command[i + 1] in "\"\\":
166
+ # 反斜杠转义引号:这是最危险的一种,层间会二次解释
167
+ buf.append(command[i + 1])
168
+ i += 2
169
+ continue
170
+ if ch == quote_char:
171
+ quote_char = None
172
+ i += 1
173
+ # 引号闭合后如果紧跟非空白,继续积累(相邻拼接)
174
+ if i < n and command[i] not in " \t":
175
+ quoted = True
176
+ continue
177
+ flush()
178
+ continue
179
+ buf.append(ch)
180
+ i += 1
181
+ continue
182
+
183
+ if ch in " \t\n\r":
184
+ flush()
185
+ i += 1
186
+ continue
187
+
188
+ if ch == "\\" and i + 1 < n and command[i + 1] in "\"' ":
189
+ buf.append(command[i + 1])
190
+ i += 2
191
+ continue
192
+
193
+ buf.append(ch)
194
+ quoted = False
195
+ i += 1
196
+
197
+ if quote_char is not None:
198
+ return ParsedCommand(
199
+ tokens=tokens,
200
+ ambiguous=True,
201
+ ambiguous_reason=f"引号未闭合({quote_char})",
202
+ )
203
+
204
+ flush()
205
+
206
+ ambiguous = False
207
+ reason = None
208
+
209
+ text = command
210
+ # 引号层间转义:同时出现 shell 启动器与转义引号,是 H1 的温床
211
+ layers = detect_shell_layers(tokens)
212
+ if len(layers) >= 2 and '\\"' in text:
213
+ ambiguous = True
214
+ reason = "多层 shell 链中出现转义引号,目标参数会在层间被重新解释"
215
+
216
+ return ParsedCommand(tokens=tokens, ambiguous=ambiguous, ambiguous_reason=reason, shell_layers=layers)
217
+
218
+
219
+ def unwrap_launcher_text(command: str, tokens: list[Token]) -> tuple[str | None, list[str]]:
220
+ """若命令形如 `cmd /c "..."` / `powershell -Command "..."` / `wsl rm ...`,
221
+ 提取内层命令文本。返回 (内层文本, 经过的层);提取不出返回 (None, layers)。
222
+ """
223
+ if not tokens:
224
+ return None, []
225
+ first = tokens[0].value.lower().removesuffix(".exe")
226
+ if first not in SHELL_LAUNCHERS:
227
+ return None, []
228
+ layers = [first]
229
+ inner_idx = None
230
+ for i, t in enumerate(tokens[1:], start=1):
231
+ lv = t.value.lower()
232
+ if lv in {"/c", "/k", "-c", "-command", "--command", "--", "-e"}:
233
+ inner_idx = i + 1
234
+ break
235
+ if inner_idx is None:
236
+ for i, t in enumerate(tokens[1:], start=1):
237
+ if not is_flag_token(t.value):
238
+ inner_idx = i
239
+ break
240
+ if inner_idx is None or inner_idx >= len(tokens):
241
+ return None, layers
242
+
243
+ rest = tokens[inner_idx:]
244
+ return " ".join(t.value for t in rest), layers
245
+
246
+
247
+ def detect_shell_layers(tokens: list[Token]) -> list[str]:
248
+ layers = []
249
+ for tok in tokens:
250
+ base = ntpath.basename(tok.value.lower()).removesuffix(".exe")
251
+ if base in SHELL_LAUNCHERS:
252
+ layers.append(base)
253
+ return layers
254
+
255
+
256
+ def is_flag_token(v: str, cmd_verb: bool = False) -> bool:
257
+ """判断一个 token 是选项而不是路径目标。
258
+
259
+ 这里必须保守:误把路径当选项 → 漏判爆炸半径;误把选项当路径 → 噪声。
260
+ `/mnt/d`、`/usr/bin` 这类不会被判成选项。
261
+
262
+ cmd_verb:当前命令的动词是否属于 cmd 系(rd/del/robocopy/xcopy/move)。
263
+ 多字母 cmd flag(/MIR /E /PURGE)只在该语境下成立 —— POSIX 删除动词的
264
+ /usr /etc 是真实路径,绝不能当 flag 剔除。作为参数显式传递而非函数
265
+ 属性:属性会在并发判定(线程池跑 tool_call)时产生跨调用竞态。
266
+ """
267
+ if v.startswith(("./", "../")):
268
+ return False
269
+ if v.startswith("-") and not re.match(r"^-\d", v):
270
+ return True
271
+ # 单字母 cmd flag(/s /q /d)与多字母一样需要 cmd 系动词语境:
272
+ # POSIX 删除动词下的 /d /x 是真实路径(目录名恰好单字母合法存在)
273
+ if _CMD_FLAG_RE.match(v):
274
+ return cmd_verb
275
+ if _CMD_LONG_FLAG_RE.match(v) and cmd_verb:
276
+ return True
277
+ return False
278
+
279
+
280
+ @dataclass
281
+ class Intent:
282
+ verb: str | None
283
+ recursive: bool
284
+ force: bool
285
+ targets: list[str]
286
+ is_delete: bool
287
+ is_move: bool
288
+ wildcard: bool
289
+ escalated: bool
290
+
291
+
292
+ def extract_intent(parsed: ParsedCommand) -> Intent:
293
+ toks = [t.value for t in parsed.tokens]
294
+ lower = [t.lower() for t in toks]
295
+
296
+ verb = None
297
+ verb_index = -1
298
+ all_delete = DELETE_VERBS_WIN | DELETE_VERBS_PS | DELETE_VERBS_POSIX
299
+ for idx, t in enumerate(lower):
300
+ base = ntpath.basename(t).removesuffix(".exe")
301
+ if base in all_delete or t in all_delete:
302
+ verb = base
303
+ verb_index = idx
304
+ break
305
+
306
+ is_move = False
307
+ if verb is None:
308
+ for idx, t in enumerate(lower):
309
+ base = ntpath.basename(t).removesuffix(".exe")
310
+ if base in MOVE_VERBS or t in MOVE_VERBS:
311
+ verb = base
312
+ verb_index = idx
313
+ is_move = True
314
+ break
315
+
316
+ recursive = False
317
+ force = False
318
+
319
+ # find <path> ... -delete:-delete 是 find 谓词不是 shell 删除动词,
320
+ # 但语义就是递归删除命中项 —— 有 -delete 才当作删除意图处理。
321
+ # 目标取 find 之后的路径参数;-name 谓词里的 glob 由 wildcard 捕获。
322
+ # 无 -delete 的 find(-print/-ls)完全不进入删除判定。
323
+ if verb is None:
324
+ find_idx = next(
325
+ (i for i, t in enumerate(lower)
326
+ if ntpath.basename(t).removesuffix(".exe") == "find" or t == "find"),
327
+ -1,
328
+ )
329
+ if find_idx >= 0 and "-delete" in lower[find_idx:]:
330
+ verb = "find"
331
+ verb_index = find_idx
332
+ recursive = True
333
+ force = True
334
+ elif find_idx >= 0:
335
+ find_idx = -1 # find 存在但无 -delete:不设动词,flag 循环也跳过其谓词
336
+
337
+ # git 子命令:clean -f(强制清未跟踪)与 worktree remove(H4 事故原型)。
338
+ # verb_index 指向子动词本身,targets 从其后开始,避免把子命令词当路径。
339
+ if verb is None:
340
+ git_idx = next(
341
+ (i for i, t in enumerate(lower)
342
+ if ntpath.basename(t).removesuffix(".exe") == "git" or t == "git"),
343
+ -1,
344
+ )
345
+ if git_idx >= 0 and len(lower) > git_idx + 1:
346
+ sub = lower[git_idx + 1]
347
+ if sub == "clean":
348
+ rest = lower[git_idx + 2 :]
349
+ has_force = any(
350
+ t in {"-f", "-fd", "-fdx", "-fx", "--force"} or
351
+ (t.startswith("-") and not t.startswith("--")
352
+ and "f" in set(t.lstrip("-")))
353
+ for t in rest
354
+ )
355
+ has_dry = any(
356
+ t == "-n" or (t.startswith("-") and not t.startswith("--")
357
+ and "n" in set(t.lstrip("-")))
358
+ for t in rest
359
+ )
360
+ if has_force and not has_dry:
361
+ verb = "git clean -f"
362
+ verb_index = git_idx + 1
363
+ recursive = True
364
+ force = True
365
+ # -n 在场(哪怕同时有 -f)一律视为 dry-run,无害放行;
366
+ # 显式复位预设位,防止后续 flag 循环误叠加
367
+ elif sub == "worktree" and len(lower) > git_idx + 2 \
368
+ and lower[git_idx + 2] == "remove":
369
+ verb = "git worktree remove"
370
+ verb_index = git_idx + 2
371
+ recursive = True
372
+ force = True
373
+
374
+ # cmd 系动词认得多字母 /FLAG(/MIR /E);POSIX 动词不认
375
+ cmd_verb = verb in {"rd", "del", "robocopy", "xcopy", "move"}
376
+
377
+ # 提权判定(H10):删除动词之前出现 sudo/doas/su
378
+ escalated = False
379
+ if verb_index > 0:
380
+ escalated = any(t in PRIVILEGE_ESCALATORS for t in lower[:verb_index])
381
+
382
+ # 选项拆解:既要认 `-recursive` 这种长选项,也要认 `-rf` 这种合写短选项。
383
+ # (find/git 特化分支已预设 recursive/force,此处循环只做累加。)
384
+ for tok in lower:
385
+ # 工具特定镜像/删除语义(先于通用解析):
386
+ # robocopy /MIR —— 镜像复制:目标中源里没有的文件会被删除
387
+ # rsync --delete —— 使目标与源严格一致:多余文件删除
388
+ if tok in {"/mir", "/mirror"}:
389
+ recursive = True
390
+ force = True
391
+ if tok == "--delete":
392
+ recursive = True
393
+ force = True
394
+ if tok in {"/purge", "--prune-empty-dirs"}:
395
+ force = True
396
+ if tok in {f.lower() for f in RECURSIVE_LONG}:
397
+ recursive = True
398
+ elif tok in RECURSIVE_LONG:
399
+ recursive = True
400
+ elif tok.startswith("-") and not tok.startswith("--"):
401
+ body = tok.lstrip("-")
402
+ letters = set(body)
403
+ if letters & RECURSIVE_SHORT or body.lower() == "recursive":
404
+ recursive = True
405
+ if letters & FORCE_SHORT or body.lower() in {"force", "yes"}:
406
+ force = True
407
+ elif tok in FORCE_LONG or tok.lower() in FORCE_LONG:
408
+ force = True
409
+ elif _CMD_FLAG_RE.match(tok):
410
+ letter = tok[1]
411
+ if letter in RECURSIVE_SHORT:
412
+ recursive = True
413
+ if letter in FORCE_SHORT:
414
+ force = True
415
+
416
+ targets: list[str] = []
417
+ wildcard = False
418
+ if verb_index >= 0:
419
+ # find 的值谓词(-name/-iname/-path 的参数)不是删除目标
420
+ find_value_predicates = {"-name", "-iname", "-path", "-ipath",
421
+ "-regex", "-iregex", "-newer"}
422
+ skip_next = False
423
+ for tok in parsed.tokens[verb_index + 1 :]:
424
+ v = tok.value
425
+ if not v:
426
+ continue
427
+ if skip_next:
428
+ skip_next = False
429
+ continue
430
+ lv = v.lower()
431
+ if lv in find_value_predicates:
432
+ skip_next = True
433
+ continue
434
+ if is_flag_token(v, cmd_verb):
435
+ continue
436
+ targets.append(v)
437
+ if any(c in v for c in "*?"):
438
+ wildcard = True
439
+
440
+ # find -delete / git clean -f / git worktree remove 是合成删除意图:
441
+ # 不在 shell 删除动词表里,但消费端(judge_command)按删除语义处理。
442
+ destructive = verb in all_delete or verb in {
443
+ "find", "git clean -f", "git worktree remove",
444
+ }
445
+ return Intent(
446
+ verb=verb,
447
+ recursive=recursive,
448
+ force=force,
449
+ targets=targets,
450
+ is_delete=destructive,
451
+ is_move=is_move,
452
+ wildcard=wildcard,
453
+ escalated=escalated,
454
+ )
455
+
456
+
457
+ # ---------------------------------------------------------------------------
458
+ # 路径判定
459
+ # ---------------------------------------------------------------------------
460
+
461
+
462
+ def case_collision(path: str, windows_layout: bool | None = None) -> str | None:
463
+ """若路径的大小写与磁盘上的实际条目不一致但确实能解析到,返回实际路径。
464
+
465
+ NTFS/APFS 大小写不敏感 —— 这正是 D:\\CampusconnECT 删掉
466
+ D:\\CampusConnect 的原因(claude-code#60442)。
467
+
468
+ windows_layout 为 None 时按当前宿主推断,仅用于测试显式指定布局。
469
+ """
470
+ if not path or not case_insensitive_host():
471
+ return None
472
+ if windows_layout is None:
473
+ windows_layout = os.name == "nt"
474
+ # 逐级比对大小写:Windows 走盘符/反斜杠布局,macOS 走 POSIX 布局
475
+ if windows_layout:
476
+ drive, tail = ntpath.splitdrive(path)
477
+ segments = [s for s in tail.replace("/", "\\").split("\\") if s]
478
+ cur = drive + "\\" if drive else ""
479
+ root = cur or "."
480
+ else:
481
+ segments = [s for s in path.replace("\\", "/").split("/") if s]
482
+ cur = ""
483
+ root = "/"
484
+ for seg in segments:
485
+ try:
486
+ entries = os.listdir(cur or root)
487
+ except OSError:
488
+ return None
489
+ match = next((e for e in entries if e == seg), None)
490
+ if match is None:
491
+ ci = next((e for e in entries if e.lower() == seg.lower()), None)
492
+ if ci is not None:
493
+ return os.path.join(cur or root, ci)
494
+ return None
495
+ cur = os.path.join(cur, match)
496
+ return None
497
+
498
+
499
+ def walk_blast_radius(path: str, max_entries: int = 20000) -> BlastRadius:
500
+ br = BlastRadius(target=path)
501
+ if not os.path.exists(path):
502
+ br.note = "目标不存在(若命令仍会执行,说明路径在别处被改写过)"
503
+ return br
504
+ br.exists = True
505
+ br.is_dir = os.path.isdir(path)
506
+
507
+ if not br.is_dir:
508
+ try:
509
+ br.files = 1
510
+ br.bytes = os.lstat(path).st_size
511
+ except OSError:
512
+ br.unreadable += 1
513
+ return br
514
+
515
+ stack = [path]
516
+ seen = 0
517
+ while stack:
518
+ cur = stack.pop()
519
+ try:
520
+ with os.scandir(cur) as it:
521
+ for entry in it:
522
+ seen += 1
523
+ if seen > max_entries:
524
+ br.truncated = True
525
+ stack.clear()
526
+ break
527
+ try:
528
+ st = entry.stat(follow_symlinks=False)
529
+ except OSError:
530
+ br.unreadable += 1
531
+ continue
532
+ if _is_reparse(entry, st):
533
+ # 链接单独计数:它是穿透风险本体,不算普通文件
534
+ br.reparse_points += 1
535
+ continue
536
+ if entry.is_dir(follow_symlinks=False):
537
+ br.dirs += 1
538
+ stack.append(entry.path)
539
+ else:
540
+ br.files += 1
541
+ br.bytes += st.st_size
542
+ except OSError:
543
+ br.unreadable += 1
544
+
545
+ from .platform import host_name
546
+
547
+ if br.reparse_points and host_name() != "windows":
548
+ br.note = (
549
+ "在非 Windows 宿主上检测到疑似链接;NTFS junction 的 reparse 属性"
550
+ "在 WSL/9p 下可能不可见,结论仅供参考"
551
+ )
552
+ return br
553
+
554
+
555
+ def _is_reparse(entry: os.DirEntry, st: os.stat_result) -> bool:
556
+ if entry.is_symlink():
557
+ return True
558
+ attrs = getattr(st, "st_file_attributes", 0)
559
+ if attrs & _REPARSE_ATTR:
560
+ return True
561
+ return False
562
+
563
+
564
+ def is_mount_point(path: str) -> bool:
565
+ """Linux H12:目标是否为挂载点(/proc/mounts + os.path.ismount 双核对)。"""
566
+ if not os.path.isabs(path.replace("\\", "/")) and not os.path.exists(path):
567
+ return False
568
+ try:
569
+ if os.path.ismount(path):
570
+ return True
571
+ # ismount 对某些 FUSE/NFS 挂载可能漏报,补一份 /proc/mounts 交叉核对
572
+ if os.name != "nt" and os.path.exists("/proc/mounts"):
573
+ real = os.path.realpath(path)
574
+ with open("/proc/mounts", encoding="utf-8", errors="replace") as f:
575
+ for line in f:
576
+ fields = line.split()
577
+ if len(fields) >= 2:
578
+ mp = fields[1].replace("\\040", " ").replace("\\011", "\t")
579
+ if mp == real or mp == path:
580
+ return True
581
+ except OSError:
582
+ return False
583
+ return False
584
+
585
+
586
+ # ---------------------------------------------------------------------------
587
+ # 判定
588
+ # ---------------------------------------------------------------------------
589
+
590
+
591
+ def judge_command(
592
+ command: str,
593
+ cwd: str | None = None,
594
+ wsl_context: bool | None = None,
595
+ privileged_context: bool | None = None,
596
+ ) -> dict:
597
+ """wsl_context:外层命令是否经由 wsl 启动器进入。递归判定内层命令时
598
+ 必须继承(wsl rm -rf /mnt/... 的内层没有 wsl 字样,但语义上就是
599
+ 跨文件系统删除)。None 表示按宿主是否为 WSL 自行判定。
600
+
601
+ privileged_context:外层是否带提权(sudo/su/doas)。跨层时必须继承:
602
+ `sudo bash -c "rm ..."` 的内层没有 sudo 字样,但删除就是以 root 跑的。
603
+ """
604
+ if "\x00" in command:
605
+ # NUL 字节无法被任何 shell 执行,但能让下游 os.* 抛
606
+ # ValueError(embedded null byte) 使判定链崩溃 —— hook/扩展层
607
+ # fail-open 放行。显式拒绝而不是崩溃(fail-closed 的正确形态)。
608
+ return _result(
609
+ [Hazard(
610
+ code="H0_AMBIGUOUS",
611
+ severity="block",
612
+ why="命令含 NUL 字节,无法被任何 shell 无歧义执行",
613
+ evidence="posix/execve NUL semantics",
614
+ )],
615
+ [], [],
616
+ )
617
+ cwd = cwd or os.getcwd()
618
+ parsed = tokenize(command)
619
+ hazards: list[Hazard] = []
620
+ unknowns: list[str] = []
621
+
622
+ seen: set[tuple[str, str]] = set()
623
+
624
+ def add(code: str, detail: str = "") -> None:
625
+ if (code, detail) in seen:
626
+ return
627
+ seen.add((code, detail))
628
+ sev, why, ev = RULES[code]
629
+ hazards.append(Hazard(code=code, severity=sev, why=why, evidence=ev, detail=detail))
630
+
631
+ if parsed.ambiguous:
632
+ add("H0_AMBIGUOUS", parsed.ambiguous_reason or "")
633
+ return _result(hazards, [], unknowns)
634
+
635
+ # find <path> ... -exec <cmd> {} \; —— 内层命令递归判定
636
+ # (候选 13/0.6:-exec rm 是嵌套删除,判定器必须能看见)
637
+ layers_from_parse = parsed.shell_layers # parse 阶段已检出的跳转层
638
+ exec_match = re.search(r"-exec\s+(.+?)\s*\{\}\s*(?:\\;|\+)", command)
639
+ if exec_match and not layers_from_parse:
640
+ inner = exec_match.group(1).replace("{}", "<matched-file>")
641
+ inner_r = judge_command(inner, cwd, wsl_context, privileged_context)
642
+ # 容器危险:-exec 作用于 find 命中的每个文件(批量语义)
643
+ add("H8_GLOB_RECURSIVE", "-exec 批量执行:作用于 find 命中的所有文件")
644
+ return _merge_inner(hazards, unknowns, inner_r, ["find -exec"])
645
+
646
+ # 跨层执行:提取内层命令文本,递归判定,危险按层级累加。
647
+ inner_text, layers = unwrap_launcher_text(command, parsed.tokens)
648
+ if layers:
649
+ if inner_text is None:
650
+ add("H0_AMBIGUOUS", f"经 {layers[0]} 跳转的命令无法无歧义地提取内层目标")
651
+ return _result(hazards, [], unknowns)
652
+ if any(
653
+ (" " in t.value or has_cjk(t.value)) and t.quoted for t in parsed.tokens
654
+ ):
655
+ add(
656
+ "H1_QUOTE_CHAIN",
657
+ f"目标带引号且含空格/CJK,经 {' -> '.join(layers)} 跳转时"
658
+ "参数会在层间被重新解释",
659
+ )
660
+ lower_layers = [l.lower() for l in layers]
661
+ inner_wsl = (
662
+ wsl_context
663
+ if wsl_context is not None
664
+ else "wsl" in lower_layers
665
+ )
666
+ inner_priv = (
667
+ privileged_context
668
+ if privileged_context is not None
669
+ else any(l in PRIVILEGE_ESCALATORS for l in lower_layers)
670
+ )
671
+ return _merge_inner(
672
+ hazards,
673
+ unknowns,
674
+ judge_command(inner_text, cwd, inner_wsl, inner_priv),
675
+ layers,
676
+ )
677
+
678
+ intent = extract_intent(parsed)
679
+
680
+ # 一次额外 shell 跳转就是一次重新解释的机会。
681
+ # 宿主本身那层不算:纯 `rm -rf ./build` 不该被这条规则打。
682
+ if parsed.shell_layers and (intent.is_delete or intent.is_move):
683
+ risky_chars = any((" " in t or has_cjk(t)) for t in intent.targets)
684
+ has_quote = any(t.quoted for t in parsed.tokens)
685
+ if risky_chars and has_quote:
686
+ add(
687
+ "H1_QUOTE_CHAIN",
688
+ f"经 {' -> '.join(parsed.shell_layers)} 多一跳;"
689
+ f"目标含空格/CJK 且带引号:{intent.targets}",
690
+ )
691
+
692
+ if (
693
+ not intent.targets
694
+ and (intent.is_delete or intent.is_move)
695
+ and intent.verb != "git clean -f" # 无路径参数 = 默认当前目录,合法形态
696
+ ):
697
+ add("H0_AMBIGUOUS", "识别到破坏性动词但未解析出任何目标")
698
+
699
+ # H10 提权删除:动词前有提权词,或外层继承来的提权语境
700
+ if privileged_context is None:
701
+ privileged_context = intent.escalated
702
+ if privileged_context and (intent.is_delete or intent.is_move):
703
+ add(
704
+ "H10_SUDO_DELETE",
705
+ f"提权({intent.verb} 前有 sudo/doas/su)执行 {intent.verb}",
706
+ )
707
+
708
+ # H6 只在 WSL 语境下成立:宿主本身是 WSL,或命令经 wsl 启动器跳转。
709
+ # 原生 Linux 上 /mnt 下可能是任意普通挂载,交由 H12 按真实挂载表判定。
710
+ if wsl_context is None:
711
+ wsl_context = is_wsl() or "wsl" in [
712
+ l.lower() for l in parsed.shell_layers
713
+ ]
714
+
715
+ # H15 覆盖型销毁(命令级判定;需要目标存在性核对,仅在真实 FS 上有效)
716
+ ow_hit = overwrite_risk(command)
717
+ if ow_hit:
718
+ add("H15_OVERWRITE", ow_hit)
719
+
720
+ # H14 云/容器/ORM/SQL 工具的破坏性动词(命令级判定)
721
+ cloud_hit = cloud_tool_match(command)
722
+ if cloud_hit:
723
+ shape, evidence = cloud_hit
724
+ # kubectl delete namespace / terraform destroy / DROP DATABASE:
725
+ # 官方确认不可逆或级联全删 → block;其余(卷/表级)→ warn
726
+ block_shapes = (
727
+ "kubectl delete namespace", "kubectl delete ns",
728
+ "terraform destroy", "pulumi destroy",
729
+ "sql drop/truncate",
730
+ "kiro environment delete",
731
+ )
732
+ # 级别:block 形态通过独立 Hazard 覆盖 severity(RULES 表里 H14 默认 warn)
733
+ detail = (
734
+ f"{shape!r} 官方确认不可逆/级联删除"
735
+ if shape in block_shapes
736
+ else f"{shape!r} 删除持久数据(可能有备份)"
737
+ )
738
+ add("H14_CLOUD_TOOLING", detail)
739
+ if shape in block_shapes:
740
+ hazards[-1].severity = "block"
741
+ # 事故依据进 evidence(动态命中形态专属依据与规则表依据合并)
742
+ hazards[-1].evidence = f"{evidence}"
743
+
744
+ # 无目标的合成破坏性动词(git clean -f 默认当前目录):H9 在循环外补发
745
+ if (
746
+ not intent.targets
747
+ and intent.is_delete
748
+ and intent.force
749
+ and intent.recursive
750
+ ):
751
+ add(
752
+ "H9_PERMANENT_DELETE",
753
+ f"{intent.verb}(默认当前目录)递归强制清理,不进回收站",
754
+ )
755
+
756
+ radii: list[BlastRadius] = []
757
+ for target in intent.targets:
758
+ radii.append(walk_blast_radius(target))
759
+
760
+ if is_drive_root(target):
761
+ add("H2_DRIVE_ROOT", f"目标 {target!r} 是卷根")
762
+
763
+ real = case_collision(target)
764
+ if real and os.path.normcase(real) != os.path.normcase(target):
765
+ add("H3_CASE_COLLISION", f"{target!r} 实际指向已存在的 {real!r}")
766
+
767
+ br = radii[-1]
768
+ if br.reparse_points and intent.recursive:
769
+ add(
770
+ "H4_REPARSE_TRAVERSAL",
771
+ f"{target!r} 子树内有 {br.reparse_points} 个链接,递归删除会穿透",
772
+ )
773
+
774
+ if has_cjk(target):
775
+ add("H5_CJK_SILENT_FAIL", f"目标含 CJK:{target!r}")
776
+
777
+ if wsl_context and is_wsl_windows_mount(target):
778
+ add("H6_WSL_CROSS_FS", f"目标在 Windows 挂载点:{target!r}")
779
+
780
+ if is_ancestor_of_cwd(target, cwd):
781
+ add("H7_ANCESTOR_OF_CWD", f"{target!r} 是 cwd {cwd!r} 的祖先或本身")
782
+
783
+ if intent.wildcard and intent.recursive:
784
+ add("H8_GLOB_RECURSIVE", f"递归 + 通配符:{target!r}")
785
+ # glob 爆炸半径预判(Steam 2015:rm -rf "$STEAMROOT/"* -> /*):
786
+ # 命中范围在执行前无法静态确定,必须按前缀可确定性分档。
787
+ base = glob_base_dir(target)
788
+ if base is None:
789
+ pass # 非通配目标,不适用
790
+ elif base == "":
791
+ add(
792
+ "H0_AMBIGUOUS",
793
+ f"{target!r} 的通配符无可确定前缀(变量可能为空/相对根),"
794
+ "展开范围完全未知 —— Steam 2015 事故形态",
795
+ )
796
+ else:
797
+ # 前缀本身命中卷根或系统前缀:展开必然波及
798
+ if is_drive_root(base):
799
+ add("H2_DRIVE_ROOT", f"通配目标 {target!r} 的前缀 {base!r} 是卷根")
800
+ sysp = posix_system_prefix(base)
801
+ if sysp:
802
+ add("H11_SYSTEM_PREFIX", f"通配目标 {target!r} 的前缀命中 {sysp}")
803
+
804
+ mirror_semantics = intent.verb in {"robocopy", "rsync"} and intent.force
805
+ if (
806
+ (intent.is_delete or mirror_semantics)
807
+ and intent.force
808
+ and intent.recursive
809
+ ):
810
+ add(
811
+ "H9_PERMANENT_DELETE",
812
+ f"{intent.verb} {'镜像同步' if mirror_semantics else '递归强制删除'}"
813
+ "会删除目标侧多余文件,不进回收站",
814
+ )
815
+
816
+ # 目标含未展开的 shell/cmd 变量:真实路径执行前不可知
817
+ # (Steam 2015:$STEAMROOT 为空,rd 落到上层)
818
+ if _SHELL_VAR_RE.search(target):
819
+ add(
820
+ "H0_AMBIGUOUS",
821
+ f"目标 {target!r} 含未展开变量,真实路径在执行前不可知",
822
+ )
823
+
824
+ # H11 系统关键前缀(含变量退化形态,如空变量后剩余的 /*)
825
+ sys_prefix = posix_system_prefix(target)
826
+ if sys_prefix and intent.recursive:
827
+ add("H11_SYSTEM_PREFIX", f"{target!r} 命中系统前缀 {sys_prefix}")
828
+
829
+ # H12 挂载点
830
+ if intent.recursive and is_mount_point(target):
831
+ add("H12_MOUNT_POINT", f"{target!r} 是挂载点,删除作用于整个卷")
832
+
833
+ # H13 macOS 家目录特殊目录
834
+ special = macos_home_special(target)
835
+ if special:
836
+ add("H13_MACOS_HOME_SPECIAL", f"{target!r} 命中 macOS 家目录特殊目录 {special}")
837
+
838
+ unknowns.extend(unknowns_for_host())
839
+ if any(br.truncated for br in radii):
840
+ unknowns.append("爆炸半径统计已达上限,实际文件数更多")
841
+
842
+ return _result(hazards, radii, unknowns)
843
+
844
+
845
+ def judge_path(path: str, cwd: str | None = None) -> dict:
846
+ cwd = cwd or os.getcwd()
847
+ hazards: list[Hazard] = []
848
+ unknowns: list[str] = []
849
+
850
+ seen: set[tuple[str, str]] = set()
851
+
852
+ def add(code: str, detail: str = "") -> None:
853
+ if (code, detail) in seen:
854
+ return
855
+ seen.add((code, detail))
856
+ sev, why, ev = RULES[code]
857
+ hazards.append(Hazard(code=code, severity=sev, why=why, evidence=ev, detail=detail))
858
+
859
+ if is_drive_root(path):
860
+ add("H2_DRIVE_ROOT", f"{path!r} 是卷根")
861
+ real = case_collision(path)
862
+ if real and os.path.normcase(real) != os.path.normcase(path):
863
+ add("H3_CASE_COLLISION", f"{path!r} 实际指向已存在的 {real!r}")
864
+ if has_cjk(path):
865
+ add("H5_CJK_SILENT_FAIL", f"路径含 CJK:{path!r}")
866
+ if is_wsl() and is_wsl_windows_mount(path):
867
+ add("H6_WSL_CROSS_FS", f"路径在 Windows 挂载点:{path!r}")
868
+ if is_ancestor_of_cwd(path, cwd):
869
+ add("H7_ANCESTOR_OF_CWD", f"{path!r} 是 cwd {cwd!r} 的祖先或本身")
870
+
871
+ br = walk_blast_radius(path)
872
+ if br.reparse_points:
873
+ add("H4_REPARSE_TRAVERSAL", f"{path!r} 子树内有 {br.reparse_points} 个链接")
874
+
875
+ sys_prefix = posix_system_prefix(path)
876
+ if sys_prefix:
877
+ add("H11_SYSTEM_PREFIX", f"{path!r} 命中系统前缀 {sys_prefix}")
878
+ if is_mount_point(path):
879
+ add("H12_MOUNT_POINT", f"{path!r} 是挂载点")
880
+ special = macos_home_special(path)
881
+ if special:
882
+ add("H13_MACOS_HOME_SPECIAL", f"{path!r} 命中 macOS 家目录特殊目录 {special}")
883
+
884
+ unknowns.extend(unknowns_for_host())
885
+
886
+ return _result(hazards, [br], unknowns)
887
+
888
+
889
+ def _merge_inner(
890
+ outer_hazards: list[Hazard],
891
+ outer_unknowns: list[str],
892
+ inner: dict,
893
+ layers: list[str],
894
+ ) -> dict:
895
+ """合并外层危险与内层判定结果。内层 verdict 升级外层。"""
896
+ merged = dict(inner)
897
+ inner_hazards = [Hazard(**h) for h in inner.get("hazards", [])]
898
+ all_hazards = outer_hazards + inner_hazards
899
+ verdict = inner.get("verdict", "allow")
900
+ for h in outer_hazards:
901
+ if VERDICT_ORDER[h.severity] > VERDICT_ORDER[verdict]:
902
+ verdict = h.severity
903
+ merged["hazards"] = [h.as_dict() for h in all_hazards]
904
+ merged["verdict"] = verdict
905
+ merged["unknowns"] = list(
906
+ dict.fromkeys(list(inner.get("unknowns", [])) + outer_unknowns)
907
+ )
908
+ # 跨层命令的爆炸半径以内层为准(外层只是转发)
909
+ if not merged.get("blast_radius"):
910
+ merged["blast_radius"] = []
911
+ return merged
912
+
913
+
914
+ def _result(hazards: list[Hazard], radii: list[BlastRadius], unknowns: list[str]) -> dict:
915
+ verdict = "allow"
916
+ for h in hazards:
917
+ if VERDICT_ORDER[h.severity] > VERDICT_ORDER[verdict]:
918
+ verdict = h.severity
919
+ return {
920
+ "verdict": verdict,
921
+ "hazards": [h.as_dict() for h in hazards],
922
+ "blast_radius": [r.as_dict() for r in radii],
923
+ "unknowns": unknowns,
924
+ }