diff --git a/.claude/settings.json b/.claude/settings.json index 5dfb8657..af316bde 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -15,6 +15,29 @@ "Edit(**/.env.production)" ] }, + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + {"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/scripts/hooks/hooks.py post-edit", "timeout": 30} + ] + }, + { + "matcher": "Bash", + "hooks": [ + {"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/scripts/hooks/hooks.py post-bash", "timeout": 10} + ] + } + ], + "Stop": [ + { + "hooks": [ + {"type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/scripts/hooks/hooks.py stop", "timeout": 10} + ] + } + ] + }, "extraKnownMarketplaces": { "claude-harness": { "source": { diff --git a/scripts/hooks/README.md b/scripts/hooks/README.md new file mode 100644 index 00000000..b713ab80 --- /dev/null +++ b/scripts/hooks/README.md @@ -0,0 +1,46 @@ +# repo 훅 + +Claude Code가 정해진 때에 대신 실행하는 명령이다. 연결은 `.claude/settings.json`, 본체는 `hooks.py` 하나, 시험은 `scripts/tests/test_hooks.py`다. 모델이 잊어도 돈다. + +```text +Edit·Write 직후 ──> post-edit ──> src TypeScript면 N3 경계 알림, 테스트·기준 파일이면 N6 게이트 기준 알림, 문서면 N2 문서 검사 알림 +Bash 직후 ──> post-bash ──> desktop에서 pnpm·게이트를 돌렸으면 N5 기록을 비운다 +턴 끝 ──> stop ──> N5 desktop이 확인해야 할 파일을 고쳤는데 desktop 실행이 없으면 한 번 알린다 +``` + +## 1. 원칙 + +- 막지 않는다. 모두 알리기만 한다(넛지). 알림은 종료 코드 0이고, 모델 컨텍스트에 몇 줄(최대 5줄)만 더한다. 이 repo 안에서 편집 하나가 되돌릴 수 없는 일을 하지 않아서, 편집 전 차단 훅은 없다. 되돌릴 수 없는 명령 차단(force push, 범위 밖 `rm -rf`, DB·볼륨 삭제)과 비밀 값 알림은 repo가 아니라 소유자 전역 훅과 하네스 플러그인 `harness@claude-harness` 몫이다. +- 훅은 게이트의 일부만 본다. 정본은 게이트(desktop `check:architecture`, `lint`, `check:types`, `verify:documentation`)다. 훅이 틀리면 훅을 고치거나 끄고, 게이트는 그대로 둔다. +- 노트북에서 pnpm·node·eslint·브라우저를 돌리지 않는다. 포맷·린트·타입 검사는 desktop의 `scripts/verify.sh`에서 돈다(소유자 결정 2026-11-08, `docs/work/reference/decisions.md`). 그래서 편집 직후 훅은 Python 표준 라이브러리와 git만 쓰는 정적 검사이고, 1초 안에 끝난다. +- 받거나 설치하지 않는다. 의존성이 없다. + +## 2. 훅마다 + +| ID | 때 | 하는 일 | 결과 | +| --- | --- | --- | --- | +| N3 | PostToolUse `Edit\|Write\|MultiEdit`, `src/**/*.{ts,tsx}`(`.d.ts` 제외) | 편집한 파일의 import(정적·type-only·re-export·리터럴 dynamic import·require)를 경로로 풀고, `.dependency-cruiser.json`의 `forbidden` 규칙(`from`·`to`의 `path`·`pathNot`, `$1` 치환)에 대 본다. 사이클 규칙은 그래프 전체가 필요해 보지 않는다 | 「꼭 지킬 것 N 의심」 줄(규칙 이름과 import), 정본 게이트 안내 | +| N6 | 같은 때, 테스트 파일(`tests/**`, `*.test.*`·`*.spec.*`·`*.stories.*`) | 마지막 커밋(`git show HEAD:`)보다 `.skip`·`.only`·`.fixme`·`.todo`가 늘었는지 센다 | 늘어난 수와 「꼭 지킬 것 4」 | +| N6 | 같은 때, 게이트 기준 파일(`config/performance/budgets.json`, `config/scale/`, `config/testing/`, `config/ci/ungated-*.json`, `config/**/*baseline*.json`, `vitest.config.ts`, 스냅숏) | 편집 자체를 알린다 | 「게이트의 기준 파일」 한 줄과 「꼭 지킬 것 4」 | +| N2 | 같은 때, `*.md` | `scripts/check-work-docs.py`를 돌린다(작업 매뉴얼의 분량·이력 ID·뼈대·상대 링크) | 실패 줄. 고친 문서를 가리키는 줄이 있으면 그것만 | +| N5 | Stop | 이 세션에서 desktop만 확인할 수 있는 파일(아래 밖의 모든 파일)을 고친 뒤 desktop 실행이 없으면 턴을 한 번 막고 이유를 준다 | `decision: block`, 다음 편집 전까지 한 번 | + +- N5가 "desktop 실행"으로 치는 것: `ssh …`로 pnpm·`ci:gate`·`verify.sh`·vitest·playwright·`node scripts/…`를 돌린 명령, 또는 `scripts/verify.sh`를 `docs`·`hooks` 밖 단계로(`--on here` 없이) 돌린 명령. +- N5가 세지 않는 파일(노트북에서 확인되는 것): `.claude/`, `scripts/hooks/`, `scripts/tests/`, `scripts/check-work-docs.py`, `docs/ledger/`, `CLAUDE.md`. 이것들은 `scripts/verify.sh docs`·`hooks`가 노트북에서 본다. +- N5가 기억하는 것은 `.claude/hook-state/.json`이다(git이 무시한다). +- 권한 쪽 차단: `.claude/settings.json`의 `permissions.deny`가 실제 `.env`·`.env.local`·`.env.*.local`·`.env.` 읽기·쓰기를 막는다. `.env.example`은 막지 않는다. + +## 3. 시험 + +```bash +scripts/verify.sh hooks +``` + +- `python3 -m unittest discover -s scripts/tests`와 같다. 노트북에서 돈다. +- 고장 낸 입력(배럴 밖 import, kernel 밖 adapter 간 import, 늘어난 `.only`, 깨진 링크)에서 알림이 나오고, 맞는 입력에서 조용한지 본다. N3는 실제 `.dependency-cruiser.json`과 `src/` 전체에서 알림이 0인지도 본다(거짓 양성 시험). +- 훅을 고치면 조건을 끈 사본에서도 시험이 실패하는지 본다(변이 시험). 조건 하나를 끄는 것마다 시험 하나 이상이 실패해야 한다. +- 이 시험은 아직 CI workflow가 부르지 않는다. 훅·검사기를 고친 PR은 보고에 `scripts/verify.sh hooks` 결과를 적는다. + +## 4. 끄기 + +훅이 시끄럽거나 틀리면 `.claude/settings.json`에서 그 항목을 지우고, 이유를 커밋 본문에 쓴다. 개인적으로만 끄려면 `.claude/settings.local.json`(git이 무시한다)에 `"disableAllHooks": true`를 둔다. diff --git a/scripts/hooks/hooks.py b/scripts/hooks/hooks.py new file mode 100755 index 00000000..461c5676 --- /dev/null +++ b/scripts/hooks/hooks.py @@ -0,0 +1,374 @@ +#!/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 …` 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:])) diff --git a/scripts/tests/test_hooks.py b/scripts/tests/test_hooks.py new file mode 100644 index 00000000..cc838f41 --- /dev/null +++ b/scripts/tests/test_hooks.py @@ -0,0 +1,306 @@ +"""scripts/hooks/hooks.py의 시험. 고장 낸 입력에서 알림이 나오고, 맞는 입력에서 조용한지 본다. + + python3 -m unittest discover -s scripts/tests +""" + +from __future__ import annotations + +import importlib.util +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +SCRIPTS = Path(__file__).resolve().parent.parent +REPO = SCRIPTS.parent +_spec = importlib.util.spec_from_file_location("hooks", SCRIPTS / "hooks/hooks.py") +hooks = importlib.util.module_from_spec(_spec) +sys.modules["hooks"] = hooks +_spec.loader.exec_module(hooks) + +GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath", + "GIT_CONFIG_VALUE_0": "/dev/null"} +FILES = { + "src/adapters/http/index.ts": "export * from './client.ts';\n", + "src/adapters/http/client.ts": "export const client = 1;\n", + "src/adapters/auth/index.ts": "export const auth = 1;\n", + "src/adapters/auth/session.ts": "export const session = 1;\n", + "src/adapters/platform/locks.ts": "export const locks = 1;\n", + "src/bootstrap/compose.ts": "export {};\n", + "src/presentation/pages/home-page.tsx": "export {};\n", + "src/domain/order.ts": "export {};\n", +} + + +class Repository: + """A throwaway git checkout with the real import rules and a few adapter groups.""" + + def __init__(self) -> None: + self._directory = tempfile.TemporaryDirectory() + self.root = Path(self._directory.name).resolve() + shutil.copy(REPO / hooks.RULES, self.root / hooks.RULES) + for path, text in FILES.items(): + self.write(path, text) + self.git("init", "-q") + self.git("add", "-A") + self.git("commit", "-q", "-m", "base") + + def git(self, *args: str) -> None: + subprocess.run(["git", *args], cwd=self.root, check=True, capture_output=True, env={**os.environ, **GIT_ENV}) + + def write(self, path: str, text: str) -> Path: + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + return target + + def payload(self, path: str, tool: str = "Edit", **extra) -> dict: + return {"session_id": "s1", "cwd": str(self.root), "tool_name": tool, + "tool_input": {"file_path": str(self.root / path)}, **extra} + + def close(self) -> None: + self._directory.cleanup() + + +def run_event(event: str, payload: dict) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, {}, clear=False), \ + mock.patch.object(sys, "stdin", io.StringIO(json.dumps(payload))), redirect_stdout(out), redirect_stderr(err): + os.environ.pop("CLAUDE_PROJECT_DIR", None) + code = hooks.main([event]) + return code, out.getvalue(), err.getvalue() + + +def added_context(stdout: str) -> str: + return json.loads(stdout)["hookSpecificOutput"]["additionalContext"] if stdout else "" + + +class RepositoryTestCase(unittest.TestCase): + def setUp(self) -> None: + self.repo = Repository() + self.addCleanup(self.repo.close) + + def edit(self, path: str, text: str) -> str: + self.repo.write(path, text) + code, out, _ = run_event("post-edit", self.repo.payload(path)) + self.assertEqual(code, 0) + return added_context(out) + + +class BoundaryNudgeTest(RepositoryTestCase): + def test_a_deep_import_past_the_barrel_is_item_1(self) -> None: + text = self.edit("src/bootstrap/compose.ts", 'import { client } from "../adapters/http/client.ts";\n') + self.assertIn("경계 알림(N3) src/bootstrap/compose.ts", text) + self.assertIn("꼭 지킬 것 1 의심: `adapter-groups-are-reached-through-their-barrel`", text) + self.assertIn("src/adapters/http/client.ts", text) + + def test_the_barrel_is_quiet(self) -> None: + self.assertEqual(self.edit("src/bootstrap/compose.ts", 'import { client } from "../adapters/http/index.ts";\n'), "") + + def test_another_adapter_is_item_2_and_the_kernel_is_allowed(self) -> None: + text = self.edit("src/adapters/http/client.ts", textwrap.dedent("""\ + import { session } from "../auth/session.ts"; + import { locks } from "../platform/locks.ts"; + """)) + self.assertIn("꼭 지킬 것 2 의심: `adapters-do-not-know-other-concrete-adapters`", text) + self.assertNotIn("platform/locks", text) + + def test_a_package_import_is_checked_by_its_name(self) -> None: + text = self.edit("src/domain/order.ts", 'import { useState } from "react";\n') + self.assertIn("꼭 지킬 것 3 의심: `domain-is-framework-neutral` — `react`", text) + + def test_type_only_reexports_and_dynamic_imports_count(self) -> None: + for source in ('export type { Client } from "../../adapters/http/client.ts";\n', + 'const page = () => import("../../adapters/http/client.ts");\n', + 'import type {\n Client,\n} from "../../adapters/http/client";\n'): + with self.subTest(source=source): + self.assertIn("presentation-does-not-know-adapters", + self.edit("src/presentation/pages/home-page.tsx", source)) + + def test_findings_are_capped_and_keep_the_gate_line(self) -> None: + text = self.edit("src/presentation/pages/home-page.tsx", + 'import { client } from "../../adapters/http/client.ts";\nimport z from "zod";\n') + lines = text.splitlines() + self.assertLessEqual(len(lines), hooks.MAX_LINES) + self.assertRegex(lines[-2], r"^- 외 \d+개$") + self.assertIn("FE-GATE-010", lines[-1]) + + def test_files_outside_src_and_declarations_are_not_checked(self) -> None: + self.assertEqual(self.edit("tests/unit/x.test.ts", 'import { c } from "../../src/adapters/http/client.ts";\n'), "") + self.assertEqual(self.edit("src/bootstrap/env.d.ts", 'import { c } from "../adapters/http/client.ts";\n'), "") + + def test_the_real_rules_find_nothing_in_the_real_sources(self) -> None: + # A nudge the gate would not raise is noise. The repository passes check:architecture, so every + # source file here must be quiet; a new false positive fails this test before it reaches a session. + noisy = [] + for path in sorted((REPO / "src").rglob("*")): + if path.suffix in (".ts", ".tsx") and path.is_file(): + relative = path.relative_to(REPO).as_posix() + if hooks.boundary_findings(REPO, relative, path.read_text(encoding="utf-8")): + noisy.append(relative) + self.assertEqual(noisy, []) + + +class StandardNudgeTest(RepositoryTestCase): + TEST = "tests/unit/orders.test.ts" + + def setUp(self) -> None: + super().setUp() + self.repo.write(self.TEST, 'it.skip("a", () => {});\nit("b", () => {});\n') + self.repo.git("add", "-A") + self.repo.git("commit", "-q", "-m", "test") + + def test_skips_and_only_added_since_the_last_commit_are_reported(self) -> None: + text = self.edit(self.TEST, 'it.skip("a", () => {});\nit.skip("b", () => {});\ndescribe.only("c", () => {});\n') + self.assertIn("게이트 기준 알림(N6) tests/unit/orders.test.ts", text) + self.assertIn("`.only` 0→1", text) + self.assertIn("`.skip` 1→2", text) + self.assertIn("꼭 지킬 것 4", text) + + def test_an_unchanged_or_smaller_count_is_quiet(self) -> None: + self.assertEqual(self.edit(self.TEST, 'it.skip("a", () => { expect(1).toBe(1); });\n'), "") + self.assertEqual(self.edit(self.TEST, 'it("a", () => {});\n'), "") + + def test_a_new_test_file_counts_from_zero_and_playwright_fixme_counts(self) -> None: + text = self.edit("tests/e2e/new.spec.ts", 'test.fixme("x", async () => {});\n') + self.assertIn("`.fixme` 0→1", text) + + def test_a_gate_standard_file_edit_is_reported(self) -> None: + for path in ("config/performance/budgets.json", "config/ci/ungated-tests.json", + "config/scale/feature-shape-ceilings.json", "vitest.config.ts", + "tests/unit/__snapshots__/x.test.ts.snap"): + with self.subTest(path=path): + self.assertIn("게이트의 기준 파일", self.edit(path, "{}\n")) + + def test_source_text_that_looks_like_a_skip_is_not_counted(self) -> None: + self.assertEqual(self.edit("src/domain/order.ts", 'export const note = "use it.only when";\n'), "") + + +class DocumentNudgeTest(RepositoryTestCase): + def checker(self, code: int, stderr_lines: list[str]) -> None: + body = "import sys\n" + "".join(f"print({line!r}, file=sys.stderr)\n" for line in stderr_lines) + self.repo.write(hooks.DOC_CHECK[0], body + f"sys.exit({code})\n") + + def test_failures_naming_the_edited_document_come_back_first(self) -> None: + self.checker(1, ["", "FAILED: 2 problem(s)", " docs/work/improve.md:3: history ID '1103/11-07'", + " docs/work/README.md:9: broken relative link 'x.md'"]) + text = self.edit("docs/work/improve.md", "# x\n") + self.assertIn("문서 검사 알림(N2) docs/work/improve.md", text) + self.assertIn("1103/11-07", text) + self.assertNotIn("broken relative link", text) + + def test_failures_elsewhere_are_shown_when_none_names_the_document(self) -> None: + self.checker(1, [" AGENTS.md: 41 lines, limit 40"]) + self.assertIn("AGENTS.md: 41 lines", self.edit("docs/manual/README.md", "# x\n")) + + def test_a_passing_check_adds_nothing(self) -> None: + self.checker(0, []) + self.assertEqual(self.edit("docs/work/improve.md", "# x\n"), "") + + +class TurnEndNudgeTest(RepositoryTestCase): + def stop(self, **extra) -> dict | None: + _, out, _ = run_event("stop", {"session_id": "s1", "cwd": str(self.repo.root), **extra}) + return json.loads(out) if out else None + + def bash(self, command: str) -> None: + run_event("post-bash", {"session_id": "s1", "cwd": str(self.repo.root), "tool_name": "Bash", + "tool_input": {"command": command}}) + + def test_an_edit_blocks_the_turn_end_once_with_the_reason(self) -> None: + self.edit("src/domain/order.ts", "export const a = 1;\n") + first = self.stop() + self.assertEqual(first["decision"], "block") + self.assertIn("src/domain/order.ts", first["reason"]) + self.assertIn("scripts/verify.sh", first["reason"]) + self.assertIsNone(self.stop()) + + def test_a_desktop_run_clears_the_pending_edits(self) -> None: + for command in ("ssh desktop 'cd ~/workspace/x && corepack pnpm -s lint'", + "scripts/verify.sh merge --log fe-x", + "./scripts/verify.sh gate FE-GATE-005", + "cd /w && scripts/verify.sh script verify:documentation 2>&1 | tail"): + with self.subTest(command=command): + self.edit("src/domain/order.ts", "export const a = 2;\n") + self.bash(command) + self.assertIsNone(self.stop()) + + def test_laptop_commands_and_other_hosts_do_not_count(self) -> None: + for command in ("corepack pnpm lint", "ssh build-box 'corepack pnpm lint'", "scripts/verify.sh docs", + "scripts/verify.sh hooks", "scripts/verify.sh gate FE-GATE-005 --on here", + "ssh desktop uptime"): + with self.subTest(command=command): + self.edit("src/domain/order.ts", "export const a = 3;\n") + self.bash(command) + self.assertIsNotNone(self.stop()) + + def test_files_the_laptop_checks_do_not_need_the_desktop(self) -> None: + for path in (".claude/rules/x.md", "scripts/hooks/hooks.py", "scripts/tests/test_x.py", "CLAUDE.md", + "docs/ledger/estimates.jsonl", "scripts/check-work-docs.py"): + self.repo.write(path, "x\n") + run_event("post-edit", self.repo.payload(path)) + self.assertIsNone(self.stop()) + + def test_a_new_edit_after_the_reminder_reminds_again(self) -> None: + self.edit("src/domain/order.ts", "export const a = 4;\n") + self.stop() + self.edit("docs/work/README.md", "# x\n") + self.assertIsNotNone(self.stop()) + + def test_an_active_stop_hook_never_blocks_again(self) -> None: + self.edit("src/domain/order.ts", "export const a = 5;\n") + self.assertIsNone(self.stop(stop_hook_active=True)) + + +class SettingsWiringTest(unittest.TestCase): + SETTINGS = REPO / ".claude/settings.json" + + def setUp(self) -> None: + self.settings = json.loads(self.SETTINGS.read_text(encoding="utf-8")) + + def commands(self, event: str, matcher: str | None) -> list[str]: + return [hook["command"] for entry in self.settings["hooks"].get(event, []) + if entry.get("matcher") == matcher for hook in entry["hooks"]] + + def test_every_event_calls_its_hook(self) -> None: + self.assertEqual(self.commands("PostToolUse", "Edit|Write|MultiEdit"), + ['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py post-edit']) + self.assertEqual(self.commands("PostToolUse", "Bash"), + ['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py post-bash']) + self.assertEqual(self.commands("Stop", None), ['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py stop']) + self.assertNotIn("PreToolUse", self.settings["hooks"]) + + def test_real_env_files_are_denied_and_the_example_is_not(self) -> None: + deny = self.settings["permissions"]["deny"] + for tool in ("Read", "Edit"): + self.assertIn(f"{tool}(**/.env)", deny) + self.assertIn(f"{tool}(**/.env.local)", deny) + self.assertFalse([rule for rule in deny if "example" in rule or rule in ("Read(**/.env.*)", "Edit(**/.env.*)")]) + + def test_the_harness_plugin_is_enabled_from_its_marketplace(self) -> None: + self.assertEqual(self.settings["enabledPlugins"], {"harness@claude-harness": True}) + source = self.settings["extraKnownMarketplaces"]["claude-harness"]["source"] + self.assertEqual(source, {"source": "git", + "url": "https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness.git"}) + + def test_the_hook_script_runs_from_the_command_line(self) -> None: + for event in hooks.EVENTS: + result = subprocess.run([sys.executable, str(SCRIPTS / "hooks/hooks.py"), event], input="{}", + capture_output=True, text=True, timeout=10, cwd=tempfile.gettempdir()) + self.assertEqual(result.returncode, 0, event + result.stderr) + result = subprocess.run([sys.executable, str(SCRIPTS / "hooks/hooks.py"), "nope"], input="{}", + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 1) + + +if __name__ == "__main__": + unittest.main()