Files
clean-architecture-frontend…/scripts/hooks/hooks.py
DongHyeonka f117a5af41 docs(src): 계층 폴더마다 지역 규칙 AGENTS.md를 두고 CLAUDE.md가 가져온다
계층별 규칙이 Claude만 읽는 .claude/rules/에만 있어 다른 에이전트에는
보이지 않았다. 하네스 자료의 3단계는 레이어마다 그 폴더에 AGENTS.md다.

src/의 9개 계층 폴더마다 AGENTS.md(16~20줄)를 둔다: 그 폴더가 하는 일,
그 폴더에만 걸리는 import 금지(.dependency-cruiser.json에서 from이 그
폴더에 맞는 규칙을 뽑아 이름과 함께), 검사하는 게이트, 테스트 위치. 모든
폴더에 걸리는 규칙은 루트 AGENTS.md와 layers.md를 가리킨다. 옆에
@AGENTS.md 한 줄 CLAUDE.md를 둬 Claude Code가 그 폴더 파일을 열 때 같은
책을 읽는다(백엔드와 같은 짝).

- .claude/rules/adapters·features는 폴더 AGENTS.md를 가리키게 줄였다.
- scripts/check-work-docs.py: src/**/AGENTS.md도 이력 ID 0·200줄·짝·링크를
  본다. 훅 N5는 이 파일들을 노트북 확인 파일로 친다.
- docs/reviews/adapters/INVENTORY.md: check:adapter-inventory가 src/adapters
  아래 추적 파일을 모두 요구하므로 두 행(142·143)을 더했다.
- 루트 AGENTS.md 지도가 가장 가까운 src/<계층>/AGENTS.md와 비전·문제 정의
  양식을 가리킨다.

버린 대안: .claude/rules/만 두기(다른 에이전트가 못 읽는다), 폴더 CLAUDE.md
없이 AGENTS.md만(Claude Code는 같은 폴더에 CLAUDE.md가 없고 Read로 열 때만
읽어 백엔드와 갈린다).

위험·한계: 규칙 이름은 지금 규칙 파일에서 뽑았다. 규칙을 더하거나 바꾸면
이 문서도 손으로 고쳐야 한다(정본은 규칙 파일과 check:architecture).

검증: scripts/verify.sh docs rc=0(src/**/AGENTS.md 9개, 최대 20/200),
python3 -m unittest discover -s scripts/tests 62건 통과.
2026-11-08 22:57:03 +09:00

376 lines
16 KiB
Python
Executable File

