Files
DongHyeonka 2d61bad023 feat(claude): reviewer 서브에이전트의 Bash를 읽기 전용 가드로 막는다
문제: reviewer는 Bash를 갖고 본문에 「읽기 명령만 쓴다」고만 적혀 있다. 모델이
그 줄을 어기면 리뷰 중에 작업 트리를 바꾸거나 git 상태를 옮길 수 있고, 막는 장치가 없다.

방법: reviewer 머리 칸에 PreToolUse(Bash) 가드를 건다. 가드는 허용 목록 방식이라
`git diff/log/show/grep`과 `python3 -I scripts/check-work-docs.py`만 통과하고, 그 밖의
명령·출력 돌리기·줄바꿈 뒤 명령은 rc 2로 막는다. 스크립트와 시험은 프로젝트 문서
저장소의 공용 사본을 고치지 않고 `.claude/hooks/`에 둔다. `.claude/*`를 무시하는
`.gitignore`에 `!.claude/hooks/`를 더해 함께 배포한다. 본문의 python 줄은 가드와 같게
`-I`를 붙였다. repo 훅 README 1절의 「막지 않는다」에 이 예외를 적는다.
`scripts/tests/test_agent_guard.py`는 가드 자체 시험을 돌리고, 머리 칸에 적힌 그대로의
인자로 본문의 허용 명령은 rc 0, 쓰는 명령은 rc 2인지 본다. Bash를 가진 에이전트는
가드를 걸거나 그 시험의 UNGUARDED에 까닭과 함께 적어야 한다. CI의 scripts/tests step이
이 시험을 돈다. `.gitignore` 시험 목록에 `!.claude/hooks/`를 더하고, 문서 작성 순서의
`check-work-docs.py` 호출도 가드 인자와 같게 `-I`를 붙인다.
- 버린 대안: `scripts/hooks/`에 두기. 그 폴더는 settings.json이 거는 알림 훅
  `hooks.py` 하나만 두는 곳이라 성격이 다르다.
- verify-app은 걸지 않았다. 원격 묶음 명령(`ssh desktop '<cd·flock·pnpm>'`)과 임시
  spec 쓰기를 명령 앞머리 하나로 좁힐 수 없다. arch-reviewer는 Bash가 없다.

위험·한계: 사고 방지용이다. 허용한 명령 안에서 일부러 돌아가는 것은 못 막는다.
`cd <폴더> && git diff`는 막히니 `git -C <폴더>`를 쓴다.

검증:
- python3 -I .claude/hooks/test_readonly_bash.py: 9 tests OK
- 가드 직접 입력: 허용 8개 rc 0, touch·>·줄바꿈 touch·checkout·stash·-I 없는 python·
  --output·cd 8개 rc 2
- 새 프로세스 guard_probe(reviewer, git log --oneline -3): rc 0, 가드가 막은 줄 3
- python3 -I -m unittest discover -s scripts/tests: 112 OK
- 변이 넷(머리 칸 가드 빼기, --git에서 diff 빼기, 본문의 -I 빼기, 가드 없는 Bash
  에이전트 더하기)이 각각 test_agent_guard.py의 시험 하나를 떨어뜨림
- scripts/verify.sh docs rc 0, scripts/verify.sh hooks rc 0
2026-12-03 02:48:48 +09:00

249 lines
9.9 KiB
Python

