Files
clean-architecture-frontend…/scripts/tests/test_agent_guard.py
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

90 lines
4.1 KiB
Python

"""서브에이전트 머리 칸의 읽기 전용 가드(`.claude/hooks/readonly_bash.py`) 시험.
가드 자체의 시험(`.claude/hooks/test_readonly_bash.py`)을 돌리고, 가드를 건 서브에이전트마다 머리 칸에 적힌
그대로의 인자로 본문의 허용 명령은 통과하고 쓰는 명령은 막히는지 본다(scripts/hooks/README.md 1절).
python3 -m unittest discover -s scripts/tests
"""
from __future__ import annotations
import json
import os
import re
import shlex
import subprocess
import sys
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent.parent
AGENTS = REPO / ".claude/agents"
HOOKS = REPO / ".claude/hooks"
GUARD_PATH = "$CLAUDE_PROJECT_DIR/.claude/hooks/readonly_bash.py"
# Subagents that hold Bash and return results only; each runs Bash through the guard.
GUARDED = {"reviewer"}
# Bash agents left without a guard, with the reason. verify-app runs compound commands on desktop
# (`ssh desktop '<cd, flock, pnpm>'`) and writes a temporary spec there; no single command prefix opens only those.
UNGUARDED = {"verify-app"}
ALLOWED_LINE = "Bash는 읽기 명령만 쓴다:"
GUARD_COMMAND = re.compile(r"^\s+command: '(.+)'\s*$", re.M)
MUST_BLOCK = ("touch x", "ls / > x", "git log -1\ntouch x", "rm -rf x", "git checkout main", "git stash",
"git commit -m x", "python3 scripts/check-work-docs.py", "git diff --output=x")
def front_matter(agent: str) -> str:
return (AGENTS / f"{agent}.md").read_text(encoding="utf-8").split("---", 2)[1]
def guard_args(agent: str) -> list[str]:
match = GUARD_COMMAND.search(front_matter(agent))
if not match:
raise AssertionError(f"{agent}: no guard command in the front matter")
words = shlex.split(match.group(1))
if words[:3] != ["python3", "-I", GUARD_PATH]:
raise AssertionError(f"{agent}: the guard command must start with python3 -I {GUARD_PATH}")
return words[3:]
def allowed_commands(agent: str) -> list[str]:
body = (AGENTS / f"{agent}.md").read_text(encoding="utf-8").split("---", 2)[2]
line = next(line for line in body.splitlines() if ALLOWED_LINE in line)
return re.findall(r"`([^`]+)`", line.split(ALLOWED_LINE, 1)[1].split(". ", 1)[0])
def guard_rc(args: list[str], command: str) -> int:
data = json.dumps({"tool_name": "Bash", "tool_input": {"command": command}})
env = dict(os.environ, CLAUDE_PROJECT_DIR=str(REPO))
done = subprocess.run([sys.executable, "-I", str(HOOKS / "readonly_bash.py"), *args], input=data,
capture_output=True, text=True, env=env, timeout=30)
return done.returncode
class AgentGuardTest(unittest.TestCase):
def test_the_guard_passes_its_own_tests(self) -> None:
done = subprocess.run([sys.executable, "-I", str(HOOKS / "test_readonly_bash.py")], capture_output=True,
text=True, timeout=120)
self.assertEqual(done.returncode, 0, done.stderr[-2000:])
def test_every_bash_agent_is_guarded_or_named_with_its_reason(self) -> None:
for path in sorted(AGENTS.glob("*.md")):
tools = re.search(r"^tools:(.*)$", front_matter(path.stem), re.M)
if tools and "Bash" in {tool.strip() for tool in tools.group(1).split(",")}:
self.assertIn(path.stem, GUARDED | UNGUARDED, f"{path}: a Bash agent needs a guard")
for agent in UNGUARDED:
self.assertIsNone(GUARD_COMMAND.search(front_matter(agent)), agent)
def test_the_body_commands_pass_the_guard_and_writes_do_not(self) -> None:
for agent in sorted(GUARDED):
args = guard_args(agent)
allowed = allowed_commands(agent)
self.assertTrue(allowed, f"{agent}: the body must list its Bash commands after '{ALLOWED_LINE}'")
for command in allowed + [f"{allowed[0]} --stat HEAD~1...HEAD -- .claude"]:
self.assertEqual(guard_rc(args, command), 0, f"{agent} must run: {command}")
for command in MUST_BLOCK:
self.assertEqual(guard_rc(args, command), 2, f"{agent} must not run: {command!r}")
if __name__ == "__main__":
unittest.main()