Files
clean-architecture-backend-…/scripts/hooks/hooks.py
DongHyeonka a86e00d6e4
pr / done (pull_request) Successful in 3m35s
fix(hooks): N5는 실행되는 낱말만 세고 N6는 merge-base와 비교한다
N5는 명령 안 어디에 있든 `verify.sh <단계>`를 실행으로 셌다. 그래서
`echo scripts/verify.sh pr`, `bash -n scripts/verify.sh pr`도 desktop
실행이 됐다. here-document는 명령 안 아무 낱말이나 bash·sh·zsh면
스크립트로 읽었고(`grep -c bash <<EOF`), `<<\EOF`·`<<'END NOTE'`
구분자는 못 알아 본문을 명령으로 읽었다. `ssh … gradlew`는 옛 검사
그대로 명령 글 전체에서 낱말을 찾아, 커밋 메시지 본문이나 주석의
`ssh desktop ./gradlew`도 셌다. registry에 없는 leaf 대상, 미추적
파일로 보내기를 거절한 실행(rc 5)처럼 Gradle 전에 멈춘 verify.sh도
셌다.

N6는 HEAD와 비교해서, 이 브랜치에서 새로 쓰고 커밋한 기록을 다듬을
때도 「본문을 되돌린다」를 알렸다. 아직 main에 들어가지 않은 글이라
그 알림은 정당한 수정을 되돌리게 만든다.

고친 방법:
- N5: 단순 명령마다 실제로 실행되는 낱말 하나만 본다. 대입과 감싸개
  (timeout·flock·env·nohup 등, 값 받는 옵션과 앞 인자 수를 표로 둠)
  뒤의 낱말, 셸에 준 스크립트 파일이다. 셸은 옵션을 읽어 -c 스크립트,
  stdin 스크립트(-s 또는 인자 없음), 스크립트 파일, -n(실행 안 함)을
  가른다. ssh 원격 명령은 ssh가 보내는 대로 리다이렉션을 뺀 낱말을
  이어 desktop에서 다시 읽는다. gradlew도 같은 길로 desktop 안에서
  돌 때만 센다. leaf 대상은 registry gradle_path와 대조하고, 출력에
  verify.sh의 거절 문구가 있으면 그 명령의 verify.sh는 세지 않는다.
  스크립트 안의 스크립트는 MAX_NESTING단까지만 읽는다(깊은 ssh 중첩이
  RecursionError로 훅을 죽이지 않게).
- here-document 구분자 정규식이 `\WORD`와 따옴표 안 공백을 받는다.
- N6: 기준 커밋을 verify.sh와 같은
  `git merge-base HEAD "${VERIFY_BASE_REF:-origin/main}"`로 하고, 그
  ref가 없으면 HEAD로 돌아간다. 알림 문구는 기준 커밋 이름을 적는다.

버린 대안:
- README의 N5 문구를 verify.sh 경로로 좁히고 옛 gradlew 검사를 둔다
  — 같은 오판이 gradlew 쪽에 남는다.
- 실패한 Bash는 PostToolUse가 안 돈다고 보고 rc 5를 두지 않는다 —
  `| tail`·`; echo rc=$?`로 끝나면 rc가 0이라 돈다.

위험·한계: 여전히 넛지다. 원격 준비 실패(rc 4)는 출력으로 가리지
못해 센다. flock의 `-c` 꼴, 감싸개 표에 없는 감싸개는 실행으로 보지
않아 알림이 한 번 더 나올 수 있다. 「실행 중」 계획서 체크 상자 수정은
기록 규칙상 본문 수정이라 N6가 계속 알린다(이 브랜치에서 새로 쓴
계획서는 이제 조용하다).

검증(노트북, Python·문서만):
- python3 -m unittest discover -s scripts/tests -p test_hooks.py:
  61개 rc=0(1 skip = 실제 포매터 jar).
- RED: 9c0a7cb3d의 hooks.py에 새 상수 셋만 얹고 새 시험을 돌리면
  rc=1, failures=20.
- 변이: 이 커밋이 더하거나 건드린 조건 41개를 하나씩 끈 사본에서
  모두 rc=1(생존 0).
- python3 scripts/check-docs.py, scripts/check-work-docs.py rc=0.
2026-11-22 02:09:28 +09:00

853 lines
40 KiB
Python