#!/usr/bin/env python3
"""서브에이전트 머리 칸 hooks(PreToolUse)에 거는 읽기 전용 가드.
docs/worker-redesign/master.md S-2: Bash를 주면 허용 명령 범위를 본문에 적고 쓰기 명령을 가드로 막는다.
허용 목록은 인자로 받는다. 인자에 없는 명령은 전부 막는다(막을 것을 세는 방식이 아니다).
--git log,show,diff 허용할 git 하위 명령. READ_GIT 밖의 이름이 있으면 설정 오류로 모든 호출을 막는다.
--cmd ls,wc,grep 허용할 명령. READ_CMD 밖의 이름이 있으면 설정 오류다.
--py `python3 -I -c '<코드>'`를 허용한다. 코드가 파일·프로세스를 건드리면 막는다.
--pyfile `python3 -I <파일>.py …`를 허용한다(검사기·시험). 그 파일이 하는 일은 부르는 쪽이 본다.
--run '<명령 앞머리>' 그 앞머리로 시작하는 명령을 허용한다(여러 번 쓸 수 있다). 예: --run './verify.sh'
--write <폴더> Write·Edit가 쓸 수 있는 폴더(여러 번). 없으면 Write·Edit는 보지 않는다.
막으면 까닭을 stderr에 쓰고 rc 2, 통과면 rc 0. 입력을 못 읽거나 설정이 틀려도 rc 2다.
사고를 막는 가드다. 허용한 명령 안에서 일부러 돌아가는 것까지 막지는 못한다.
시험: python3 -I .claude/hooks/test_readonly_bash.py
"""
import json
import os
import re
import sys
READ_GIT = {"log", "show", "diff", "rev-parse", "rev-list", "status", "cat-file", "for-each-ref", "ls-files",
"ls-tree", "blame", "grep", "describe", "merge-base", "name-rev", "shortlog", "diff-tree", "show-ref"}
READ_CMD = {"cd", "ls", "stat", "wc", "sort", "uniq", "head", "tail", "grep", "cut", "date", "cat", "find", "diff",
"sha256sum", "md5sum", "file", "du", "tr", "basename", "dirname", "realpath", "readlink", "echo",
"printf", "test", "true", "pwd", "jq", "nl", "tac", "comm", "cmp", "sed", "awk"}
ENV_OK = {"TZ", "LC_ALL", "LANG", "PYTHONIOENCODING", "NO_COLOR", "COLUMNS"}
SEP = {"&&", "||", ";", "|", "&", "|&"}
FIND_BAD = {"-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"}
PY_BAD = re.compile(r"open\([^)]*['\"][wax+]|\.write_(text|bytes)|\bos\.(remove|unlink|rename|replace|rmdir|"
r"mkdir|makedirs|system|popen|exec|spawn)|shutil|subprocess|\.touch\(|socket|urllib|requests")
WRITE_TOOLS = {"Write", "Edit", "MultiEdit", "NotebookEdit"}
OPCH = ";&|()<>"
def tokens(command):
"""(종류, 글, 앞 낱말에 붙었나) 목록을 낸다. 종류는 w(낱말)·op. 못 읽으면 ValueError."""
out, word, has, i, n = [], [], False, 0, len(command)
def flush():
nonlocal word, has
if has:
out.append(("w", "".join(word), False))
word, has = [], False
while i < n:
c = command[i]
if c == "\\":
if i + 1 < n and command[i + 1] == "\n":
i += 2
continue
if i + 1 >= n:
raise ValueError("끝이 역슬래시")
word.append(command[i + 1]); has = True; i += 2
continue
if c == "'":
j = command.find("'", i + 1)
if j < 0:
raise ValueError("따옴표가 닫히지 않음")
word.append(command[i + 1:j]); has = True; i = j + 1
continue
if c == '"':
j = i + 1
while j < n and command[j] != '"':
if command[j] == "\\" and j + 1 < n:
word.append(command[j + 1]); j += 2
continue
if command[j] == "`" or command[j:j + 2] == "$(":
raise ValueError("명령 치환")
word.append(command[j]); j += 1
if j >= n:
raise ValueError("따옴표가 닫히지 않음")
has = True; i = j + 1
continue
if c == "`" or command[i:i + 2] in ("$(", "<(", ">("):
raise ValueError("명령 치환")
if c == "\n":
flush(); out.append(("op", ";", False)); i += 1
continue
if c in " \t\r":
flush(); i += 1
continue
if c == "#" and not has:
while i < n and command[i] != "\n":
i += 1
continue
if c in OPCH:
glued = has
flush()
j = i
while j < n and command[j] in OPCH and command[j] not in "()" and j - i < 3:
j += 1
if c in "()":
j = i + 1
out.append(("op", command[i:j], glued)); i = j
continue
word.append(c); has = True; i += 1
flush()
return out
def segment_problem(seg, cfg):
while seg and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", seg[0], re.S):
if seg[0].split("=", 1)[0] not in ENV_OK:
return "환경 변수 " + seg[0].split("=", 1)[0]
seg = seg[1:]
if not seg:
return None
for pre in cfg["run"]:
if seg[:len(pre)] == pre:
return None
cmd, args = seg[0], seg[1:]
if cmd == "git":
while args[:1] in (["-C"], ["--no-pager"]):
args = args[2:] if args[0] == "-C" else args[1:]
if not args or args[0] not in cfg["git"]:
return "git " + (args[0] if args else "")
if any(a.startswith("--output") or a.startswith("--ext-diff") for a in args):
return "git 출력 파일"
return None
if cmd == "python3":
if args[:1] != ["-I"]:
return "python3는 -I로"
rest = args[1:]
if rest[:1] == ["-c"]:
if not cfg["py"]:
return "python3 -c"
return "python3 코드가 파일·프로세스를 건드린다" if PY_BAD.search(rest[1] if len(rest) > 1 else "") else None
if cfg["pyfile"] and rest and rest[0].endswith(".py") and not rest[0].startswith("-"):
return None
return "python3 " + (rest[0] if rest else "")
if cmd not in cfg["cmd"]:
return cmd
if cmd == "find" and any(a in FIND_BAD for a in args):
return "find의 쓰는 옵션"
if cmd == "sed" and any(a == "--in-place" or re.fullmatch(r"-[a-zA-Z]*i.*", a) for a in args):
return "sed -i"
if cmd == "awk":
prog = [a for k, a in enumerate(args) if not a.startswith("-F") and (k == 0 or args[k - 1] != "-F")]
if any(a == "-f" or ">" in a or "system(" in a or "|" in a for a in prog):
return "awk의 쓰기·실행"
return None
def bash_problem(command, cfg):
try:
toks = tokens(command)
except ValueError as e:
return str(e)
seg, i = [], 0
while i < len(toks):
kind, text, glued = toks[i]
if kind == "w":
seg.append(text)
elif text in SEP:
p = segment_problem(seg, cfg)
if p:
return p
seg = []
elif text in ("(", ")"):
return "괄호 묶음"
else:
nxt = toks[i + 1] if i + 1 < len(toks) else ("", "", False)
if nxt[0] != "w":
return "돌리기 대상 없음"
if text in ("<", "<<<"):
pass
elif text in (">", ">>", "&>") and nxt[1] == "/dev/null":
pass
elif text == ">&" and nxt[1] in ("1", "2"):
pass
else:
return "출력 돌리기 " + text
if glued and seg and seg[-1] in ("1", "2") and text != "<":
seg.pop()
i += 1
i += 1
return segment_problem(seg, cfg)
def write_problem(path, dirs, base):
if not dirs:
return None
full = os.path.realpath(path if os.path.isabs(path) else os.path.join(base, path))
for d in dirs:
root = os.path.realpath(d if os.path.isabs(d) else os.path.join(base, d))
if full.startswith(root + os.sep):
return None
return "쓸 수 있는 곳은 " + ", ".join(dirs) + " 안뿐"
def config(argv):
cfg = {"git": set(), "cmd": set(), "py": False, "pyfile": False, "run": [], "write": []}
i = 0
while i < len(argv):
a = argv[i]
if a in ("--py", "--pyfile"):
cfg[a[2:]] = True
i += 1
continue
if a not in ("--git", "--cmd", "--run", "--write") or i + 1 >= len(argv):
raise ValueError("모르는 인자 " + a)
v = argv[i + 1]
if a in ("--git", "--cmd"):
names = {x for x in v.split(",") if x}
extra = names - (READ_GIT if a == "--git" else READ_CMD)
if extra:
raise ValueError("%s에 읽기 명령이 아닌 것: %s" % (a, ",".join(sorted(extra))))
cfg[a[2:]] |= names
elif a == "--run":
pre = [t[1] for t in tokens(v)]
if not pre or any(t[0] != "w" for t in tokens(v)):
raise ValueError("--run 앞머리가 비었거나 연산자가 있다")
cfg["run"].append(pre)
else:
cfg["write"].append(v)
i += 2
return cfg
def main(argv):
try:
cfg = config(argv)
except ValueError as e:
sys.stderr.write("읽기 전용 가드 설정 오류: %s\n" % e)
return 2
try:
d = json.load(sys.stdin)
except Exception:
sys.stderr.write("읽기 전용 가드가 입력을 못 읽음\n")
return 2
tool, inp = d.get("tool_name"), d.get("tool_input") or {}
if tool == "Bash":
p = bash_problem(inp.get("command", ""), cfg)
elif tool in WRITE_TOOLS:
base = os.environ.get("CLAUDE_PROJECT_DIR") or d.get("cwd") or os.getcwd()
p = write_problem(inp.get("file_path") or inp.get("notebook_path") or "", cfg["write"], base)
else:
p = None
if p:
sys.stderr.write("읽기 전용 가드가 막음: %s. 이 에이전트 본문의 허용 명령만 쓴다\n" % p)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))