#!/usr/bin/env python3
"""Claude Code repo hooks: nudge right after an edit, remind at the end of a turn.
Called by `.claude/settings.json`, one event per invocation, with the hook input JSON on stdin:
python3 scripts/hooks/hooks.py post-edit # PostToolUse Edit|Write|MultiEdit N3, N6, N2
python3 scripts/hooks/hooks.py post-bash # PostToolUse Bash records desktop runs
python3 scripts/hooks/hooks.py stop # Stop N5
What each ID does, and why it nudges instead of blocking, is in scripts/hooks/README.md. A nudge
exits 0 and adds at most a few lines to the model's context. No hook blocks an edit: nothing an edit
does inside this repository is irreversible, and the commands that are (force push, wide `rm -r`)
are the owner's global hook and the harness plugin. No hook runs pnpm, node, eslint or a browser:
the owner's laptop never does (docs/work/operate.md 4.1). The format, lint and type checks run on
the desktop through scripts/verify.sh. Standard library and git only. The tests are
scripts/tests/test_hooks.py.
"""
from __future__ import annotations
import json
import os
import re
import shlex
import subprocess
import sys
from pathlib import Path
RULES = ".dependency-cruiser.json"
STATE_DIR = ".claude/hook-state"
EDIT_TOOLS = ("Edit", "Write", "MultiEdit")
MAX_LINES = 5
# --- N3: the import rules check:architecture holds, checked on the imports of one edited source -----------
SOURCE = re.compile(r"^src/.+\.(?:ts|tsx|mts|cts)$")
# Static imports and re-exports (type-only ones too: the architecture graph counts them), side-effect
# imports, dynamic import() with a literal and require() with a literal.
SPECIFIER = re.compile(
r"""(?:^|[\s;}])(?:import|export)\s+[^'"`;]*?\bfrom\s*['"]([^'"\n]+)['"]"""
r"""|(?:^|[\s;])import\s*['"]([^'"\n]+)['"]"""
r"""|\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)"""
r"""|\brequire\s*\(\s*['"]([^'"\n]+)['"]\s*\)""",
re.M | re.S,
)
RESOLVE_SUFFIXES = ("", ".ts", ".tsx", ".mts", ".js", ".jsx", "/index.ts", "/index.tsx")
# Which of AGENTS.md's "꼭 지킬 것" a broken rule is; every other rule is item 3 (the import rules).
RULE_ITEMS = {
"adapter-groups-are-reached-through-their-barrel": "꼭 지킬 것 1",
"adapters-do-not-know-other-concrete-adapters": "꼭 지킬 것 2",
}
# --- N6: gate standards that an edit can lower -------------------------------------------------------------
TEST_SOURCE = re.compile(r"(?:^tests/.+|\.(?:test|spec|stories)\.[cm]?[jt]sx?)$")
LOWERING = re.compile(r"\b(?:it|test|describe|suite|bench|context)(?:\.\w+)*\.(skip|only|fixme|todo)\b")
# Files whose numbers or lists are the gates' standards: budgets, ceilings, baselines, the ungated
# allow-lists, coverage thresholds, snapshots and visual goldens.
GATE_STANDARDS = (
re.compile(r"^config/performance/budgets\.json$"),
re.compile(r"^config/scale/.+\.json$"),
re.compile(r"^config/testing/.+\.json$"),
re.compile(r"^config/ci/ungated-[^/]+\.json$"),
re.compile(r"^config/.*baseline[^/]*\.json$"),
re.compile(r"^vitest\.config\.ts$"),
re.compile(r"(?:^|/)__snapshots__/"),
re.compile(r"\.snap$"),
)
# --- N2: the work-manual check a document edit can break ---------------------------------------------------
DOC_CHECK = ("scripts/check-work-docs.py",)
DOC_TIMEOUT = 20
# --- N5: an edit that only the desktop can check, until a desktop run --------------------------------------
# Laptop-checkable on their own: the hooks and their tests, the work-manual checker, the ledger, Claude
# settings, CLAUDE.md and the folder rule books under src/ (scripts/check-work-docs.py checks them). Everything else is checked by gates that need pnpm.
LAPTOP_ONLY = (
re.compile(r"^\.claude/"),
re.compile(r"^scripts/hooks/"),
re.compile(r"^scripts/tests/"),
re.compile(r"^scripts/check-work-docs\.py$"),
re.compile(r"^docs/ledger/"),
re.compile(r"^CLAUDE\.md$"),
re.compile(r"^src/(?:.+/)?(?:AGENTS|CLAUDE)\.md$"),
)
DESKTOP_HOST = re.compile(r"desktop")
DESKTOP_WORK = re.compile(r"\b(?:pnpm|ci:gate|verify\.sh|vitest|playwright)\b|\bnode\s+scripts/")
VERIFY = re.compile(r"(?:^|[\s;&|(])(?:\./)?scripts/verify\.sh\s+(\S+)(.*)")
LAPTOP_STAGES = {"docs", "hooks"}
# ----------------------------------------------------------------------------------------------------
# plumbing
def project_root(payload: dict) -> Path:
root = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd()
return Path(root).resolve()
def relative(root: Path, file_path: str | None) -> str | None:
if not file_path:
return None
path = Path(file_path)
if not path.is_absolute():
path = root / path
try:
return path.resolve().relative_to(root).as_posix()
except ValueError:
return None
def edited_path(payload: dict) -> str | None:
if payload.get("tool_name") not in EDIT_TOOLS:
return None
return relative(project_root(payload), (payload.get("tool_input") or {}).get("file_path"))
def context(event: str, lines: list[str]) -> str:
"""The PostToolUse output that adds lines to the model's context without blocking."""
text = "\n".join(lines[:MAX_LINES] + ([f"(… {len(lines) - MAX_LINES}줄 더)"] if len(lines) > MAX_LINES else []))
return json.dumps({"hookSpecificOutput": {"hookEventName": event, "additionalContext": text}},
ensure_ascii=False)
def state_file(root: Path, session_id: str) -> Path:
safe = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "unknown")
return root / STATE_DIR / f"{safe}.json"
def load_state(root: Path, session_id: str) -> dict:
try:
state = json.loads(state_file(root, session_id).read_text(encoding="utf-8"))
except (OSError, ValueError):
state = {}
state.setdefault("pending", [])
state.setdefault("reminded", False)
return state
def save_state(root: Path, session_id: str, state: dict) -> None:
path = state_file(root, session_id)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
# ----------------------------------------------------------------------------------------------------
# N3 — imports of one edited source against the forbidden rules of .dependency-cruiser.json
def load_rules(root: Path) -> list[dict]:
try:
rules = json.loads((root / RULES).read_text(encoding="utf-8")).get("forbidden", [])
except (OSError, ValueError):
return []
# The cycle rule needs the whole graph; the gate holds it.
return [rule for rule in rules if "path" in (rule.get("to") or {})]
def specifiers(source: str) -> list[str]:
found = []
for groups in SPECIFIER.findall(source):
value = next((group for group in groups if group), None)
if value and value not in found:
found.append(value)
return found
def resolve(root: Path, path: str, specifier: str) -> str:
"""A relative specifier as a repository path (the file it names when one exists); a package as itself."""
if not specifier.startswith("."):
return specifier
base = os.path.normpath(os.path.join(os.path.dirname(path), specifier)).replace(os.sep, "/")
stem = re.sub(r"\.(?:js|jsx|mjs)$", "", base)
for candidate in (base, *(stem + suffix for suffix in RESOLVE_SUFFIXES)):
if (root / candidate).is_file():
return candidate
return base
def broken_rules(rules: list[dict], path: str, target: str) -> list[str]:
broken = []
for rule in rules:
origin, to = rule.get("from") or {}, rule.get("to") or {}
match = re.search(origin.get("path", ""), path)
if match is None or ("pathNot" in origin and re.search(origin["pathNot"], path)):
continue
group = re.escape(match.group(1)) if match.re.groups and match.group(1) is not None else ""
if not re.search(to["path"].replace("$1", group), target):
continue
if "pathNot" in to and re.search(to["pathNot"].replace("$1", group), target):
continue
broken.append(rule["name"])
return broken
def boundary_findings(root: Path, path: str, source: str) -> list[str]:
if not SOURCE.match(path) or path.endswith(".d.ts"):
return []
rules = load_rules(root)
findings = []
for specifier in specifiers(source):
target = resolve(root, path, specifier)
for name in broken_rules(rules, path, target):
findings.append(f"- {RULE_ITEMS.get(name, '꼭 지킬 것 3')} 의심: `{name}` — `{specifier}`(→ `{target}`)")
if len(findings) > 2:
# One wrong import usually breaks several rules; the first two say what to look at.
findings = findings[:2] + [f"- 외 {len(findings) - 2}개"]
if findings:
findings.insert(0, f"경계 알림(N3) {path}")
findings.append("정본은 게이트다: desktop `scripts/verify.sh gate FE-GATE-010`(check:architecture). "
"kernel 예외를 늘려 풀지 않는다.")
return findings
# ----------------------------------------------------------------------------------------------------
# N6 — skip·only·fixme·todo added to a test, or a gate standard file changed
def committed(root: Path, path: str) -> str:
try:
result = subprocess.run(["git", "show", f"HEAD:{path}"], cwd=root, capture_output=True, text=True,
timeout=5)
except (OSError, subprocess.TimeoutExpired):
return ""
return result.stdout if result.returncode == 0 else ""
def lowering_counts(source: str) -> dict[str, int]:
counts: dict[str, int] = {}
for word in LOWERING.findall(source):
counts[word] = counts.get(word, 0) + 1
return counts
def standard_findings(root: Path, path: str, source: str) -> list[str]:
lines = []
if any(pattern.search(path) for pattern in GATE_STANDARDS):
lines.append(f"게이트 기준 알림(N6) {path}는 게이트의 기준 파일(예산·기준선·ungated 목록·스냅숏)이다.")
elif TEST_SOURCE.search(path):
before, after = lowering_counts(committed(root, path)), lowering_counts(source)
grown = [f"`.{word}` {before.get(word, 0)}→{count}" for word, count in sorted(after.items())
if count > before.get(word, 0)]
if grown:
lines.append(f"게이트 기준 알림(N6) {path}: 마지막 커밋보다 {', '.join(grown)}.")
if lines:
lines.append("꼭 지킬 것 4: 기준을 낮춰 통과시키지 않는다. 의도한 변경이면 이유와 결정 출처를 커밋 본문에 적는다.")
return lines
# ----------------------------------------------------------------------------------------------------
# N2 — the work-manual check, failures only
def wants_doc_check(path: str | None) -> bool:
return bool(path) and path.endswith(".md") and not path.startswith(STATE_DIR + "/")
def doc_findings(root: Path, path: str) -> list[str]:
if not (root / DOC_CHECK[0]).is_file():
return []
try:
result = subprocess.run([sys.executable, *DOC_CHECK], cwd=root, capture_output=True, text=True,
timeout=DOC_TIMEOUT)
except subprocess.TimeoutExpired:
return [f"문서 검사 알림(N2): {DOC_CHECK[0]}가 {DOC_TIMEOUT}초 안에 끝나지 않았다"]
if result.returncode == 0:
return []
lines = [line.strip() for line in result.stderr.splitlines() if line.startswith(" ") and line.strip()]
mine = [line for line in lines if path in line]
return [f"문서 검사 알림(N2) {path} 편집 뒤 실패 줄:", *[f"- {line}" for line in (mine or lines)]]
# ----------------------------------------------------------------------------------------------------
# N5 — something only the desktop can check changed, and the desktop has not run since
def needs_desktop(path: str) -> bool:
return not any(pattern.search(path) for pattern in LAPTOP_ONLY)
def ran_on_desktop(command: str) -> bool:
"""An `ssh <desktop> …` running pnpm or a gate, or scripts/verify.sh with a stage that goes there."""
try:
words = shlex.split(command)
except ValueError:
words = command.split()
for position, word in enumerate(words):
if word.endswith("ssh"):
hosts = [w for w in words[position + 1:position + 5] if not w.startswith("-")][:2]
if any(DESKTOP_HOST.search(host) for host in hosts) and DESKTOP_WORK.search(command):
return True
for match in VERIFY.finditer(command):
stage, rest = match.group(1), match.group(2)
if stage not in LAPTOP_STAGES and not re.search(r"--on\s+here\b", rest):
return True
return False
def turn_end_reason(state: dict) -> str | None:
edits = state.get("pending") or []
if not edits or state.get("reminded"):
return None
shown = ", ".join(f"`{edit}`" for edit in edits[:3]) + (f" 외 {len(edits) - 3}개" if len(edits) > 3 else "")
return (f"[N5 턴 끝 알림] 이 세션에서 파일 {len(edits)}개를 고쳤고({shown}) 그 뒤 desktop 실행이 없다. "
"포맷·린트·타입·테스트·문서 검사는 노트북이 아니라 desktop에서 `scripts/verify.sh gate FE-GATE-0NN`이나 "
"`scripts/verify.sh merge`로 한다(docs/work/operate.md 4.1절). 이번 턴에 돌릴 수 없으면 완료를 말하지 말고, "
"보고의 확인 줄에 돌리지 못한 것과 이유를 적는다(꼭 지킬 것 5). 이 알림은 다음 편집 전까지 한 번만 나온다.")
# ----------------------------------------------------------------------------------------------------
# events
def post_edit(payload: dict) -> int:
root = project_root(payload)
path = edited_path(payload)
if path is None or not (root / path).is_file():
return 0
try:
source = (root / path).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
source = ""
lines = boundary_findings(root, path, source) + standard_findings(root, path, source)
if wants_doc_check(path):
lines += doc_findings(root, path)
if needs_desktop(path):
state = load_state(root, payload.get("session_id", ""))
if path not in state["pending"]:
state["pending"].append(path)
state["reminded"] = False
save_state(root, payload.get("session_id", ""), state)
if lines:
print(context("PostToolUse", lines))
return 0
def post_bash(payload: dict) -> int:
command = (payload.get("tool_input") or {}).get("command", "")
if ran_on_desktop(command):
root = project_root(payload)
state = load_state(root, payload.get("session_id", ""))
state["pending"] = []
state["reminded"] = False
save_state(root, payload.get("session_id", ""), state)
return 0
def stop(payload: dict) -> int:
if payload.get("stop_hook_active"):
return 0
root = project_root(payload)
state = load_state(root, payload.get("session_id", ""))
reason = turn_end_reason(state)
if reason:
state["reminded"] = True
save_state(root, payload.get("session_id", ""), state)
print(json.dumps({"decision": "block", "reason": reason}, ensure_ascii=False))
return 0
EVENTS = {"post-edit": post_edit, "post-bash": post_bash, "stop": stop}
def main(argv: list[str]) -> int:
if len(argv) != 1 or argv[0] not in EVENTS:
print(f"usage: hooks.py {{{'|'.join(EVENTS)}}} < hook-input.json", file=sys.stderr)
return 1
try:
payload = json.load(sys.stdin)
except ValueError:
return 0
return EVENTS[argv[0]](payload if isinstance(payload, dict) else {})
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))