delete-guard-agent 0.6.0 → 0.6.2

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 CHANGED
@@ -138,6 +138,7 @@ python scripts/guard.py command "rm -rf /mnt/d/data" --json
138
138
  | H15 | 覆盖型销毁(通配 mv/cp 落入已存在目录、`>` 重定向清空非空文件) | 全平台 | warn |
139
139
  | H16 | 目标是家目录根(`/home`、`/root`、`/home/<u>`、`/Users/<u>`、`C:\Users\<u>`) | 全平台 | block |
140
140
  | H17 | 目标是凭据/密钥目录或文件(`.ssh` `.aws` `.gnupg` `.kube` `.docker` `.config/gh`、`id_rsa`、`.netrc`…) | 全平台 | block |
141
+ | H18 | git 还原/重置类动词(`reset --hard`、`restore <pathspec>`、`checkout --`、`stash clear/drop`、`gc --prune=now`、`reflog expire --expire=now`) | 全平台 | warn |
141
142
 
142
143
  ## 代码结构(0.2 起拆包;0.3 起 find/git 意图在 core.py 内原生解析)
143
144
 
@@ -170,7 +171,7 @@ python -m unittest discover tests -v
170
171
  以下项已由 CI 的 `ubuntu-latest` / `windows-latest` / `macos-latest` runner
171
172
  或真机 E2E 覆盖:
172
173
 
173
- - [x] 单元测试(140 个,含 H3/H4/H11-H15/find/git 断言、中文社区与第四轮事故回归、预筛一致性比对、过度拦截反例)在
174
+ - [x] 单元测试(145 个,含 H3/H4/H11-H18/find/git 断言、中文社区与第四/五轮事故回归、预筛一致性比对、过度拦截反例)在
174
175
  ubuntu + windows + macos 三个 runner 上跑
175
176
  - [x] macOS 真机回归(H3 APFS 大小写、H13 家目录特殊目录)——由
176
177
  `macos-latest` runner 真机执行,不再是仅静态判定
