템플릿 안에 프로젝트 계층이 아닌 메시징 플랫폼(src/platforms/messaging,
19개 모듈)이 있다. 소유자 결정(2026-11-07)은 라이브러리를 별도 repo에서
관리하고 템플릿은 버전으로 받는 것이다. 라이브러리는 이력째
messaging-library로 옮겨 dev.cakit.messaging 1.0.0으로 Gitea Packages에
게시했다(태그 v1.0.0 = 8c6045e, release run 28).
- 받는 법: src/settings.gradle에 exclusiveContent 저장소(group dev.cakit와
그 아래는 Gitea에서만, 나머지는 Maven Central에서만). 카탈로그
messagingLibrary = "1.0.0"과 쓰는 모듈 여섯.
- 쓰는 leaf: adapter:outbound:messaging, adapter:outbound:messaging-kafka,
adapter:inbound:messaging(admin exclude 좌표를 새 group으로), 시험만
composition:outbox-relay와 app-bootstrap architectureTest. import와
auto-configuration 이름 문자열 dev.caskeleton.messaging →
dev.cakit.messaging, 시험 stand-in도 같은 FQCN으로.
- persistence-jpa migration 시험이 라이브러리 소스 폴더를 경로
(../../../platforms/…)로 읽던 것을, 카탈로그 버전의 jar를 전용 구성
messagingMigrations(non-transitive)로 받아 db/migration을 풀어 읽게
했다. classpath에 올리면 그 leaf 시험의 Flyway가 메시징 migration까지
볼 수 있어 버렸다.
- registry: 메시징 19행을 지우고 library_groups ["dev.cakit"]와 쓰는 세
행의 allowed_libraries. 분리 전 프로젝트 edge 검사가 지키던 약속이
앞 커밋의 라이브러리 edge 검사로 그대로 남는다.
- 계약 테스트: MessagingPublicSurfaceContractTest는 라이브러리로 옮겼고,
MessagingAuthorityContractTest는 이 repo의 app.messaging 주인 하나만
본다(라이브러리 쪽 하나는 그 repo가 본다).
- system caller 규칙(ApplicationBoundaryArchitectureTest)의 「프로젝트
타입」에 dev.cakit.을 더했다. 메시지 handler가 구현하는 MessageHandler가
라이브러리 타입이 되면서, 그대로 두면 manual 09의 handler가
SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES에 걸리고 MessageHandler로
주입받는 endpoint를 USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS가
따라가지 못한다(구조 리뷰가 찾음).
- 순서 시험: 이름 정렬로도 라이브러리 root가 먼저 오게 되어 bridge 시험이
afterName을 지키지 못했다. stand-in을 맨 뒤 순서로 두고, inbox 쪽
beforeName을 지키는 시험을 더했다.
- 지움: src/platforms(와 빈 폴더), messaging-certification.yml, 카탈로그의
avro·cloudevents·protobuf 4.33.2, SpotBugs 제외의 메시징 줄,
check-repo-layout.py의 platforms. 편집 훅이 계층 leaf의 dev.cakit import를
알린다.
- lockfile: 바뀐 줄은 dev.cakit.messaging 좌표 추가 45줄뿐이다(외부
의존성 집합은 그대로, 설계 16절 H6).
버린 대안: 라이브러리 jar를 persistence-jpa testRuntimeOnly로 올려
classpath에서 읽기(위 이유). 템플릿에 docs/messaging 사본을 남기기
(라이브러리 문서와 갈라진다. 다음 커밋이 문서를 그 repo로 가리킨다).
위험: 캐시가 빈 빌드(새 기계, 이미지 builder)는 git.learn.hyeonworks.com에
닿아야 한다. 공개 owner라 토큰은 필요 없다(익명 200 확인). 이 커밋만으로는
살아 있는 문서가 지운 경로를 부른다(check-docs는 다음 커밋에서 통과).
검증: desktop에서 이 트리로 RED·GREEN(system caller 고정 시험 2건, 순서
시험 2건은 수정 전·제약 제거 시 실패, 수정 후 통과). 전체 게이트는
PR 본문.
BREAKING CHANGE: src/platforms/messaging과 project(':messaging:…') 경로가
없어졌다. dev.cakit.messaging:<모듈>:1.0.0 좌표로 받고 import를
dev.caskeleton.messaging → dev.cakit.messaging으로 바꾼다
(docs/upgrade/2026-11-maturity-review.md B-57~B-59).
Refs: design-docs repo-structure/05-library-repos.md 4·8·10·13절
465 lines
20 KiB
Python
465 lines
20 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
|
|
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 hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
REGISTRY = "src/config/architecture/modules.json"
|
|
CATALOG = "src/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 = ("src/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
|
|
|
|
# --- N5: a Bash command that ran Gradle on the desktop clears the pending Java edits --------------------
|
|
DESKTOP_HOST = re.compile(r"desktop")
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------------
|
|
# 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
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------------
|
|
# N5 — Java changed and the desktop has not compiled it since
|
|
|
|
|
|
def ran_desktop_gradle(command: str) -> bool:
|
|
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 "gradlew" in command:
|
|
return True
|
|
return False
|
|
|
|
|
|
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에서 소유 leaf의 `<gradle-path>:check`로 한다"
|
|
"(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):
|
|
lines += doc_findings(root, path)
|
|
if lines:
|
|
print(context("PostToolUse", lines))
|
|
return 0
|
|
|
|
|
|
def post_bash(payload: dict) -> int:
|
|
command = (payload.get("tool_input") or {}).get("command", "")
|
|
if ran_desktop_gradle(command):
|
|
root = project_root(payload)
|
|
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:]))
|