경계 위반, 늘어난 skip·only, 작업 매뉴얼 규칙 위반은 desktop 게이트에서야 드러났고, desktop 검증 없이 턴을 끝내도 아무것도 알리지 않았다. scripts/hooks/hooks.py(백엔드 hooks.py와 같은 모양, 표준 라이브러리와 git만)를 .claude/settings.json에 단다. - N3: src TypeScript를 고치면 import를 .dependency-cruiser.json의 forbidden 규칙(path·pathNot·$1)에 그대로 대 본다. 규칙 파일을 읽으므로 규칙이 바뀌면 따라간다. - N6: 테스트에 .skip·.only·.fixme·.todo가 마지막 커밋보다 늘거나, 예산· 기준선·ungated 목록·스냅숏을 고치면 알린다. - N2: .md를 고치면 scripts/check-work-docs.py의 실패 줄을 알린다. - N5: desktop만 확인할 수 있는 파일을 고친 뒤 desktop 실행이 없으면 턴 끝을 한 번 막고 이유를 준다. 모두 넛지다. repo 안 편집에 되돌릴 수 없는 것이 없어 차단 훅은 없다. 고른 방법: 노트북에서는 정적 검사만 하고 포맷·린트·타입은 desktop scripts/verify.sh에 둔다(brief, 2026-11-08). 설계 13절 Q6은 편집 훅에서 한 파일 eslint를 골랐지만, 프론트 eslint는 pnpm·node_modules가 필요해 "pnpm은 desktop에서만" 규칙과 부딪친다. 위험·한계: N3는 정규식으로 import를 뽑아 주석 속 따옴표 같은 드문 모양을 놓칠 수 있다. 정본은 check:architecture다. 훅 시험은 아직 CI workflow가 부르지 않는다. 훅은 세션 시작에 읽혀 이 세션에서는 돌지 않았다. 검증: python3 -m unittest scripts/tests/test_hooks.py 26건 통과. 실제 규칙과 src 377개 파일에서 N3 알림 0(거짓 양성 시험). 조건 하나씩 끈 변이 10개를 모두 시험이 잡았다. Refs: design-docs harness/01-harness-design.md 5.2·5.3절
375 lines
15 KiB
Python
Executable File
375 lines
15 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 and CLAUDE.md. 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$"),
|
|
)
|
|
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:]))
|