#!/usr/bin/env python3
"""Claude Code repo hooks: nudge right after an edit, block only what cannot be undone.
Called by `.claude/settings.json`, one event per invocation, with the hook input JSON on stdin:
python3 scripts/hooks/hooks.py pre-edit # PreToolUse Edit|Write|MultiEdit H13
python3 scripts/hooks/hooks.py post-edit # PostToolUse Edit|Write|MultiEdit format, N1, N2, N6
python3 scripts/hooks/hooks.py post-bash # PostToolUse Bash records desktop Gradle 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; only H13 exits 2. No hook runs Gradle
or Docker: the owner's laptop never does (docs/work/operate.md 4.1). The formatter is one JVM on
one file, from the jar Gradle already cached. Standard library only. The tests are
scripts/tests/test_hooks.py.
"""
from __future__ import annotations
import ast
import difflib
import hashlib
import json
import os
import re
import shlex
import subprocess
import sys
from pathlib import Path
REGISTRY = "gradle/modules.json"
CATALOG = "gradle/libs.versions.toml"
MIGRATION_MANIFEST = "src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256"
STATE_DIR = ".claude/hook-state"
EDIT_TOOLS = ("Edit", "Write", "MultiEdit")
MAX_LINES = 5
# --- formatter: the step Spotless runs (QualityConventionsPlugin), on one file -----------------------
GJF_GROUP = "com.google.googlejavaformat/google-java-format"
# The Spotless step keeps long strings as written; the CLI reflows them unless told not to.
GJF_FLAGS = ("--skip-reflowing-long-strings", "--replace")
GJF_EXPORTS = tuple(f"--add-exports=jdk.compiler/com.sun.tools.javac.{part}=ALL-UNNAMED"
for part in ("api", "code", "file", "parser", "tree", "util"))
GJF_TIMEOUT = 25
# Spotless is not applied to build-logic (it is its own build), so the hook leaves it alone too.
FORMAT_EXCLUDED = ("build-logic/",)
SKIPPED = "포맷을 건너뛰었다"
# --- N1: the layer rules the gates hold, checked on the imports of one edited main source --------------
# Mirrors DomainPurityArchitectureTest (DOMAIN_IS_PURE, DOMAIN_HAS_NO_LOGGER).
# dev.cakit.: the owner's libraries (messaging-library, grpc-library) are reached only through adapters;
# a layer row may not list one in allowed_libraries (registry library_groups, build-logic ArchitecturePlugin).
DOMAIN_FORBIDDEN = ("org.springframework.", "jakarta.persistence.", "javax.persistence.", "jakarta.servlet.",
"org.hibernate.", "lombok.", "org.slf4j.", "java.util.logging.", "ch.qos.logback.",
"org.apache.logging.log4j.", "dev.cakit.")
# Mirrors VerifyApplicationCoreDependencyPurityTask and the application-core AGENTS.md forbidden list.
APPLICATION_FORBIDDEN = ("org.springframework.", "org.slf4j.", "ch.qos.logback.", "org.apache.logging.log4j.",
"io.micrometer.", "java.util.logging.", "jakarta.persistence.", "javax.persistence.",
"lombok.", "dev.cakit.")
SHARED_FORBIDDEN = ("org.springframework.", "jakarta.", "javax.persistence.", "org.hibernate.", "lombok.",
"dev.cakit.")
# HARD-STOP 2: an inbound adapter reaching the store.
INBOUND_FORBIDDEN = ("org.springframework.data.repository.", "org.springframework.data.jpa.",
"org.springframework.data.mongodb.repository.", "jakarta.persistence.", "javax.persistence.")
IMPORT = re.compile(r"^\s*import\s+(static\s+)?([\w.]+)(\.\*)?\s*;", re.M)
PROJECT_PREFIX = "dev.caskeleton."
MAIN_JAVA = re.compile(r"^(?P<leaf>src/.+?)/src/main/java/(?P<rest>.+\.java)$")
# --- N2: the document checks a living document edit can break -------------------------------------------
DOC_CHECKS = (("scripts/check-work-docs.py",), ("scripts/check-docs.py",))
DOC_TIMEOUT = 20
# --- N6: a record keeps the body it was written with; the vision is the owner's ------------------------
# Which folders hold records, which of them are decisions and where a head block ends are read from the
# document checker's source (literals only, the script is not run), not copied here.
DOC_CHECKER = "scripts/check-docs.py"
DOC_CHECKER_NAMES = ("RECORD_KINDS", "DECISION_PREFIXES", "HEAD_START", "HEAD_END", "HEAD_SEARCH_LINES")
VISION = "docs/vision.md"
GIT_TIMEOUT = 10
RECORD_CHANGES_SHOWN = 3
# The body is compared with where this branch left the base, as scripts/verify.sh finds it
# (`git merge-base HEAD "${VERIFY_BASE_REF:-origin/main}"`); without that ref, with HEAD.
BASE_REF_VARIABLE = "VERIFY_BASE_REF"
BASE_REF_DEFAULT = "origin/main"
# --- N5: a Bash command that ran Gradle on the desktop clears the pending Java edits --------------------
DESKTOP_HOST = re.compile(r"desktop")
# The scripts/verify.sh stages that run Gradle or Docker (run_here). Their --on default is
# ${VERIFY_HOST:-desktop}; docs runs here and never on the desktop (scripts/verify.sh main).
VERIFY_SCRIPT = "verify.sh"
VERIFY_HEAVY_STAGES = ("leaf", "pr", "main", "nightly", "release", "app", "round")
# scripts/verify.sh main: any other word after the stage (and the leaf target) stops it at usage, before Gradle.
VERIFY_VALUE_OPTIONS = ("--on", "--log")
VERIFY_FLAGS = ("--no-cache", "--include-untracked")
VERIFY_HOST_ASSIGNMENT = "VERIFY_HOST="
# scripts/verify.sh run_remote says this and exits 5 before it sends anything to the desktop.
VERIFY_REFUSED = "verify: 미추적 파일이 있어 보내지 않는다"
GRADLE_WRAPPER = "gradlew"
# How deep a script inside a script (ssh remote command, `-c`, here-document) is still read.
MAX_NESTING = 8
# ssh options that take a value, so the host is the first word after them (ssh(1) SYNOPSIS).
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 here-document fed to one of these, or `<shell> -c '<script>'`, is a script; any other body is text.
SHELLS = ("bash", "sh", "zsh")
SHELL_VALUE_OPTIONS = ("-o", "+o", "-O", "+O", "--rcfile", "--init-file")
# Words that run the rest of a command: (their options that take a value, how many arguments come before the
# command they run) — `timeout 600 <command>`, `flock <lock file> <command>`.
WRAPPERS = {"command": ((), 0), "env": (("-u", "--unset", "-C", "--chdir"), 0), "exec": (("-a",), 0),
"flock": (("-w", "--wait", "--timeout", "-E", "--conflict-exit-code"), 1),
"nice": (("-n", "--adjustment"), 0), "nohup": ((), 0),
"sudo": (("-u", "-g", "-h", "-p", "-C", "-D", "-R", "-T", "-U"), 0), "time": (("-f", "-o"), 0),
"timeout": (("-s", "--signal", "-k", "--kill-after"), 1)}
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR_CHARS = "();|&\n"
# The delimiter is a word, `\word`, or quoted (quotes may hold spaces); `<<-` strips leading tabs.
HEREDOC = re.compile(r"<<(-?)[ \t]*(?:'([^'\n]*)'|\"([^\"\n]*)\"|\\?([A-Za-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:
return json.loads(state_file(root, session_id).read_text(encoding="utf-8"))
except (OSError, ValueError):
return {"java_edits": [], "reminded": False}
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")
# ----------------------------------------------------------------------------------------------------
# H13 — an applied migration is never edited
def applied_migrations(root: Path) -> set[str]:
try:
text = (root / MIGRATION_MANIFEST).read_text(encoding="utf-8")
except OSError:
return set()
return {line.split()[1] for line in text.splitlines() if line.strip() and not line.startswith("#")
and len(line.split()) == 2}
def migration_key(path: str) -> str | None:
"""`src/<leaf>/src/main/resources/db/migration/jpa/core/V1__x.sql` → `jpa/core/V1__x.sql`."""
marker = "/src/main/resources/db/migration/"
if marker not in path or not path.endswith(".sql"):
return None
return path.split(marker, 1)[1]
def h13_message(root: Path, path: str | None) -> str | None:
key = migration_key(path) if path else None
if key is None or key not in applied_migrations(root):
return None
return (f"[H13 적용된 migration 편집 금지] {path}\n"
"이 파일은 이미 적용된 migration이다(" + MIGRATION_MANIFEST + "에 있다). Flyway가 기동마다 checksum을"
" 대조하므로 고치면 운영 DB가 뜨지 않는다.\n"
"대신 새 버전 파일(V<다음 번호>__<설명>.sql)을 더하고 sha256 목록에 한 줄을 더한다. 어떤 DB에도 적용된 적 없는"
" 파일이라 고쳐야 하면 소유자에게 묻는다.")
# ----------------------------------------------------------------------------------------------------
# format — google-java-format on the one edited file
def catalog_version(root: Path, key: str) -> str | None:
try:
text = (root / CATALOG).read_text(encoding="utf-8")
except OSError:
return None
match = re.search(rf'^{re.escape(key)}\s*=\s*"([^"]+)"', text, re.M)
return match.group(1) if match else None
def gradle_cache() -> Path:
home = os.environ.get("GRADLE_USER_HOME")
return (Path(home) if home else Path.home() / ".gradle") / "caches/modules-2/files-2.1"
def version_key(version: str) -> tuple:
return tuple(int(part) if part.isdigit() else -1 for part in re.split(r"[.-]", version))
def newest_jar(cache: Path, group_artifact: str, suffix: str = "") -> Path | None:
folder = cache / group_artifact
artifact = group_artifact.rsplit("/", 1)[1]
versions = sorted((v.name for v in folder.glob("*") if v.name.endswith(suffix)), key=version_key) \
if folder.is_dir() else []
for version in reversed(versions):
jars = sorted(folder.glob(f"{version}/*/{artifact}-{version}.jar"))
if jars:
return jars[0]
return None
def formatter_classpath(root: Path, cache: Path) -> tuple[list[Path] | None, str]:
version = catalog_version(root, "googleJavaFormat")
if version is None:
return None, f"{CATALOG}에 googleJavaFormat 버전이 없다"
jars = sorted(cache.glob(f"{GJF_GROUP}/{version}/*/google-java-format-{version}.jar"))
if not jars:
return None, f"google-java-format {version} jar가 Gradle 캐시({cache})에 없다"
guava = newest_jar(cache, "com.google.guava/guava", "-jre")
access = newest_jar(cache, "com.google.guava/failureaccess")
if guava is None or access is None:
return None, "guava jar가 Gradle 캐시에 없다"
return [jars[0], guava, access], version
def wants_format(path: str | None) -> bool:
return bool(path) and path.startswith("src/") and path.endswith(".java") \
and not path.startswith(FORMAT_EXCLUDED) and "/build/" not in path
def format_java(root: Path, path: str, cache: Path | None = None) -> list[str]:
"""Format lines for the model. A skip line starts with SKIPPED so the caller can say it once."""
classpath, detail = formatter_classpath(root, cache or gradle_cache())
if classpath is None:
return [f"{SKIPPED}: {detail}. 받거나 설치하지 않는다. desktop `./gradlew spotlessApply`가 맞춘다."]
target = root / path
before = hashlib.sha256(target.read_bytes()).hexdigest()
command = ["java", *GJF_EXPORTS, "-cp", os.pathsep.join(str(jar) for jar in classpath),
"com.google.googlejavaformat.java.Main", *GJF_FLAGS, str(target)]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=GJF_TIMEOUT)
except FileNotFoundError:
return [f"{SKIPPED}: `java`가 PATH에 없다. desktop `./gradlew spotlessApply`가 맞춘다."]
except subprocess.TimeoutExpired:
return [f"{SKIPPED}: google-java-format이 {GJF_TIMEOUT}초 안에 끝나지 않았다."]
if result.returncode != 0:
errors = [line for line in result.stderr.splitlines() if line.strip()][:3]
return [f"google-java-format {detail}가 {path}를 읽지 못했다(문법 오류일 수 있다):", *errors]
if hashlib.sha256(target.read_bytes()).hexdigest() != before:
return [f"google-java-format {detail}가 {path}를 Spotless와 같은 모양으로 다시 썼다. 다음 Edit 전에 다시 읽는다."]
return []
# ----------------------------------------------------------------------------------------------------
# N1 — imports of one edited main source against the registry and the layer purity rules
def load_registry(root: Path) -> list[dict]:
return json.loads((root / REGISTRY).read_text(encoding="utf-8")).get("modules", [])
def owning_leaf(modules: list[dict], path: str) -> dict | None:
owners = [m for m in modules if path.startswith(m["source_path"].rstrip("/") + "/")]
return max(owners, key=lambda m: len(m["source_path"])) if owners else None
def package_index(root: Path, modules: list[dict]) -> dict[str, set[str]]:
"""Java package → the leaves whose main source set has a class in it."""
index: dict[str, set[str]] = {}
for module in modules:
base = root / module["source_path"] / "src/main/java"
for directory, _, names in os.walk(base):
if any(name.endswith(".java") for name in names):
package = Path(directory).relative_to(base).as_posix().replace("/", ".")
index.setdefault(package, set()).add(module["id"])
return index
def closure(modules: list[dict], start: str) -> set[str]:
edges = {m["id"]: m.get("allowed_dependencies", []) for m in modules}
seen, pending = {start}, [start]
while pending:
for target in edges.get(pending.pop(), []):
if target not in seen:
seen.add(target)
pending.append(target)
return seen
def owner_of(index: dict[str, set[str]], name: str) -> tuple[str, set[str]] | None:
"""The longest package prefix of an imported name that some leaf owns (handles nested and static)."""
parts = name.split(".")
for end in range(len(parts), 1, -1):
package = ".".join(parts[:end])
if package in index:
return package, index[package]
return None
def forbidden_prefixes(leaf: str) -> tuple[str, tuple[str, ...]] | None:
if leaf == "domain-core":
return "HARD-STOP 1", DOMAIN_FORBIDDEN
if leaf.startswith("application-"):
return "HARD-STOP 1·4", APPLICATION_FORBIDDEN
if leaf == "shared-contract":
return "shared-contract 금지", SHARED_FORBIDDEN
if leaf.startswith("adapter-inbound-"):
return "HARD-STOP 2", INBOUND_FORBIDDEN
return None
def stop_number(leaf: str, target: str) -> str:
if (leaf == "domain-core" or leaf.startswith("application-")) and target.startswith("adapter-inbound-"):
return "HARD-STOP 3"
if leaf.startswith("adapter-inbound-") and target.startswith("adapter-outbound-persistence"):
return "HARD-STOP 2"
return "HARD-STOP 5"
def boundary_findings(root: Path, path: str, source: str) -> list[str]:
if not MAIN_JAVA.match(path):
return []
modules = load_registry(root)
leaf = owning_leaf(modules, path)
if leaf is None:
return []
allowed = closure(modules, leaf["id"])
index = package_index(root, modules)
rule = forbidden_prefixes(leaf["id"])
findings = []
for static, name, wildcard in IMPORT.findall(source):
imported = name + (".*" if wildcard else "")
if rule and any(imported.startswith(prefix) for prefix in rule[1]):
findings.append(f"- {rule[0]} 의심: `{leaf['id']}`가 `{imported}`를 import한다.")
continue
if not name.startswith(PROJECT_PREFIX):
continue
owner = owner_of(index, name)
if owner is None or owner[1] & allowed:
continue
target = sorted(owner[1])[0]
findings.append(f"- {stop_number(leaf['id'], target)} 의심: `{imported}`는 leaf `{target}`의 것인데"
f" `{leaf['id']}`의 registry allowed_dependencies(전이 포함)에 없다.")
if findings:
findings.insert(0, f"레이어 의존 알림(N1) {path}")
findings.append("정본은 게이트다: desktop `./gradlew architectureCheck`. 의도한 edge면 registry가 먼저다.")
return findings
# ----------------------------------------------------------------------------------------------------
# N2 — the document checks, failures only
def wants_doc_check(path: str | None) -> bool:
return bool(path) and path.endswith(".md") and "/build/" not in path and not path.startswith(".claude/hook-state/")
def doc_findings(root: Path, path: str) -> list[str]:
failures: list[str] = []
for script in DOC_CHECKS:
try:
result = subprocess.run([sys.executable, *script], cwd=root, capture_output=True, text=True,
timeout=DOC_TIMEOUT)
except subprocess.TimeoutExpired:
failures.append(f"- {script[0]}: {DOC_TIMEOUT}초 안에 끝나지 않았다")
continue
if result.returncode == 0:
continue
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]
failures += [f"- {line}" for line in (mine or lines)]
if failures:
failures.insert(0, f"문서 검사 알림(N2) {path} 편집 뒤 실패 줄:")
return failures
# ----------------------------------------------------------------------------------------------------
# N6 — a record's body and the owner's vision are not rewritten
def record_rules(root: Path) -> dict | None:
"""The record constants of scripts/check-docs.py, or None when it is missing or no longer has them all."""
try:
tree = ast.parse((root / DOC_CHECKER).read_text(encoding="utf-8"))
except (OSError, SyntaxError, ValueError):
return None
rules = {}
for node in tree.body:
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) \
and node.targets[0].id in DOC_CHECKER_NAMES:
try:
rules[node.targets[0].id] = ast.literal_eval(node.value)
except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
return None
return rules if len(rules) == len(DOC_CHECKER_NAMES) else None
def is_record(rules: dict, path: str) -> bool:
return any(path.startswith(prefix) for prefix, _ in rules["RECORD_KINDS"])
def git_output(root: Path, *arguments: str) -> str | None:
try:
result = subprocess.run(["git", *arguments], cwd=root, capture_output=True,
encoding="utf-8", errors="replace", timeout=GIT_TIMEOUT)
except (OSError, subprocess.TimeoutExpired):
return None
return result.stdout if result.returncode == 0 else None
def base_commit(root: Path) -> tuple[str, str]:
"""The commit a record's body is compared with and its name in the nudge.
A record written or reworded on this branch before it reaches the base is still being written, so the base
is where this branch left ${VERIFY_BASE_REF:-origin/main}; without that ref it is HEAD.
"""
ref = os.environ.get(BASE_REF_VARIABLE) or BASE_REF_DEFAULT
base = git_output(root, "merge-base", "HEAD", ref)
return (base.strip(), f"merge-base {ref}") if base else ("HEAD", "HEAD")
def record_body(rules: dict, text: str) -> tuple[list[str], int]:
"""The lines after the head block, without trailing blank lines, and how many lines come before them.
The head block is found as check-docs.py strip_head_block finds it: the first line opens it and its end
mark is within the first HEAD_SEARCH_LINES lines. Without one the whole text is the body.
"""
lines = text.split("\n")
head = lines[:rules["HEAD_SEARCH_LINES"]]
offset = head.index(rules["HEAD_END"]) + 1 if lines[0] == rules["HEAD_START"] and rules["HEAD_END"] in head else 0
body = lines[offset:]
while body and not body[-1].strip():
body = body[:-1]
return body, offset
def record_findings(root: Path, path: str) -> list[str]:
if path == VISION:
return [f"소유자 문서 알림(N6) {path}: 소유자만 쓴다(docs/vision.md:3-4). 되돌리고 제안만 한다."]
rules = record_rules(root)
if rules is None or not is_record(rules, path):
return []
base, base_name = base_commit(root)
old = git_output(root, "show", f"{base}:./{path}")
if old is None:
return [] # a record written on this branch: there is no earlier body to keep
old_body, _ = record_body(rules, old)
new_body, offset = record_body(rules, (root / path).read_text(encoding="utf-8"))
decision = path.startswith(tuple(rules["DECISION_PREFIXES"]))
if new_body == old_body or decision and new_body[:len(old_body)] == old_body:
return []
# A decision record may grow a supplement at its end; that part is not the change to name.
changes = [(tag, i1, i2, j1, j2) for tag, i1, i2, j1, j2
in difflib.SequenceMatcher(None, old_body, new_body, autojunk=False).get_opcodes()
if tag != "equal" and not (decision and tag == "insert" and i1 == len(old_body))]
rule = ("결정 기록 본문은 고치지 않는다. 바뀐 결정은 본문 끝에 보완 절로 덧붙이고 상태를 「채택(보완)」으로 한다"
if decision else "기록 본문은 쓴 때의 원문이다. 머리 블록 칸만 고친다")
lines = [f"기록 본문 알림(N6) {path}: 머리 블록 끝 뒤 본문이 기준 커밋({base_name})과 {len(changes)}곳 다르다. "
f"{rule}(docs/README.md 「문서 수명과 언어」). 본문을 되돌린다."]
for tag, i1, i2, j1, j2 in changes[:RECORD_CHANGES_SHOWN]:
line = next((index for index in range(j1, j2) if new_body[index].strip()), j1)
before = next((text for text in old_body[i1:i2] if text.strip()), "")
after = new_body[line] if line < j2 else ""
lines.append(f"- {offset + line + 1}행: 기준 「{before[:60]}」 → 지금 「{after[:60]}」")
if len(changes) > RECORD_CHANGES_SHOWN:
lines.append(f"- 바뀐 곳 {len(changes) - RECORD_CHANGES_SHOWN}곳 더")
return lines
# ----------------------------------------------------------------------------------------------------
# N5 — Java changed and the desktop has not compiled it since
def ran_desktop_gradle(command: str, on_desktop: bool = False, leaves: frozenset[str] | None = None,
refused: bool = False, depth: int = 0) -> bool:
"""Whether `command` runs Gradle on the desktop.
That is `gradlew` run inside `ssh <desktop host> …`, or a scripts/verify.sh Gradle stage its --on sends to
the desktop: from the laptop no --on (the default host) or a desktop host, and `--on here` only inside
`ssh <desktop host> …`. Only the word a simple command runs counts — after assignments and wrappers
(`timeout`, `flock` …) or as the script file given to a shell — so `echo scripts/verify.sh pr` runs nothing.
The ssh remote command (its words joined, as ssh sends them), a `<shell> -c` script, and a here-document or
`<<<` string read by a shell or by `ssh <desktop host>` are read the same way where they run; any other
here-document body (`cat > file <<EOF`, `git commit -F - <<EOF`) is text. `leaves` are the registry
gradle_paths a `leaf` target must be one of; `refused` says verify.sh sent nothing, so its stages do not count.
Scripts nested deeper than MAX_NESTING are not read.
"""
if depth > MAX_NESTING:
return False
script, bodies = split_heredocs(command)
words = shell_words(script)
heredocs = dict(zip([index for index, word in enumerate(words) if word == "<<"], bodies))
nested: list[tuple[str, bool]] = []
for start, end in simple_commands(words):
plain, strings = command_words(words, start, end)
at = command_word(words, plain)
if at is None:
continue
name = Path(words[plain[at]]).name
program: int | None = plain[at]
reader = None # where the here-documents and <<< strings this command reads run as a script
if name == "ssh":
host = ssh_host(words, plain, at)
if host is not None and DESKTOP_HOST.search(words[plain[host]]):
nested.append((" ".join(words[index] for index in plain[host + 1:]), True))
reader = True
elif name in SHELLS:
program, inline, reads_input = shell_input(words, plain, at)
if inline is not None:
nested.append((words[inline], on_desktop))
reader = on_desktop if reads_input else None
if reader is not None:
nested += [(heredocs[index], reader) for index in range(start, end) if heredocs.get(index) is not None]
nested += [(words[index], reader) for index in strings]
if program is not None and runs_gradle(words, start, program, end, on_desktop, leaves, refused):
return True
return any(ran_desktop_gradle(text, where, leaves, refused, depth + 1) for text, where in nested)
def split_heredocs(command: str) -> tuple[str, list[str | None]]:
"""The command as the shell reads its words, and the body of each `<<` in order.
Comments and backslash-newlines go; a here-document body (the lines after its `<<` line up to its delimiter
line) is taken out, so its text is not read as commands. A `<<` without a plain delimiter gets None.
"""
out: list[str] = []
bodies: list[str | None] = []
pending: list[tuple[int, bool, str]] = []
quote = None
index = 0
while index < len(command):
char = command[index]
if quote:
if char == quote:
quote = None
elif char == "\\" and quote == '"' and index + 1 < len(command):
out.append(char)
index += 1
char = command[index]
out.append(char)
index += 1
continue
if char in "'\"":
quote = char
elif char == "\\" and command.startswith("\\\n", index):
index += 2
continue
elif char == "\\" and index + 1 < len(command):
out.append(char)
index += 1
char = command[index]
elif char == "#" and (index == 0 or command[index - 1] in " \t" + OPERATOR_CHARS):
index = command.find("\n", index) if "\n" in command[index:] else len(command)
continue
elif command.startswith("<<", index) and not command.startswith("<<<", index):
match = HEREDOC.match(command, index)
bodies.append(None)
if match:
delimiter = next(group for group in match.group(2, 3, 4) if group is not None)
pending.append((len(bodies) - 1, match.group(1) == "-", delimiter))
out.append(match.group(0) if match else "<<")
index = match.end() if match else index + 2
continue
elif char == "\n" and pending:
out.append(char)
lines = command[index + 1:].split("\n")
taken = 0
for slot, strip_tabs, delimiter in pending:
body = []
while taken < len(lines) and (lines[taken].lstrip("\t") if strip_tabs else lines[taken]) != delimiter:
body.append(lines[taken])
taken += 1
taken += 1
bodies[slot] = "\n".join(body)
index += 1 + sum(len(line) + 1 for line in lines[:taken])
pending = []
continue
out.append(char)
index += 1
return "".join(out), bodies
def shell_words(script: str) -> list[str]:
"""Words and control operators (`&&`, `|`, `;`, `(`, newline …) of a script; quotes stay one word."""
lexer = shlex.shlex(script, posix=True, punctuation_chars="();<>|&\n")
lexer.whitespace = " \t\r"
lexer.commenters = ""
lexer.whitespace_split = True
try:
return list(lexer)
except ValueError:
return [] # an unclosed quote: the shell runs nothing of it
def is_operator(word: str) -> bool:
"""A control operator ends a simple command; a redirection (`>`, `2>&1`, `<<`) does not."""
return bool(word) and all(char in OPERATOR_CHARS for char in word)
def is_redirection(word: str) -> bool:
return bool(word) and all(char in "<>&" for char in word) and ("<" in word or ">" in word)
def simple_commands(words: list[str]) -> list[tuple[int, int]]:
bounds, start = [], 0
for index, word in enumerate(words + [";"]):
if is_operator(word):
if index > start:
bounds.append((start, index))
start = index + 1
return bounds
def command_words(words: list[str], start: int, end: int) -> tuple[list[int], list[int]]:
"""The words of a simple command without its redirections, and the `<<<` strings it reads (indices)."""
plain, strings = [], []
index = start
while index < end:
if words[index].isdigit() and index + 1 < end and is_redirection(words[index + 1]):
index += 1 # the file descriptor of `2>&1`
elif is_redirection(words[index]):
if words[index] == "<<<" and index + 1 < end:
strings.append(index + 1)
index += 2 # the operator and the word it takes (file, delimiter, string)
else:
plain.append(index)
index += 1
return plain, strings
def command_word(words: list[str], plain: list[int]) -> int | None:
"""Where in `plain` the word the command runs is: after assignments and wrappers with their options."""
index = 0
while index < len(plain):
word = words[plain[index]]
wrapper = WRAPPERS.get(Path(word).name)
if ASSIGNMENT.match(word):
index += 1
elif wrapper is None:
return index
else:
values, arguments = wrapper
index += 1
while index < len(plain) and words[plain[index]].startswith("-"):
index += 2 if words[plain[index]] in values else 1
index += arguments
return None
def ssh_host(words: list[str], plain: list[int], at: int) -> int | None:
"""Where in `plain` the host of the ssh at `at` is: the first word after its options and their values."""
index = at + 1
while index < len(plain) and words[plain[index]].startswith("-"):
index += 2 if words[plain[index]] in SSH_VALUE_OPTIONS else 1
return index if index < len(plain) else None
def shell_input(words: list[str], plain: list[int], at: int) -> tuple[int | None, int | None, bool]:
"""What the shell at `at` runs: (the script file word, the `-c` script word, whether it reads stdin)."""
index = at + 1
while index < len(plain) and words[plain[index]][:1] in "-+" and words[plain[index]] not in ("-", "--"):
option = words[plain[index]]
letters = option[1:] if option.startswith("-") and not option.startswith("--") else ""
if "n" in letters:
return None, None, False # -n reads the script and runs none of it
if "c" in letters:
return None, plain[index + 1] if index + 1 < len(plain) else None, False
if "s" in letters:
return None, None, True
index += 2 if option in SHELL_VALUE_OPTIONS else 1
if index < len(plain) and words[plain[index]] in ("-", "--"):
index += 1
return (plain[index], None, False) if index < len(plain) else (None, None, True)
def runs_gradle(words: list[str], start: int, position: int, end: int, on_desktop: bool,
leaves: frozenset[str] | None, refused: bool) -> bool:
name = Path(words[position]).name
if name == GRADLE_WRAPPER:
return on_desktop
if name != VERIFY_SCRIPT or refused or position + 1 >= end or words[position + 1] not in VERIFY_HEAVY_STAGES:
return False
target = verify_target(words, start, position, end, on_desktop, leaves)
return target is not None and (on_desktop if target == "here" else bool(DESKTOP_HOST.search(target)))
def verify_target(words: list[str], start: int, position: int, end: int, on_desktop: bool,
leaves: frozenset[str] | None) -> str | None:
"""The host scripts/verify.sh main runs this stage on, or None when it stops before Gradle.
It stops at usage on an unknown word, and run_leaf stops on a target that is not a registry gradle_path.
The last --on wins; without one it is ${VERIFY_HOST:-desktop}, where VERIFY_HOST comes from this command's
own assignments, an earlier `export`, or (on the laptop only) the environment.
"""
index = position + 2
if words[position + 1] == "leaf":
if index >= end or words[index].startswith("--") or is_redirection(words[index]):
return None # run_leaf needs a gradle_path
if leaves is not None and words[index] not in leaves:
return None
index += 1
target = None
while index < end:
word = words[index]
if is_redirection(word) or word.isdigit() and index + 1 < end and is_redirection(words[index + 1]):
index += 1 if word.isdigit() else 2
elif word in VERIFY_VALUE_OPTIONS and index + 1 < end:
target = words[index + 1] if word == "--on" else target
index += 2
elif word in VERIFY_FLAGS:
index += 1
else:
return None
if target is not None:
return target
own = [word for word in words[start:position] if word.startswith(VERIFY_HOST_ASSIGNMENT)]
exported = [word for first, last in simple_commands(words[:start]) if words[first] == "export"
for word in words[first + 1:last] if word.startswith(VERIFY_HOST_ASSIGNMENT)]
environment = [] if on_desktop else [VERIFY_HOST_ASSIGNMENT + os.environ.get("VERIFY_HOST", "")]
value = next((word[len(VERIFY_HOST_ASSIGNMENT):] for word in own[::-1] + exported[::-1] + environment), "")
return value or "desktop"
def turn_end_reason(state: dict) -> str | None:
edits = state.get("java_edits") 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 턴 끝 알림] 이 세션에서 Java 파일 {len(edits)}개를 고쳤고({shown}) 그 뒤 desktop Gradle 실행이 없다. "
"컴파일과 테스트는 노트북이 아니라 desktop에서 한다: 저장소 루트에서 `scripts/verify.sh leaf <gradle-path>`"
"(경로는 registry `gradle_path`)를 돌리면 desktop에서 소유 leaf의 `check`가 돈다(AGENTS.md 「검증」, "
"docs/work/operate.md 4.1절). 이번 턴에 돌릴 수 없으면 완료를 말하지 말고, 보고의 확인 줄에 돌리지 못한 것과"
" 이유를 적는다(HARD-STOP 6). 이 알림은 다음 Java 편집 전까지 한 번만 나온다.")
# ----------------------------------------------------------------------------------------------------
# events
def pre_edit(payload: dict) -> int:
message = h13_message(project_root(payload), edited_path(payload))
if message:
print(message, file=sys.stderr)
return 2
return 0
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
lines: list[str] = []
if wants_format(path):
state = load_state(root, payload.get("session_id", ""))
formatted = format_java(root, path)
if formatted and formatted[0].startswith(SKIPPED):
# The reason does not change within a session; saying it on every edit is noise.
formatted = [] if state.get("format_skip_reported") else formatted
state["format_skip_reported"] = True
lines += formatted
if path not in state["java_edits"]:
state["java_edits"].append(path)
state["reminded"] = False
save_state(root, payload.get("session_id", ""), state)
lines += boundary_findings(root, path, (root / path).read_text(encoding="utf-8"))
if wants_doc_check(path):
documents = doc_findings(root, path)
records = record_findings(root, path)
# N6 has no gate behind it, so its first line always shows; next to N2 failure lines it keeps only that.
lines += (records[:1] if documents else records) + documents
if lines:
print(context("PostToolUse", lines))
return 0
def registry_leaves(root: Path) -> frozenset[str] | None:
try:
return frozenset(module["gradle_path"] for module in load_registry(root))
except (OSError, ValueError, KeyError, TypeError, AttributeError):
return None
def post_bash(payload: dict) -> int:
command = (payload.get("tool_input") or {}).get("command", "")
response = payload.get("tool_response")
output = "\n".join(str(response.get(key, "")) for key in ("stdout", "stderr")) if isinstance(response, dict) else ""
root = project_root(payload)
if ran_desktop_gradle(command, leaves=registry_leaves(root), refused=VERIFY_REFUSED in output):
state = load_state(root, payload.get("session_id", ""))
state["java_edits"] = []
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 = {"pre-edit": pre_edit, "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:]))