#!/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 and the # Claude settings, documents left out. Everything else is checked by gates that need pnpm, documents # included: verify:documentation reads CLAUDE.md, the folder rule books under src/, .claude/**/*.md and # the module READMEs of scripts/hooks/ and docs/ledger/ too (1112/08-04). LAPTOP_ONLY = ( re.compile(r"^\.claude/(?!.*\.md$)"), re.compile(r"^scripts/hooks/(?!.*\.md$)"), re.compile(r"^scripts/tests/(?!.*\.md$)"), re.compile(r"^scripts/check-work-docs\.py$"), re.compile(r"^docs/ledger/(?!.*\.md$)"), ) DESKTOP_HOST = re.compile(r"desktop") DESKTOP_WORK = re.compile(r"\b(?:pnpm|ci:gate|verify\.sh|vitest|playwright)\b|\bnode\s+scripts/") LAPTOP_STAGES = {"docs", "hooks"} # 1112/08-09. One command of a shell line: what follows ;, &&, ||, |, ( or a newline. COMMAND_SEPARATOR = re.compile(r"&&|\|\||;|\||\(|\)|\n") # Words that run the next command: `timeout 900 scripts/verify.sh …`, `bash scripts/verify.sh …`. WRAPPERS = {"timeout": 1, "nohup": 0, "setsid": 0, "env": 0, "time": 0, "exec": 0, "bash": 0, "sh": 0} # ssh options that take the next word as their value (`ssh -o BatchMode=yes desktop …`). SSH_VALUE_OPTIONS = {"-B", "-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-P", "-p", "-Q", "-R", "-S", "-W", "-w"} # A remote command made only of these reads logs; it runs nothing. READ_ONLY = {"cat", "grep", "tail", "head", "less", "ls", "sed", "awk", "wc", "find", "stat", "echo", "printf", "date", "uptime", "ps", "test", "true", "for", "do", "done", "if", "then", "fi"} ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") STEP_WORD = re.compile(r"^[a-z][a-z0-9-]*$") # ---------------------------------------------------------------------------------------------------- # 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 split_words(text: str) -> list[str]: try: return shlex.split(text) except ValueError: return text.split() def command_words(segment: str) -> list[str]: """The words of one command, its leading `VAR=value` and wrapper words dropped.""" words = split_words(segment) while words: if ASSIGNMENT.match(words[0]): words = words[1:] elif words[0] in WRAPPERS: words = words[1 + WRAPPERS[words[0]]:] else: break return words def ssh_host_and_remote(words: list[str]) -> tuple[str | None, str]: """The host and the remote command of the words after `ssh`, its options and their values skipped.""" position = 0 while position < len(words) and words[position].startswith("-"): position += 2 if words[position] in SSH_VALUE_OPTIONS else 1 if position >= len(words): return None, "" return words[position], " ".join(words[position + 1:]) def runs_only_reads(remote: str) -> bool: segments = [command_words(part) for part in COMMAND_SEPARATOR.split(remote)] return all(not words or words[0] in READ_ONLY for words in segments) def ran_on_desktop(command: str) -> bool: """An `ssh …` running pnpm or a gate, or scripts/verify.sh running a step that goes there. 1112/08-09. Reading verify.sh (`sed`, `grep`, `git log -- scripts/verify.sh`), `--dry-run` and an ssh that only reads logs run nothing on the desktop. """ words = split_words(command) for position, word in enumerate(words): if word.endswith("ssh"): host, remote = ssh_host_and_remote(words[position + 1:]) if (host is not None and DESKTOP_HOST.search(host) and DESKTOP_WORK.search(remote) and not runs_only_reads(remote)): return True for segment in COMMAND_SEPARATOR.split(command): words = command_words(segment) if len(words) < 2 or not re.search(r"(?:^|/)scripts/verify\.sh$", words[0]): continue step, flags = words[1], words[2:] if (STEP_WORD.match(step) and step not in LAPTOP_STAGES and "--dry-run" not in flags and not re.search(r"--on\s+here\b", " ".join(flags))): 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:]))