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