fix(harness): main checkout 안 worktree를 통째로 지우는 rm을 막는다
문제: H12는 cwd의 main checkout도 rm 허용 폴더에 넣는다. 그래서 main checkout 안 worktree(.claude/worktrees/…)에서 worktree 자신 (`rm -rf ./*`), 옆 worktree(`rm -rf ../w2`), 그 안(`../w2/src`)을 지우는 것이 통과한다(docs/retro/2026-11-08.md C6). 앱은 worktree 세션의 CLAUDE_PROJECT_DIR를 main checkout으로 주므로 실제 세션이 이 경우다. 고친 방법: 허용 폴더는 그대로 두고 지킬 checkout을 따로 센다. 작업 폴더와 그 repo에 `git worktree list`로 등록된 모든 worktree다. /tmp·앱 임시 작업 폴더 밖에서는 checkout 자신이나 그것을 품은 폴더를 통째로 지우면 막는다. 이 세션 작업 폴더와 같지도, 품지도, 그 안에 있지도 않은 checkout(옆 worktree)은 그 안을 지워도 막는다. 「이 세션 작업 폴더」는 cwd의 checkout을 먼저 본다. 프로젝트 폴더를 먼저 보면 main checkout이 내 것이 되어 옆 worktree 안이 열린다(실제 세션에서 확인). main checkout 안 다른 자리(worktree 밖)와 main checkout 세션이 worktree 안을 치우는 일은 전처럼 통과한다. 버린 대안: worktree 세션에서 main checkout을 허용 폴더에서 빼기(설계 문구에는 맞지만 지금 통과하는 일을 더 많이 막는다. 근거 없이 넓히지 않았다), `.claude/worktrees` 이름으로 판정(다른 곳에 둔 worktree를 놓친다). 위험: 판정마다 git을 한 번 더 부른다(`worktree list`, 시간 제한 5초). 등록되지 않은 폴더(지운 worktree의 남은 폴더)는 지켜지지 않는다. /tmp 아래 worktree는 일부러 그대로 허용한다. 훅 동작이 바뀌어 harness 0.3.1로 올린다. 같은 판정이 전역 ~/.claude/hooks/guard_bash.py 에도 있어 같이 고쳤다. 이 repo가 병합되고 main checkout을 받고 플러그인을 0.3.1로 올리기 전까지 전역 훅 시험의 사본 비교 2줄은 다르다고 나온다. 검증: 새 시험을 main 훅에 돌려 실패를 먼저 봤다(worktree `./*`, main checkout `.claude/worktrees`, 프로젝트 폴더가 main일 때 `../w2/src`). 고친 뒤 scripts/check.sh 통과(harness 28·redteam 21· 템플릿 11, expectedFailure 없음). 새 규칙 둘을 하나씩 끄면 각각 시험이 실패한다. 소유자 기계 세션 기록의 rm -r 647개를 프로젝트 폴더 없이, 또 main checkout으로 주고 옛·새 판정을 비교해 바뀐 것은 이 작업의 확인 명령 1개뿐이었다. Refs: docs/retro/2026-11-08.md C6
This commit is contained in:
@@ -7,6 +7,9 @@
|
||||
보내는 force push는 운반이라 통과하되, 보호 브랜치를 덮거나 대상 ref가 없으면 막는다.
|
||||
- `rm -r`: 대상이 이 세션의 git 작업 폴더·/tmp·앱 임시 작업 폴더 밖이거나, 너무 넓다
|
||||
(`/`, `~`, `~/workspace/<묶음>`, `.git`, 빈 변수로 `/`가 되는 경로, `폴더/*`로 작업 폴더를 통째 비움).
|
||||
작업 폴더 안이라도 git checkout(등록된 worktree 포함)이나 그것을 품은 폴더를 통째로 지우거나, 옆 worktree
|
||||
안을 지우면 막는다(main checkout 안 worktree에서 `rm -rf ./*`, `rm -rf ../옆-worktree`, `rm -rf ../옆-worktree/src`).
|
||||
/tmp·앱 임시 작업 폴더 아래는 예외다.
|
||||
- DB·볼륨·migration 삭제: SQL 클라이언트의 DROP DATABASE·SCHEMA·TABLE·TRUNCATE, redis FLUSHALL·FLUSHDB,
|
||||
flyway clean·flywayClean, liquibase drop-all, `-p` 없는 compose `down -v`, `volume rm|prune`,
|
||||
`system prune --volumes`, `kubectl delete pvc|pv|ns`.
|
||||
@@ -410,6 +413,7 @@ VAR_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)([^}]*)\}|([A-Za-z_][A-Za-z
|
||||
OPAQUE = "\x00" # 명령 치환처럼 값을 알 수 없지만 비지 않는 값
|
||||
H12_HOME = os.path.expanduser("~")
|
||||
H12_TMP = "/tmp/claude-%d" % os.getuid()
|
||||
H12_TEMP_ROOTS = ("/tmp", os.path.join(H12_HOME, ".config", "Claude", "scratch-workspaces"))
|
||||
H12_HOME_KEEP = {".ssh", ".config", ".local", ".claude", ".gradle", ".m2", ".cache", ".kube", ".docker",
|
||||
"workspace", "Documents", "Desktop", "Downloads"}
|
||||
|
||||
@@ -517,10 +521,12 @@ class H12Visitor:
|
||||
remote가 참이면 ssh 원격 명령이다. 원격은 작업 폴더를 모르므로 너무 넓은 대상만 막는다.
|
||||
"""
|
||||
|
||||
def __init__(self, cwd, roots, remote=False):
|
||||
def __init__(self, cwd, roots, checkouts=(), foreign=(), remote=False):
|
||||
self.home = "~" if remote else H12_HOME
|
||||
self.cwd = cwd
|
||||
self.roots = roots
|
||||
self.checkouts = checkouts
|
||||
self.foreign = foreign
|
||||
self.remote = remote
|
||||
self.vars = {}
|
||||
self.raw = self.remember
|
||||
@@ -586,6 +592,16 @@ class H12Visitor:
|
||||
return "rm -r %s(너무 넓은 대상: %s)" % (t, path)
|
||||
if not self.remote and not any(under_root(path, r) for r in self.roots):
|
||||
return "rm -r %s(이 작업 폴더·scratchpad 밖: %s)" % (t, path)
|
||||
if not any(under_root(path, r) for r in H12_TEMP_ROOTS):
|
||||
# 허용 폴더(main checkout) 안이라도 checkout 자신이나 그것을 품은 폴더는 통째로 지우지 않고,
|
||||
# 옆 worktree 안도 지우지 않는다. main checkout 안 worktree에서 worktree 자신(`./*`),
|
||||
# 옆 worktree(`../x`), 그 안(`../x/src`)을 지우는 것을 막는다
|
||||
hit = next((c for c in self.checkouts if path == c or under_root(c, path)), None)
|
||||
if hit:
|
||||
return "rm -r %s(git checkout 통째: %s)" % (t, hit)
|
||||
hit = next((c for c in self.foreign if under_root(path, c)), None)
|
||||
if hit:
|
||||
return "rm -r %s(다른 worktree 안: %s)" % (t, hit)
|
||||
return None
|
||||
|
||||
def __call__(self, argv, heredocs):
|
||||
@@ -656,8 +672,15 @@ def data_violation(argv, heredocs):
|
||||
|
||||
|
||||
def h12_roots(cwd):
|
||||
"""rm -r을 허용하는 폴더: 프로젝트와 cwd의 git 작업 폴더(와 그 main checkout), /tmp, 앱 임시 작업 폴더."""
|
||||
roots = ["/tmp", os.path.join(H12_HOME, ".config", "Claude", "scratch-workspaces")]
|
||||
"""(rm -r을 허용하는 폴더, 지킬 checkout, 옆 worktree).
|
||||
|
||||
허용 폴더: 프로젝트와 cwd의 git 작업 폴더(와 그 main checkout), /tmp, 앱 임시 작업 폴더.
|
||||
지킬 checkout: 그 작업 폴더들과, 그 repo에 등록된 모든 worktree. 허용 폴더 안에 있어도 통째로 지우지 못한다.
|
||||
옆 worktree: 지킬 checkout 중 이 세션 작업 폴더와 같지도, 그것을 품지도, 그 안에 있지도 않은 것. 그 안도 못 지운다.
|
||||
이 세션 작업 폴더는 cwd의 checkout이고, cwd가 git 밖일 때만 프로젝트 폴더의 checkout이다. 세션의 프로젝트 폴더가
|
||||
main checkout이고 cwd가 그 안 worktree일 때 옆 worktree를 남의 것으로 보기 위해서다.
|
||||
"""
|
||||
roots, checkouts, tops = list(H12_TEMP_ROOTS), set(), {}
|
||||
for start in {os.environ.get("CLAUDE_PROJECT_DIR"), cwd} - {None, ""}:
|
||||
if not os.path.isdir(start):
|
||||
continue
|
||||
@@ -671,7 +694,20 @@ def h12_roots(cwd):
|
||||
out = os.path.dirname(out)
|
||||
if out and not too_broad(os.path.realpath(out), H12_HOME):
|
||||
roots.append(os.path.realpath(out))
|
||||
return roots
|
||||
checkouts.add(os.path.realpath(out))
|
||||
if args[-1] == "--show-toplevel":
|
||||
tops[start] = os.path.realpath(out)
|
||||
try:
|
||||
r = subprocess.run(["git", "-C", start, "worktree", "list", "--porcelain"],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
if r.returncode == 0:
|
||||
checkouts.update(os.path.realpath(line[len("worktree "):]) for line in r.stdout.splitlines()
|
||||
if line.startswith("worktree "))
|
||||
mine = tops.get(cwd) or tops.get(os.environ.get("CLAUDE_PROJECT_DIR"))
|
||||
foreign = [c for c in checkouts if mine and not (c == mine or under_root(mine, c) or under_root(c, mine))]
|
||||
return roots, sorted(checkouts), sorted(foreign)
|
||||
|
||||
|
||||
H12_HINTS = {
|
||||
@@ -694,7 +730,8 @@ def check_h12(command, cwd=None):
|
||||
"""H12 막을 이유(메시지). 통과면 None."""
|
||||
if not re.search(r"(?i)push|rm|drop|truncate|flush|clean|down|volume|prune|delete", command):
|
||||
return None
|
||||
what = walk(command, H12Visitor(os.path.realpath(cwd) if cwd else None, h12_roots(cwd)))
|
||||
roots, checkouts, foreign = h12_roots(cwd)
|
||||
what = walk(command, H12Visitor(os.path.realpath(cwd) if cwd else None, roots, checkouts, foreign))
|
||||
if not what:
|
||||
return None
|
||||
return H12_MESSAGE.format(what=what, hint=H12_HINTS[what.split(":", 1)[0]])
|
||||
|
||||
Reference in New Issue
Block a user