package/SKILL.md CHANGED
@@ -55,6 +55,13 @@ description: Use before running ANY destructive file operation (rm -rf, rd /s /q
55
55
  claude-code#83058(~200GB 家目录)、STUPID-2026-0128(SSH/AWS/GH 凭据全毁)、
56
56
  deepseek-harness#13675(%USERPROFILE% 下 86k 文件)。清理"缓存/临时文件"时,
57
57
  路径必须显式落在具体项目目录内,且不得向上用 `..` 或家目录变量兜底。
58
+ 10. **“恢复”动作比事故本身更容易毁掉剩下的东西(判定器 H18)。**
59
+ `git reset --hard`、`git restore <pathspec>`、`git checkout -- .`、
60
+ `git stash clear/drop`、`git gc --prune=now`、`git reflog expire --expire=now`
61
+ 都不删路径,只把工作树与 index 写回 —— 未提交改动与未跟踪文件瞬间不可恢复。
62
+ 事故现场还在时先停手:先 `git stash push` 或把目录整体复制一份,再谈清理。
63
+ claude-code#84829 里 agent 正是一次目录作用域的 `git restore`
64
+ 把另一个 agent 的 rm 事故现场一起还原掉了,而它刚陈述过 bulk-op 教训。
58
65
 
59
66
  ## 操作流程
60
67
 
@@ -45,7 +45,7 @@ RELEVANT_TOOLS = {"Bash", "PowerShell"}
45
45
  QUICK_PREDICATE_SRC = (
46
46
  r"(?:\b(?:rm|rmdir|del|erase|rd|unlink|shred|trash|remove-item|ri|move-item|"
47
47
  r"mv|move|sudo|doas|su)\b)"
48
- r"|(?:\bgit\s+(?:clean|worktree|rm)\b)"
48
+ r"|(?:\bgit\s+(?:clean|worktree|rm|reset|restore|checkout|stash|gc|reflog)\b)"
49
49
  r"|(?:\bfind\b[^|;]*?-delete\b)"
50
50
  r"|(?:\b(?:docker|terraform|pulumi|kubectl|prisma|alembic|drizzle|railway|"
51
51
  r"gcloud|supabase|neon|kiro|psql|mysql|mariadb|sqlite3|sqlcmd|aws)\b)"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "delete-guard-agent",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
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",
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
  import ntpath
11
11
  import os
12
12
  import re
13
+ import time
13
14
  from dataclasses import dataclass, field
14
15
 
15
16
  from .paths import (
@@ -28,6 +29,7 @@ from .paths import (
28
29
  SHELL_LAUNCHERS,
29
30
  analysis_path,
30
31
  cloud_tool_match,
32
+ git_destructive_match,
31
33
  glob_base_dir,
32
34
  has_cjk,
33
35
  home_destruction,
@@ -501,7 +503,9 @@ def case_collision(path: str, windows_layout: bool | None = None) -> str | None:
501
503
  return None
502
504
 
503
505
 
504
- def walk_blast_radius(path: str, max_entries: int = 20000) -> BlastRadius:
506
+ def walk_blast_radius(
507
+ path: str, max_entries: int = 20000, time_budget_s: float = 0.15
508
+ ) -> BlastRadius:
505
509
  br = BlastRadius(target=path)
506
510
  if not os.path.exists(path):
507
511
  br.note = "目标不存在(若命令仍会执行,说明路径在别处被改写过)"
@@ -519,7 +523,15 @@ def walk_blast_radius(path: str, max_entries: int = 20000) -> BlastRadius:
519
523
 
520
524
  stack = [path]
521
525
  seen = 0
526
+ # 时间预算:爆炸半径只作参考信息、不参与 verdict 分级,而判定跑在 hook
527
+ # 的同步路径上。WSL/9p 这类慢文件系统上单次 stat 可达毫秒级,
528
+ # `rm -rf ../..` 曾耗时 6-19s(INCIDENTS.md 第五轮结论)。超预算即截断,
529
+ # 宁可报“统计已截断”也不能拖住 agent。
530
+ deadline = time.monotonic() + time_budget_s
522
531
  while stack:
532
+ if time.monotonic() > deadline:
533
+ br.truncated = True
534
+ break
523
535
  cur = stack.pop()
524
536
  try:
525
537
  with os.scandir(cur) as it:
@@ -749,6 +761,15 @@ def judge_command(
749
761
  # 事故依据进 evidence(动态命中形态专属依据与规则表依据合并)
750
762
  hazards[-1].evidence = f"{evidence}"
751
763
 
764
+ # H18 git 还原/重置类动词(命令级判定):reset --hard / restore <pathspec>
765
+ # / checkout -- / stash clear / gc --prune=now —— 不删路径,只把工作树
766
+ # 写回 index,未提交改动与未跟踪文件瞬间不可恢复。
767
+ git_hit = git_destructive_match(command)
768
+ if git_hit:
769
+ shape, evidence = git_hit
770
+ add("H18_GIT_DESTRUCTIVE", repr(shape) + " 把工作树写回 index,未提交改动不可恢复")
771
+ hazards[-1].evidence = evidence
772
+
752
773
  # 无目标的合成破坏性动词(git clean -f 默认当前目录):H9 在循环外补发
753
774
  if (
754
775
  not intent.targets
@@ -466,6 +466,102 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
466
466
  return None
467
467
 
468
468
 
469
+ # git 的还原/重置类动词:不删路径,只把工作树与 index 写回。
470
+ # 它们不在任何"删除"词表里,却是事故后二次毁灭的主力动作
471
+ # (INCIDENTS.md 候选 32/33:claude-code#84829 用 git restore 把另一个
472
+ # agent 的 rm 事故现场一起还原掉)。
473
+ _GIT_SEG_SPLIT = re.compile(r"&&|\|\||;|\n|\|")
474
+ _GIT_GLOBAL_FLAGS_WITH_ARG = {"-c", "-C", "--git-dir", "--work-tree", "--namespace"}
475
+
476
+
477
+ def _git_segments(norm: str) -> list[list[str]]:
478
+ """把命令拆成 shell 段,返回每段里 git 之后的子命令 token 列表。"""
479
+ out: list[list[str]] = []
480
+ for seg in _GIT_SEG_SPLIT.split(norm):
481
+ toks = seg.split()
482
+ for i, tok in enumerate(toks):
483
+ base = tok.replace("\\", "/").rsplit("/", 1)[-1]
484
+ if base in {"git", "git.exe"}:
485
+ out.append(toks[i + 1 :])
486
+ break
487
+ return out
488
+
489
+
490
+ def _git_sub_destructive(rest: list[str]) -> tuple[str, str] | None:
491
+ """单个 git 段的破坏性判定;rest 为 git 之后的 token(保留大小写)。"""
492
+ idx = 0
493
+ # 跳过 -C <path> / -c key=value 这类带参数的全局选项
494
+ while idx < len(rest) and rest[idx] in _GIT_GLOBAL_FLAGS_WITH_ARG:
495
+ idx += 2
496
+ while idx < len(rest) and rest[idx].startswith("-"):
497
+ idx += 1
498
+ if idx >= len(rest):
499
+ return None
500
+ sub = rest[idx].lower()
501
+ args = rest[idx + 1 :]
502
+
503
+ if sub == "reset":
504
+ mode = next((a for a in args if a in {"--hard", "--merge", "--keep"}), None)
505
+ if mode:
506
+ return "git reset " + mode, "claude-code#84829, gist yurukusa 恢复指南"
507
+ return None
508
+
509
+ if sub == "restore":
510
+ # -S/--staged 单独出现只动 index(可反悔);-s/--source 与
511
+ # -W/--worktree 都会把工作树写回,是真正的销毁形态。
512
+ # 注意大小写:git 的 -S 与 -s 语义相反,判定前不能统一小写。
513
+ staged = any(a in {"--staged", "-S"} for a in args)
514
+ worktree = any(a in {"--worktree", "-W"} for a in args)
515
+ source = any(
516
+ a == "--source" or a.startswith("--source=") or a == "-s" for a in args
517
+ )
518
+ if not args or (staged and not worktree and not source):
519
+ return None
520
+ return "git restore <pathspec>", "claude-code#84829"
521
+
522
+ if sub == "checkout":
523
+ # checkout -- <path> / checkout . / checkout -f:把工作树写回 index
524
+ if "--" in args:
525
+ return "git checkout -- <pathspec>", "claude-code#84829"
526
+ if any(a in {"-f", "--force"} for a in args):
527
+ return "git checkout -f", "claude-code#84829"
528
+ # 无分支名、只给路径(. 或 ./ 或 :/):git 视为还原工作树
529
+ pathspecs = [a for a in args if not a.startswith("-")]
530
+ if pathspecs and all(p in {".", "./", ":/", ".."} for p in pathspecs):
531
+ return "git checkout " + pathspecs[0], "claude-code#84829"
532
+ return None
533
+
534
+ if sub == "stash" and args and args[0].lower() in {"clear", "drop"}:
535
+ return "git stash " + args[0].lower(), "claude-code#84829, gist yurukusa 恢复指南"
536
+
537
+ if sub == "gc" and any(a == "--prune=now" or a == "--prune" for a in args):
538
+ # --prune=now 把不可达对象立即清掉,reflog 兜底路径失效
539
+ return "git gc --prune=now", "gist yurukusa 恢复指南"
540
+
541
+ if sub == "reflog" and args and args[0].lower() == "expire" and any(
542
+ a in {"--expire=now", "--expire-unreachable=now"} for a in args
543
+ ):
544
+ return "git reflog expire --expire=now", "gist yurukusa 恢复指南"
545
+
546
+ return None
547
+
548
+
549
+ def git_destructive_match(command: str) -> tuple[str, str] | None:
550
+ """H18:git 还原/重置类破坏性动词。返回 (命中形态, 事故依据) 或 None。"""
551
+ # 保留大小写:git 的 -S(--staged)与 -s(--source)语义相反
552
+ norm = _norm_cmd_preserve_case(command)
553
+ # 只读勘察命令里的命中词只是被搜索的文本(`git log --grep="reset --hard"`)
554
+ if _readonly_head(norm):
555
+ return None
556
+ if "--help" in norm or " -h " in norm:
557
+ return None
558
+ for rest in _git_segments(norm):
559
+ hit = _git_sub_destructive(rest)
560
+ if hit:
561
+ return hit
562
+ return None
563
+
564
+
469
565
  def glob_base_dir(path: str) -> str | None:
470
566
  """返回 glob 目标的「可确定前缀」目录:从最右段开始剥掉通配符所在段。
471
567
 
@@ -75,4 +75,18 @@ RULES_COMMON: dict[str, tuple[str, str, str]] = {
75
75
  "STUPID-2026-0128 (SSH/AWS/GH credentials destroyed), "
76
76
  "deepseek-harness#13675 (~/.ssh wiped)",
77
77
  ),
78
+ # H18:git 还原/重置类动词 —— 不删路径,只把工作树与 index 写回,
79
+ # 未提交改动与未跟踪文件瞬间不可恢复。任何以"是否删除路径"为中心的
80
+ # 规则都看不见它,而它正是事故后二次毁灭的主力动作。事故链见
81
+ # INCIDENTS.md 候选 32/33(claude-code#84829 用目录作用域的 git restore
82
+ # 把另一个 agent 的 rm 事故现场一起还原掉)。
83
+ "H18_GIT_DESTRUCTIVE": (
84
+ "warn",
85
+ "git 还原/重置类动词(reset --hard、restore <pathspec>、"
86
+ "checkout --、stash clear/drop、gc --prune=now)不删路径,只把"
87
+ "工作树与 index 写回 —— 未提交改动与未跟踪文件不可恢复,"
88
+ "且常被当作事故后的「恢复动作」执行",
89
+ "claude-code#84829 (git restore wiped uncommitted work), "
90
+ "gist yurukusa 恢复指南 (#64615 /rewind, #46444 worktree)",
91
+ ),
78
92
  }
package/src/extension.ts CHANGED
@@ -31,7 +31,7 @@ const GUARD_TIMEOUT_MS = 5_000;
31
31
  * 形同虚设,而它们恰好是唯一 block 级的云/数据层保护。
32
32
  */
33
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;
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|reset|restore|checkout|stash|gc|reflog)\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
35
 
36
36
  function guardScript(): string | null {
37
37
  const here = dirname(fileURLToPath(import.meta.url));