문제: 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
774 lines
32 KiB
Python
Executable File
774 lines
32 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""하네스 플러그인 PreToolUse(Bash) 가드 — H12 되돌릴 수 없는 명령.
|
|
|
|
막는 것
|
|
- 호스팅 원격으로 force push(`-f`, `--force`, `--force-with-lease`, `+ref`), `--mirror`·`--prune`,
|
|
보호 브랜치(main·master·develop·trunk·release) 지우기. 다른 기계 작업 사본 경로(`host:/abs/path`)로
|
|
보내는 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`.
|
|
`ssh host '…'` 안의 명령도 본다. 원격은 작업 폴더를 모르므로 너무 넓은 대상만 막는다.
|
|
heredoc 본문(커밋 메시지, 파일 내용)은 데이터로 보고 명령으로 읽지 않는다.
|
|
|
|
두 번 막지 않기: 사용자 전역 `~/.claude/settings.json`에 `guard_bash.py … H12` 훅이 등록돼 있으면
|
|
이 플러그인은 아무것도 하지 않는다(같은 판정을 전역 훅이 한다). `HARNESS_H12=always`면 그래도 돈다.
|
|
|
|
종료 코드 2 = 막음(stderr가 Claude에게 간다). 0 = 통과. 그 밖(이 스크립트의 버그)은 경고만 뜨고 통과한다.
|
|
시험: `python3 -m unittest discover -s plugins/harness/tests`
|
|
"""
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
SHELLS = {"bash", "sh", "zsh", "dash", "ksh"}
|
|
RESERVED = {"!", "{", "}", "if", "then", "else", "elif", "fi", "do", "done", "while", "until", "function", "coproc"}
|
|
SKIP_SEGMENT = {"for", "case", "select", "esac"}
|
|
ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\[[^]]*\])?\+?=")
|
|
HEREDOC_RE = re.compile(r"(?<!<)<<(-?)[ \t]*(['\"]?)([A-Za-z_][\w.-]*)\2")
|
|
OPS = ["&&", "||", ";;", "|&", ";", "|", "&", "\n", "(", ")"]
|
|
REDIRS = ["&>>", "&>", "<<<", "<<-", "<<", "<>", "<&", ">&", ">>", ">|", "<", ">"]
|
|
SSH_ARG_OPTS = set("bcDEeFIiJLlmOopQRSWwB")
|
|
MAX_DEPTH = 6
|
|
|
|
|
|
# ---------------------------------------------------------------- 셸 문자열 읽기
|
|
|
|
def strip_heredocs(s, bodies):
|
|
"""heredoc 본문을 떼어 bodies에 넣고, 자리에 `<<__HD{n}__` 표시를 남긴다.
|
|
|
|
본문은 보통 데이터(커밋 메시지 등)라 명령으로 읽으면 거짓 양성이 난다.
|
|
셸·ssh가 본문을 스크립트로 받는 경우만 따로 다시 읽는다.
|
|
"""
|
|
lines = s.split("\n")
|
|
out = []
|
|
i = 0
|
|
while i < len(lines):
|
|
pending = []
|
|
|
|
def mark(m):
|
|
pending.append((m.group(1) == "-", m.group(3)))
|
|
return "<<__HD%d__" % (len(bodies) + len(pending) - 1)
|
|
|
|
out.append(HEREDOC_RE.sub(mark, lines[i]))
|
|
i += 1
|
|
for dash, delim in pending:
|
|
body = []
|
|
while i < len(lines):
|
|
line = lines[i]
|
|
i += 1
|
|
if (line.lstrip("\t") if dash else line) == delim:
|
|
break
|
|
body.append(line)
|
|
bodies.append("\n".join(body))
|
|
return "\n".join(out)
|
|
|
|
|
|
def read_paren(s, i):
|
|
"""s[i:]에서 짝이 맞는 `)`까지 읽는다. (안쪽 글, `)` 다음 위치)."""
|
|
depth = 1
|
|
start = i
|
|
n = len(s)
|
|
while i < n:
|
|
c = s[i]
|
|
if c == "\\":
|
|
i += 2
|
|
continue
|
|
if c == "'":
|
|
j = s.find("'", i + 1)
|
|
i = n if j < 0 else j + 1
|
|
continue
|
|
if c == '"':
|
|
i += 1
|
|
while i < n and s[i] != '"':
|
|
i += 2 if s[i] == "\\" else 1
|
|
i += 1
|
|
continue
|
|
if c == "(":
|
|
depth += 1
|
|
elif c == ")":
|
|
depth -= 1
|
|
if depth == 0:
|
|
return s[start:i], i + 1
|
|
i += 1
|
|
return s[start:], n
|
|
|
|
|
|
def find_backtick(s, i):
|
|
n = len(s)
|
|
while i < n:
|
|
if s[i] == "\\":
|
|
i += 2
|
|
continue
|
|
if s[i] == "`":
|
|
return i
|
|
i += 1
|
|
return n
|
|
|
|
|
|
def tokenize(s):
|
|
"""따옴표·치환을 고려해 토큰으로 나눈다.
|
|
|
|
돌려주는 것: (토큰 목록, 명령 치환 안쪽 글 목록)
|
|
토큰: ("W", 단어) / ("O", 연산자) / ("R", 리다이렉션)
|
|
작은따옴표 안은 치환이 일어나지 않으므로 그대로 단어로 둔다.
|
|
"""
|
|
toks, subs = [], []
|
|
cur, inword = [], False
|
|
i, n = 0, len(s)
|
|
|
|
def flush():
|
|
nonlocal cur, inword
|
|
if inword:
|
|
toks.append(("W", "".join(cur)))
|
|
cur, inword = [], False
|
|
|
|
while i < n:
|
|
c = s[i]
|
|
if c == "\\":
|
|
if i + 1 < n and s[i + 1] == "\n":
|
|
i += 2
|
|
continue
|
|
if i + 1 < n:
|
|
cur.append(s[i + 1])
|
|
inword = True
|
|
i += 2
|
|
continue
|
|
if c == "'":
|
|
j = s.find("'", i + 1)
|
|
j = n if j < 0 else j
|
|
cur.append(s[i + 1:j])
|
|
inword = True
|
|
i = j + 1
|
|
continue
|
|
if c == '"':
|
|
inword = True
|
|
i += 1
|
|
while i < n and s[i] != '"':
|
|
if s[i] == "\\" and i + 1 < n:
|
|
cur.append(s[i + 1])
|
|
i += 2
|
|
elif s.startswith("$(", i):
|
|
inner, i = read_paren(s, i + 2)
|
|
subs.append(inner)
|
|
cur.append("$(…)")
|
|
elif s[i] == "`":
|
|
j = find_backtick(s, i + 1)
|
|
subs.append(s[i + 1:j])
|
|
cur.append("`…`")
|
|
i = j + 1
|
|
else:
|
|
cur.append(s[i])
|
|
i += 1
|
|
i += 1
|
|
continue
|
|
if c == "`":
|
|
j = find_backtick(s, i + 1)
|
|
subs.append(s[i + 1:j])
|
|
cur.append("`…`")
|
|
inword = True
|
|
i = j + 1
|
|
continue
|
|
if s.startswith("$(", i):
|
|
inner, i = read_paren(s, i + 2)
|
|
subs.append(inner)
|
|
cur.append("$(…)")
|
|
inword = True
|
|
continue
|
|
if c in "<>" and i + 1 < n and s[i + 1] == "(" and not inword:
|
|
inner, i = read_paren(s, i + 2)
|
|
subs.append(inner)
|
|
continue
|
|
if c == "#" and not inword:
|
|
j = s.find("\n", i)
|
|
i = n if j < 0 else j
|
|
continue
|
|
if c in " \t\r":
|
|
flush()
|
|
i += 1
|
|
continue
|
|
if c in "<>&" and (not inword or "".join(cur).isdigit()):
|
|
red = next((r for r in REDIRS if s.startswith(r, i)), None)
|
|
if red:
|
|
cur, inword = [], False # 2>&1의 2 같은 fd 번호는 버린다
|
|
toks.append(("R", red))
|
|
i += len(red)
|
|
continue
|
|
op = next((o for o in OPS if s.startswith(o, i)), None)
|
|
if op:
|
|
flush()
|
|
toks.append(("O", op))
|
|
i += len(op)
|
|
continue
|
|
cur.append(c)
|
|
inword = True
|
|
i += 1
|
|
flush()
|
|
return toks, subs
|
|
|
|
|
|
class Command:
|
|
def __init__(self):
|
|
self.argv = []
|
|
self.heredocs = []
|
|
|
|
|
|
def simple_commands(script, bodies):
|
|
"""스크립트를 단순 명령 단위로 나눈다. (명령 목록, 명령 치환 안쪽 글 목록)."""
|
|
toks, subs = tokenize(strip_heredocs(script, bodies))
|
|
cmds, cur = [], Command()
|
|
i = 0
|
|
while i < len(toks):
|
|
kind, val = toks[i]
|
|
if kind == "O":
|
|
cmds.append(cur)
|
|
cur = Command()
|
|
elif kind == "R":
|
|
if i + 1 < len(toks) and toks[i + 1][0] == "W":
|
|
target = toks[i + 1][1]
|
|
m = re.fullmatch(r"__HD(\d+)__", target)
|
|
if val in ("<<", "<<-") and m and int(m.group(1)) < len(bodies):
|
|
cur.heredocs.append(bodies[int(m.group(1))])
|
|
i += 1
|
|
else:
|
|
cur.argv.append(val)
|
|
i += 1
|
|
cmds.append(cur)
|
|
return [c for c in cmds if c.argv or c.heredocs], subs
|
|
|
|
|
|
def skip_opts(argv, j, arg_opts):
|
|
while j < len(argv) and argv[j].startswith("-") and argv[j] != "-":
|
|
if argv[j] == "--":
|
|
return j + 1
|
|
j += 2 if argv[j] in arg_opts else 1
|
|
return j
|
|
|
|
|
|
def unwrap(argv):
|
|
"""앞의 변수 대입·예약어·감싸는 명령(sudo, env, timeout, flock …)을 벗긴다.
|
|
|
|
돌려주는 것: ("exec", 실제 argv) 또는 ("script", 셸 문자열) 또는 ("none", [])
|
|
"""
|
|
i = 0
|
|
while i < len(argv):
|
|
w = argv[i]
|
|
name = os.path.basename(w)
|
|
if ASSIGN_RE.match(w) or w in RESERVED:
|
|
i += 1
|
|
elif w in SKIP_SEGMENT:
|
|
return ("none", [])
|
|
elif name in ("nohup", "builtin", "time", "caffeinate"):
|
|
i = skip_opts(argv, i + 1, set())
|
|
elif name == "exec":
|
|
i = skip_opts(argv, i + 1, {"-a"})
|
|
elif name == "command":
|
|
if i + 1 < len(argv) and argv[i + 1] in ("-v", "-V"):
|
|
return ("none", [])
|
|
i = skip_opts(argv, i + 1, set())
|
|
elif name == "sudo":
|
|
i = skip_opts(argv, i + 1, {"-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U", "-T"})
|
|
elif name == "nice":
|
|
i = skip_opts(argv, i + 1, {"-n", "--adjustment"})
|
|
elif name == "stdbuf":
|
|
i = skip_opts(argv, i + 1, {"-i", "-o", "-e"})
|
|
elif name == "ionice":
|
|
i = skip_opts(argv, i + 1, {"-c", "-n", "-p", "-P", "-u"})
|
|
elif name == "timeout":
|
|
i = skip_opts(argv, i + 1, {"-s", "--signal", "-k", "--kill-after"}) + 1
|
|
elif name == "xargs":
|
|
i = skip_opts(argv, i + 1, {"-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a"})
|
|
elif name == "env":
|
|
j = i + 1
|
|
while j < len(argv):
|
|
a = argv[j]
|
|
if a in ("-S", "--split-string"):
|
|
return ("script", " ".join(argv[j + 1:]))
|
|
if a in ("-u", "--unset", "-C", "--chdir"):
|
|
j += 2
|
|
elif a.startswith("-") or ASSIGN_RE.match(a):
|
|
j += 1
|
|
else:
|
|
break
|
|
i = j
|
|
elif name == "flock":
|
|
j = skip_opts(argv, i + 1, {"-w", "--wait", "--timeout", "-E", "--conflict-exit-code"}) + 1
|
|
if j < len(argv) and argv[j] in ("-c", "--command"):
|
|
return ("script", argv[j + 1] if j + 1 < len(argv) else "")
|
|
i = j
|
|
elif name == "watch":
|
|
j = skip_opts(argv, i + 1, {"-n", "--interval", "-q", "--equexit"})
|
|
return ("script", " ".join(argv[j:]))
|
|
elif name == "eval":
|
|
return ("script", " ".join(argv[i + 1:]))
|
|
else:
|
|
return ("exec", argv[i:])
|
|
return ("none", [])
|
|
|
|
|
|
def shell_script(argv, heredocs):
|
|
"""bash/sh/zsh 호출이 실행하는 것. ("script", 글) / ("file", 경로) / None."""
|
|
j = 1
|
|
while j < len(argv) and argv[j][:1] in "-+" and argv[j] not in ("-", "--"):
|
|
a = argv[j]
|
|
if not a.startswith("--") and "c" in a[1:]:
|
|
return ("script", argv[j + 1] if j + 1 < len(argv) else "")
|
|
j += 2 if a in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file") else 1
|
|
if j < len(argv) and argv[j] == "--":
|
|
j += 1
|
|
if j < len(argv):
|
|
return ("file", argv[j])
|
|
if heredocs:
|
|
return ("script", "\n".join(heredocs))
|
|
return None
|
|
|
|
|
|
def ssh_remote(argv, heredocs):
|
|
"""ssh가 원격에서 실행할 스크립트. 원격 명령이 없으면 heredoc 본문."""
|
|
j = 1
|
|
while j < len(argv) and argv[j].startswith("-") and argv[j] != "--":
|
|
a = argv[j]
|
|
j += 2 if (len(a) == 2 and a[1] in SSH_ARG_OPTS) else 1
|
|
if j < len(argv) and argv[j] == "--":
|
|
j += 1
|
|
j += 1 # 호스트
|
|
remote = " ".join(argv[j:])
|
|
if heredocs:
|
|
remote = (remote + "\n" + "\n".join(heredocs)).strip()
|
|
return remote
|
|
|
|
|
|
# ---------------------------------------------------------------- 판정
|
|
|
|
def walk(script, visit, bodies=None, depth=0):
|
|
"""스크립트 안의 모든 실행 지점에 visit(argv, heredocs)를 부른다.
|
|
|
|
visit가 문자열을 돌려주면 막을 이유로 보고 바로 돌려준다.
|
|
visit가 ("recurse", 글)을 돌려주면 그 글을 이어서 본다(ssh 원격 등).
|
|
visit에 raw 속성이 있으면 벗기기 전 argv(앞쪽 변수 대입 포함)로 먼저 부른다.
|
|
"""
|
|
if depth > MAX_DEPTH:
|
|
return None
|
|
bodies = [] if bodies is None else bodies
|
|
cmds, subs = simple_commands(script, bodies)
|
|
for sub in subs:
|
|
found = walk(sub, visit, bodies, depth + 1)
|
|
if found:
|
|
return found
|
|
raw_visit = getattr(visit, "raw", None)
|
|
for cmd in cmds:
|
|
found = raw_visit(cmd.argv) if raw_visit else None
|
|
if found:
|
|
return found
|
|
kind, argv = unwrap(cmd.argv)
|
|
if kind == "script":
|
|
found = walk(argv, visit, bodies, depth + 1)
|
|
if found:
|
|
return found
|
|
continue
|
|
if kind == "none" or not argv:
|
|
continue
|
|
name = os.path.basename(argv[0])
|
|
if name in SHELLS:
|
|
run = shell_script(argv, cmd.heredocs)
|
|
if run and run[0] == "script":
|
|
found = walk(run[1], visit, bodies, depth + 1)
|
|
if found:
|
|
return found
|
|
continue
|
|
result = visit(argv, cmd.heredocs)
|
|
if isinstance(result, tuple) and result[0] == "recurse":
|
|
found = walk(result[1], visit, bodies, depth + 1)
|
|
if found:
|
|
return found
|
|
elif result:
|
|
return result
|
|
return None
|
|
|
|
|
|
GIT_ARG_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env",
|
|
"--super-prefix", "--list-cmds", "--attr-source"}
|
|
|
|
|
|
# ---------------------------------------------------------------- H12 되돌릴 수 없는 명령
|
|
# 이 절과 위의 셸 파서는 소유자 기계의 전역 훅 ~/.claude/hooks/guard_bash.py와 정의가 같다(주석 제외).
|
|
# 고치면 두 곳을 같이 고친다. 소유자 기계의 전역 훅 시험이 두 사본을 비교한다.
|
|
|
|
PROTECTED_REF_RE = re.compile(r"^(refs/heads/)?(main|master|develop|trunk|release([/-].*)?|HEAD)$")
|
|
PUSH_OPTS_WITH_ARG = {"-o", "--push-option", "--repo", "--receive-pack", "--exec"}
|
|
PATH_REMOTE_RE = re.compile(r"^(/|\./|\.\./|file://|[A-Za-z0-9._-]+:/(?!/))")
|
|
SQL_CLIENTS = {"psql", "mysql", "mariadb", "sqlite3", "sqlcmd", "clickhouse-client", "cqlsh"}
|
|
SQL_DROP_RE = re.compile(r"(?i)\b(drop\s+(database|schema|table)\b|truncate\b)")
|
|
CONTAINER_TOOLS = {"docker", "podman", "nerdctl"}
|
|
COMPOSE_TOOLS = {"docker-compose", "podman-compose"}
|
|
KUBE_DATA_KIND_RE = re.compile(r"(?i)^(pvc|pv|ns|persistentvolumeclaims?|persistentvolumes?|namespaces?)$")
|
|
VAR_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)([^}]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
|
|
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"}
|
|
|
|
|
|
def push_violation(args):
|
|
"""git push 인자에서 force push·보호 브랜치 지우기를 찾는다. 통과면 None.
|
|
|
|
다른 기계 작업 사본 경로(`desktop:/home/…`)로 보내는 force push는 운반이라 통과한다.
|
|
다만 보호 브랜치(main 등)를 덮거나, 대상 ref를 적지 않았으면 막는다.
|
|
"""
|
|
force = delete = False
|
|
words = []
|
|
k = 0
|
|
while k < len(args):
|
|
a = args[k]
|
|
if a == "--":
|
|
words += args[k + 1:]
|
|
break
|
|
if a.startswith("--"):
|
|
name = a.split("=", 1)[0]
|
|
if name in ("--force", "--force-with-lease"):
|
|
force = True
|
|
elif name in ("--mirror", "--prune"):
|
|
return "git push %s(원격 ref를 통째로 덮거나 지운다)" % name
|
|
elif name == "--delete":
|
|
delete = True
|
|
elif name == "--dry-run":
|
|
return None
|
|
k += 2 if (name in PUSH_OPTS_WITH_ARG and "=" not in a) else 1
|
|
continue
|
|
if a.startswith("-") and len(a) > 1:
|
|
for idx, ch in enumerate(a[1:]):
|
|
if ch == "f":
|
|
force = True
|
|
elif ch == "d":
|
|
delete = True
|
|
elif ch == "n":
|
|
return None
|
|
elif ch == "o":
|
|
if idx == len(a) - 2:
|
|
k += 1 # 값이 다음 단어다
|
|
break
|
|
k += 1
|
|
continue
|
|
words.append(a)
|
|
k += 1
|
|
remote, specs = (words[0], words[1:]) if words else (None, [])
|
|
deleted, forced = [], []
|
|
for spec in specs:
|
|
plus = spec.startswith("+")
|
|
src, sep, dst = (spec[1:] if plus else spec).partition(":")
|
|
dst = dst if sep else src
|
|
if delete or (sep and not src):
|
|
deleted.append(dst)
|
|
elif force or plus:
|
|
forced.append(dst)
|
|
for ref in deleted:
|
|
if PROTECTED_REF_RE.match(ref):
|
|
return "git push로 보호 브랜치 %s 지우기" % ref
|
|
if force and not specs:
|
|
forced.append("(대상 ref를 적지 않음)")
|
|
if not forced:
|
|
return None
|
|
if not (remote and PATH_REMOTE_RE.match(remote)):
|
|
return "force push(원격 %s)" % (remote or "기본값")
|
|
for ref in forced:
|
|
if not ref or PROTECTED_REF_RE.match(ref) or ref.startswith("("):
|
|
return "force push로 %s 덮어쓰기" % (ref or "(빈 ref)")
|
|
return None
|
|
|
|
|
|
def rm_targets(args):
|
|
"""rm 인자에서 (재귀 삭제인가, 대상 목록)."""
|
|
recursive, targets, opts_done = False, [], False
|
|
for a in args:
|
|
if not opts_done and a == "--":
|
|
opts_done = True
|
|
elif not opts_done and a.startswith("--"):
|
|
recursive = recursive or a == "--recursive"
|
|
elif not opts_done and a.startswith("-") and len(a) > 1:
|
|
recursive = recursive or "r" in a or "R" in a
|
|
else:
|
|
targets.append(a)
|
|
return recursive, targets
|
|
|
|
|
|
def under_root(path, root):
|
|
"""path가 root 아래인가(root 자신은 아니다)."""
|
|
return path.startswith(root.rstrip("/") + "/")
|
|
|
|
|
|
def too_broad(path, home):
|
|
"""통째로 지우면 되돌릴 수 없는 넓은 경로인가."""
|
|
if path in ("/", home, H12_TMP) or os.path.dirname(path) == "/":
|
|
return True
|
|
if os.path.dirname(path) == home and os.path.basename(path) in H12_HOME_KEEP:
|
|
return True
|
|
parts = os.path.relpath(path, home).split(os.sep) if under_root(path, home) else []
|
|
return len(parts) <= 2 and parts[:1] == ["workspace"] # ~/workspace/<repo 묶음> 통째
|
|
|
|
|
|
class H12Visitor:
|
|
"""walk가 부르는 H12 판정기. cd·변수 대입을 따라가며 rm 대상의 실제 위치를 어림한다.
|
|
|
|
remote가 참이면 ssh 원격 명령이다. 원격은 작업 폴더를 모르므로 너무 넓은 대상만 막는다.
|
|
"""
|
|
|
|
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
|
|
|
|
def expand(self, word):
|
|
"""변수를 아는 값으로 바꾼다. 모르는 변수는 빈 값(가장 나쁜 경우), 명령 치환은 OPAQUE."""
|
|
if "$(…)" in word or "`…`" in word:
|
|
return OPAQUE
|
|
|
|
def sub(m):
|
|
name, rest = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), "")
|
|
if name in self.vars:
|
|
return self.vars[name]
|
|
if name == "HOME":
|
|
return self.home
|
|
if name == "PWD" and self.cwd:
|
|
return self.cwd
|
|
if rest.startswith((":?", "?")):
|
|
return OPAQUE # 비면 셸이 멈춘다
|
|
if rest.startswith((":-", "-")):
|
|
return self.expand(rest.lstrip(":")[1:])
|
|
return ""
|
|
|
|
out = VAR_RE.sub(sub, word)
|
|
if out == "~" or out.startswith("~/"):
|
|
out = self.home + out[1:]
|
|
return OPAQUE if OPAQUE in out else out
|
|
|
|
def remember(self, raw):
|
|
"""벗기기 전 argv에서 변수 대입과 for 변수를 기억한다."""
|
|
if len(raw) > 1 and raw[0] in ("for", "select"):
|
|
self.vars[raw[1]] = OPAQUE
|
|
for w in raw:
|
|
if w in RESERVED:
|
|
continue
|
|
if not ASSIGN_RE.match(w):
|
|
break
|
|
name, _, value = w.partition("=")
|
|
self.vars[re.sub(r"\[.*|\+$", "", name)] = self.expand(value)
|
|
return None
|
|
|
|
def locate(self, word):
|
|
"""대상 단어의 절대 경로. 모르면 None."""
|
|
path = self.expand(word)
|
|
if path == OPAQUE or path == "":
|
|
return path if path == "" else None
|
|
if not path.startswith("/") and not (self.remote and (path == "~" or path.startswith("~/"))):
|
|
if not self.cwd:
|
|
return None
|
|
path = os.path.join(self.cwd, path)
|
|
return os.path.normpath(path) if path else ""
|
|
|
|
def rm_violation(self, targets):
|
|
for t in targets:
|
|
if os.path.basename(t.rstrip("/")) == ".git":
|
|
return "rm -r %s(git 저장소 자체)" % t
|
|
path = self.locate(t)
|
|
if not path:
|
|
continue # 빈 값(rm이 아무것도 안 함)이거나 위치를 모름
|
|
if any(c in os.path.basename(path) for c in "*?["):
|
|
path = os.path.dirname(path) # `폴더/*`는 그 폴더를 통째로 지우는 것과 같다
|
|
if too_broad(path, self.home):
|
|
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):
|
|
name = os.path.basename(argv[0])
|
|
args = argv[1:]
|
|
if name == "ssh":
|
|
return walk(ssh_remote(argv, heredocs), H12Visitor(None if self.remote else "~", [], remote=True))
|
|
if name in ("cd", "pushd"):
|
|
dest = args[0] if args else "~"
|
|
self.cwd = None if dest == "-" else (self.locate(dest) or None)
|
|
return None
|
|
if name in ("export", "declare", "typeset", "local", "readonly"):
|
|
self.remember([a for a in args if not a.startswith("-")])
|
|
return None
|
|
if name == "read":
|
|
for a in args:
|
|
if not a.startswith("-"):
|
|
self.vars[a] = OPAQUE
|
|
return None
|
|
what = " ".join(argv)
|
|
if name == "git":
|
|
j = 1
|
|
while j < len(argv) and argv[j].startswith("-"):
|
|
j += 2 if argv[j] in GIT_ARG_OPTS else 1
|
|
if j < len(argv) and argv[j] == "push":
|
|
why = push_violation(argv[j + 1:])
|
|
return "force push: %s (`%s`)" % (why, what) if why else None
|
|
return None
|
|
if name == "rm":
|
|
recursive, targets = rm_targets(args)
|
|
why = self.rm_violation(targets) if recursive else None
|
|
return "rm: %s (`%s`)" % (why, what) if why else None
|
|
return data_violation(argv, heredocs)
|
|
|
|
|
|
def data_violation(argv, heredocs):
|
|
"""DB·볼륨·migration을 지우는 명령. 다른 명령 안(docker exec, kubectl exec)의 클라이언트도 본다."""
|
|
names = [os.path.basename(w) for w in argv]
|
|
what = " ".join(argv)
|
|
for i, n in enumerate(names):
|
|
rest = argv[i + 1:]
|
|
if n in SQL_CLIENTS and SQL_DROP_RE.search(" ".join(rest + heredocs)):
|
|
return "db: DROP·TRUNCATE (`%s`)" % what
|
|
if n == "redis-cli" and any(w.lower() in ("flushall", "flushdb") for w in rest):
|
|
return "db: redis FLUSHALL·FLUSHDB (`%s`)" % what
|
|
if n in ("gradle", "gradlew", "mvn", "mvnw") and any(re.search(r"(^|:)(flywayClean|flyway:clean)$", w)
|
|
for w in rest):
|
|
return "db: flyway clean(migration 초기화) (`%s`)" % what
|
|
if (n == "flyway" and "clean" in rest) or (n == "liquibase" and ({"drop-all", "dropAll"} & set(rest))):
|
|
return "db: migration 초기화 (`%s`)" % what
|
|
compose = n in COMPOSE_TOOLS or (n in CONTAINER_TOOLS and "compose" in rest)
|
|
if compose and "down" in rest:
|
|
before, after = rest[:rest.index("down")], rest[rest.index("down") + 1:]
|
|
scoped = any(w in ("-p", "--project-name") or w.startswith("--project-name=") or "$" in w
|
|
for w in before) # 변수(`${F[*]}`) 안의 -p는 알 수 없어 막지 않는다
|
|
if not scoped and any(w == "--volumes" or (w.startswith("-") and not w.startswith("--") and "v" in w) for w in after):
|
|
return "volume: compose down -v(-p 없이 기본 프로젝트) (`%s`)" % what
|
|
if n in CONTAINER_TOOLS and rest[:1] == ["volume"] and rest[1:2] and rest[1] in ("rm", "prune"):
|
|
return "volume: %s volume %s (`%s`)" % (n, rest[1], what)
|
|
if n in CONTAINER_TOOLS and rest[:2] == ["system", "prune"] and "--volumes" in rest:
|
|
return "volume: system prune --volumes (`%s`)" % what
|
|
if n == "kubectl" and "delete" in rest:
|
|
kinds = [w for w in rest[rest.index("delete") + 1:] if not w.startswith("-")][:1]
|
|
for kind in (kinds[0].split("/")[0].split(",") if kinds else []):
|
|
if KUBE_DATA_KIND_RE.match(kind):
|
|
return "volume: kubectl delete %s (`%s`)" % (kind, what)
|
|
return None
|
|
|
|
|
|
def h12_roots(cwd):
|
|
"""(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
|
|
for args in (["rev-parse", "--show-toplevel"], ["rev-parse", "--path-format=absolute", "--git-common-dir"]):
|
|
try:
|
|
r = subprocess.run(["git", "-C", start, *args], capture_output=True, text=True, timeout=5)
|
|
except (OSError, subprocess.SubprocessError):
|
|
continue
|
|
out = r.stdout.strip() if r.returncode == 0 else ""
|
|
if out.endswith("/.git"):
|
|
out = os.path.dirname(out)
|
|
if out and not too_broad(os.path.realpath(out), H12_HOME):
|
|
roots.append(os.path.realpath(out))
|
|
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 = {
|
|
"force push": "이력을 고칠 일이면 새 커밋으로 고쳐 push한다. 원격 이력을 꼭 덮어야 하면 사용자에게 묻는다.",
|
|
"rm": "이 작업 폴더나 scratchpad 안의 정확한 경로만 지운다. worktree는 `git worktree remove`로 지운다. "
|
|
"변수로 경로를 만들면 같은 명령 안에서 값을 정하거나 `${X:?}`로 빈 값을 막는다.",
|
|
"db": "개발 DB를 새로 만들려면 repo의 초기화 스크립트를 쓴다. 운영·공유 DB는 사용자가 직접 한다.",
|
|
"volume": "볼륨을 남기고 내린다(`down`만). 시험용 환경은 `-p <고유 이름>`으로 띄우고 같은 `-p`로 `down -v`한다. "
|
|
"개발·공유 데이터를 지워야 하면 사용자에게 묻는다.",
|
|
}
|
|
|
|
H12_MESSAGE = """[H12 되돌릴 수 없는 명령] 막은 명령: {what}
|
|
원격 이력 덮어쓰기, 작업 폴더 밖 삭제, DB·볼륨·migration 삭제는 되돌릴 수 없어 사용자가 직접 합니다.
|
|
|
|
대신: {hint}
|
|
막은 것이 틀렸다고 보이면 우회하지 말고 사용자에게 알린다."""
|
|
|
|
|
|
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
|
|
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]])
|
|
|
|
|
|
def global_h12_registered():
|
|
"""사용자 전역 설정에 guard_bash.py H12 훅이 등록돼 있나."""
|
|
path = os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
|
|
try:
|
|
with open(path, encoding="utf-8") as f:
|
|
matchers = (json.load(f).get("hooks") or {}).get("PreToolUse") or []
|
|
except (OSError, ValueError, AttributeError):
|
|
return False
|
|
return any(re.search(r"guard_bash\.py\S*\s+H12\b", str(h.get("command", "")))
|
|
for m in matchers if isinstance(m, dict) for h in m.get("hooks") or [] if isinstance(h, dict))
|
|
|
|
|
|
def main():
|
|
data = json.load(sys.stdin)
|
|
if data.get("tool_name") not in (None, "Bash"):
|
|
return 0
|
|
if os.environ.get("HARNESS_H12") != "always" and global_h12_registered():
|
|
return 0
|
|
command = (data.get("tool_input") or {}).get("command") or ""
|
|
message = check_h12(command, data.get("cwd"))
|
|
if message:
|
|
print(message, file=sys.stderr)
|
|
return 2
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
sys.exit(main())
|
|
except SystemExit:
|
|
raise
|
|
except Exception as exc: # 훅 버그는 막지 않고 알리기만 한다
|
|
print("harness guard_bash 내부 오류로 검사를 건너뜀: %r" % (exc,), file=sys.stderr)
|
|
sys.exit(1)
|