문제: 앞 커밋이 Gradle 루트를 저장소 루트로 옮기고 계층 폴더를 묶었다.
빌드 스크립트·build-logic·시험·workflow·스크립트·문서가 아직 옛 배치
(Gradle 루트 = src/)를 가정해 빌드가 되지 않는다.
고른 방법:
- Gradle 경로와 registry id는 그대로 둔다(:app-bootstrap, :application-core,
:composition:*). registry의 source_path만 새 폴더를 가리킨다. 폴더에 맞춘
이름(:domain:core, :application:core)은 프로젝트 이름 core가 둘이 되어
boot jar의 BOOT-INF/lib와 기본 capability가 겹치고, 파생 서비스의 모든
project(':…') 줄을 바꾸게 한다.
- registry는 gradle/modules.json, 시험 이미지 목록은
gradle/container-images.properties: 버전 카탈로그 옆, 빌드가 고정하는 것.
config/는 코드 검사 도구 설정만 둔다.
- build-logic: settings·architecture 플러그인의 저장소 루트를 Gradle 루트로
(getParentFile 제거). config contract의 파일 트리는 src/만 훑는다(루트를
훑으면 docs·.claude/worktrees까지 줍는다).
- 빌드 스크립트: rootProject.projectDir.parentFile → rootProject.projectDir,
rootProject.file('../…') → rootProject.file('…'), 옛 src 기준 include에
src/를 붙인다. notification API surface의 application-notification 소스
루트를 새 폴더로(놓치면 272개 타입이 surface에서 말없이 빠진다).
- 시험: 옛 src 기준 모듈 목록과 ../ 개수를 고친다. 없는 폴더를 말없이
건너뛰던 목록(MessagingAuthority, NotificationPayloadAtRest 등)을 새
폴더로, FileserverDocumentationCoverageTest는 Gradle 경로 → 폴더를
registry로 찾는다. Docker 계약은 WORKDIR /build, 새 jar 경로.
- Docker: 빌드 context를 저장소 루트로, .dockerignore는 허용 목록으로 다시
써서 전에 context였던 것만 들어가게 한다. compose의 build.context는 .,
env_file은 ./.env.
- workflow: working-directory: src 기본값과 그것을 되돌리던 줄을 지운다.
- scripts: verify.sh, ci/*, bootstrap-local, new-feature,
verify-feature-scaffold, mongo 검증, hooks, check-repo-layout 허용 목록.
check-docs의 경로 검사는 build-logic/·gradle/로 시작하는 경로도 본다.
- 문서: AGENTS.md 지도, README 구조 표, leaf AGENTS.md의 cd src, gates·
operate·결정 색인, src/bootstrap/AGENTS.md를 조립 계층 family 규칙으로
다시 쓴다. 기록 문서(docs/design·history·reviews, 지난 upgrade 안내,
capability-status 제거 표)는 머리 블록만 고친다. 파생 서비스용 안내
docs/upgrade/2026-11-relayout.md를 더한다.
위험: bootRun working dir가 저장소 루트가 되어 .env와 상대 경로 설정이
루트 기준이다. 루트 .env는 compose 보간에도 읽힌다(upgrade 안내 5절).
파생 서비스는 태그 pre-relayout-2026-11까지 받은 뒤 이 묶음을 받는다.
검증: desktop에서 캐시 없이 scripts/verify.sh docs·pr·main·release,
compose smoke 18 lane, 빠른 시작(scripts/verify.sh app). 결과는 PR 본문.
구조 리뷰(arch-reviewer) 지적 5건을 반영했다.
BREAKING CHANGE: Gradle은 저장소 루트에서 돈다(cd src 없음). registry는
gradle/modules.json, 이미지 빌드 context는 저장소 루트다. 옛 경로 → 새 경로
표는 docs/upgrade/2026-11-relayout.md.
Refs: design-docs repo-structure/01-backend-layout.md 6.1절 가-2·가-3
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 = "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
|
|
|
|
# --- 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:]))
|