fix(hooks): N5가 verify.sh를 desktop 실행으로 보고 기록 본문 알림 N6를 더한다 #84
@@ -2,7 +2,7 @@
|
||||
|
||||
## Claude Code에서만
|
||||
|
||||
- 권한과 훅은 `.claude/settings.json`이다: 편집 직후 Java 한 파일 포맷·레이어 의존 알림·문서 검사, 턴 끝 desktop 검증 알림, 적용된 migration 편집 차단, 실제 `.env` 읽기 차단. 훅마다 하는 일과 시험은 `scripts/hooks/README.md`다.
|
||||
- 권한과 훅은 `.claude/settings.json`이다: 편집 직후 Java 한 파일 포맷·레이어 의존 알림·문서 검사·기록 본문 알림, 턴 끝 desktop 검증 알림, 적용된 migration 편집 차단, 실제 `.env` 읽기 차단. 훅마다 하는 일과 시험은 `scripts/hooks/README.md`다.
|
||||
- 공통 훅·스킬(되돌릴 수 없는 명령 차단, 비밀 값 알림, 장부, `estimate`·`retro`·`techdebt`)은 하네스 플러그인 `harness@claude-harness`다(같은 settings가 켠다). 비대화형(`claude -p`)은 설치하지 않으니 claude-harness README의 `--scope project` 두 명령을 한 번 돌린다.
|
||||
- 경로별 규칙(테스트·설정·Docker·문서)은 `.claude/rules/`에 있다. 그 경로의 파일을 열 때 읽힌다.
|
||||
- 스킬은 `.claude/skills/`다: `new-feature`(새 기능), `desktop-gates`(Gradle·Docker를 desktop에서), 분야 지식 `be-*`(`paths`가 걸려 그 분야 파일을 만질 때 목록에 뜬다). 여러 분야면 플러그인 `lead`. 발동 조건이 설명에 있어 모델이 부른다.
|
||||
|
||||
+10
-5
@@ -4,9 +4,9 @@ Claude Code가 정해진 때에 대신 실행하는 명령이다. 연결은 `.cl
|
||||
|
||||
```text
|
||||
Edit·Write 직전 ──> pre-edit ──> H13 적용된 migration이면 막는다(종료 코드 2)
|
||||
Edit·Write 직후 ──> post-edit ──> Java면 포맷 → N1 레이어 의존 알림, 문서면 N2 문서 검사 알림
|
||||
Bash 직후 ──> post-bash ──> desktop에서 Gradle을 돌렸으면 N5 기록을 비운다
|
||||
턴 끝 ──> stop ──> N5 Java를 고쳤는데 desktop 실행이 없으면 한 번 알린다
|
||||
Edit·Write 직후 ──> post-edit ──> Java면 포맷 → N1 레이어 의존 알림, 문서면 N6 기록 본문 알림 → N2 문서 검사 알림
|
||||
Bash 직후 ──> post-bash ──> desktop에서 Gradle을 돌렸으면(scripts/verify.sh 무거운 단계) N5 기록을 비운다
|
||||
턴 끝 ──> stop ──> N5 Java를 고쳤는데 desktop 실행이 없으면 scripts/verify.sh leaf <gradle-path>를 한 번 알린다
|
||||
```
|
||||
|
||||
## 1. 원칙
|
||||
@@ -25,9 +25,14 @@ Bash 직후 ──> post-bash ──> desktop에서 Gradle을 돌렸으면
|
||||
| 포맷 | PostToolUse `Edit\|Write\|MultiEdit` | `src/**/*.java`(`build/` 제외. `build-logic/`은 `src/` 밖이라 대상이 아니다)를 google-java-format으로 맞춘다. 버전은 카탈로그 `googleJavaFormat`, jar는 Gradle 캐시, 옵션은 Spotless 단계와 같게 `--skip-reflowing-long-strings --replace` | 파일이 바뀌면 「다시 읽는다」 한 줄. 문법 오류면 첫 줄들 |
|
||||
| N1 | 같은 때, `src/**/src/main/java/**/*.java` | registry로 그 파일의 leaf를 찾고 import를 본다: 순수성 목록(`DomainPurityArchitectureTest`, `verifyApplicationCoreDependencyPurity`와 같은 패키지), inbound의 persistence 접근, `dev.caskeleton.*`의 주인 leaf가 registry `allowed_dependencies`(전이 포함)에 있는지 | 「HARD-STOP N 의심」 줄 |
|
||||
| N2 | 같은 때, `*.md` | `scripts/check-work-docs.py`와 `scripts/check-docs.py`를 돌린다 | 실패 줄. 고친 문서를 가리키는 줄이 있으면 그것만 |
|
||||
| N5 | Stop | 이 세션에서 Java를 고친 뒤 `ssh <desktop 호스트> … gradlew …` 실행이 없으면 턴을 한 번 막고 이유를 준다 | `decision: block`, 다음 Java 편집 전까지 한 번 |
|
||||
| N6 | 같은 때, `*.md` | `docs/vision.md`면 소유자 문서라고 알린다. `scripts/check-docs.py`의 기록 폴더(`RECORD_KINDS`) 문서면 기준 커밋의 옛 글과 머리 블록 끝(`HEAD_END`) 뒤 본문을 비교한다. 기준 커밋은 `scripts/verify.sh`와 같은 `git merge-base HEAD "${VERIFY_BASE_REF:-origin/main}"`이고, 그 ref가 없으면 HEAD다. 결정 기록(`DECISION_PREFIXES`)은 옛 본문이 새 본문의 앞부분이면 되고(끝에 보완 절), 나머지 기록은 같아야 한다. 끝의 빈 줄은 세지 않는다. 기준 커밋에 없는 기록(이 브랜치에서 처음 쓴 기록, 커밋했어도)과 `docs/reviews/`는 보지 않는다. 상수는 그 파일의 소스에서 읽고, 그 파일을 실행하지 않는다 | 「기록 본문 알림(N6)」과 바뀐 줄(최대 5줄), 또는 「소유자 문서 알림(N6)」 한 줄. N2 실패 줄이 함께 있으면 N6는 첫 줄만 내고 N2 줄이 뒤따른다 |
|
||||
| N5 | Stop | 이 세션에서 Java를 고친 뒤 desktop 실행이 없으면 턴을 한 번 막고 `scripts/verify.sh leaf <gradle-path>`를 가리킨다. desktop 실행으로 보는 것은 둘이다: `scripts/verify.sh`의 Gradle 단계(`leaf`·`pr`·`main`·`nightly`·`release`·`app`·`round`)를 desktop에서 돌린 것(`--on`이 없으면 기본 호스트 `${VERIFY_HOST:-desktop}`, `--on here`는 `ssh <desktop 호스트>` 안에서만), 그리고 `ssh <desktop 호스트>` 안에서 돈 `gradlew`. `docs` 단계, 노트북의 `--on here`와 `gradlew`는 아니다 | `decision: block`, 다음 Java 편집 전까지 한 번 |
|
||||
|
||||
- N5가 기억하는 것은 `.claude/hook-state/<session_id>.json`이다(git이 무시한다).
|
||||
- N5는 셸 문법을 다 풀지 않는다. 주석·줄 잇기·here-document 본문을 떼고 `;`·`&&`·`||`·`|`·`&`·괄호·줄바꿈으로 명령을 나눈다. 명령마다 실제로 실행되는 낱말 하나만 본다: 대입(`VERIFY_HOST=…`)과 감싸개(`timeout`·`flock`·`env`·`nohup` 등) 뒤의 낱말, 셸에 준 스크립트 파일. 그래서 `echo scripts/verify.sh pr`·`bash -n …`은 세지 않는다.
|
||||
- `ssh <desktop 호스트>`의 원격 명령은 ssh가 보내는 대로 낱말을 이어 desktop에서 읽는다. 노트북 셸이 ssh에 거는 리다이렉션(`> log`, `2>&1`)은 원격 명령이 아니다. here-document 본문·`<<<` 문자열·`<셸> -c '…'`은 `ssh <desktop 호스트>`나 셸(`bash`·`sh`·`zsh`)이 스크립트로 받을 때만 명령으로 읽고, 그 밖의 본문(`cat > 파일 <<EOF`, `git commit -F - <<EOF`, `bash 파일 <<EOF`)은 글로 본다. 스크립트 안의 스크립트는 `hooks.py` `MAX_NESTING`단까지만 읽는다.
|
||||
- `verify.sh`가 Gradle 전에 멈추는 실행은 세지 않는다: 사용법 오류로 멈출 인자(모르는 인자, 대상 없는 `leaf`), registry `gradle_path`가 아닌 `leaf` 대상, 출력에 「미추적 파일이 있어 보내지 않는다」(rc 5)가 있는 실행. 원격 준비 실패(rc 4)는 출력으로 가리지 못해 센다.
|
||||
- N6는 편집 도구(Edit·Write·MultiEdit)로 바꾼 파일만 본다. Bash의 일괄 치환(`sed -i` 등)으로 바꾼 기록은 잡지 못한다. 그렇게 바꿔 커밋한 본문은 그 파일을 다음에 편집할 때 알린다. 편집 없이 커밋만 한 변경은 리뷰가 본다.
|
||||
- 권한 쪽 차단: `.claude/settings.json`의 `permissions.deny`가 실제 `.env`·`.env.local`·`.env.lane` 읽기·쓰기를 막는다. `.env.example` 같은 예시는 막지 않는다.
|
||||
|
||||
## 3. 시험
|
||||
@@ -36,7 +41,7 @@ Bash 직후 ──> post-bash ──> desktop에서 Gradle을 돌렸으면
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
```
|
||||
|
||||
- 고장 낸 입력(적용된 migration 편집, 도메인의 Spring import, 들여쓰기가 틀린 Java, 깨진 링크)에서 막힘·알림이 나오고, 맞는 입력에서 조용한지 본다.
|
||||
- 고장 낸 입력(적용된 migration 편집, 도메인의 Spring import, 들여쓰기가 틀린 Java, 깨진 링크, 기록 본문 고침)에서 막힘·알림이 나오고, 맞는 입력에서 조용한지 본다.
|
||||
- 실제 포매터 시험은 Gradle 캐시에 카탈로그 버전 jar가 있는 기계에서만 돈다. 그 밖에서는 가짜 `java`로 옵션·파일 전달·바뀜 감지를 본다.
|
||||
- 훅을 고치면 조건을 끈 사본에서도 시험이 실패하는지 본다(변이 시험). 조건 하나를 끄는 것마다 시험 하나 이상이 실패해야 한다.
|
||||
|
||||
|
||||
+403
-15
@@ -4,7 +4,7 @@
|
||||
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-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
|
||||
|
||||
@@ -17,6 +17,8 @@ scripts/tests/test_hooks.py.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import difflib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -68,8 +70,51 @@ MAIN_JAVA = re.compile(r"^(?P<leaf>src/.+?)/src/main/java/(?P<rest>.+\.java)$")
|
||||
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_.-]+))")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
@@ -356,21 +401,351 @@ def doc_findings(root: Path, path: str) -> list[str]:
|
||||
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) -> bool:
|
||||
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:
|
||||
words = shlex.split(command)
|
||||
return list(lexer)
|
||||
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
|
||||
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:
|
||||
@@ -379,8 +754,9 @@ def turn_end_reason(state: dict) -> str | None:
|
||||
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절). 이번 턴에 돌릴 수 없으면 완료를 말하지 말고, 보고의 확인 줄에 돌리지 못한 것과"
|
||||
"컴파일과 테스트는 노트북이 아니라 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 편집 전까지 한 번만 나온다.")
|
||||
|
||||
|
||||
@@ -416,16 +792,28 @@ def post_edit(payload: dict) -> int:
|
||||
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)
|
||||
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", "")
|
||||
if ran_desktop_gradle(command):
|
||||
root = project_root(payload)
|
||||
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
|
||||
|
||||
+341
-3
@@ -9,6 +9,7 @@ import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -113,6 +114,15 @@ def fake_java(folder: Path, body: str) -> str:
|
||||
return f"{folder}{os.pathsep}{os.environ.get('PATH', '')}"
|
||||
|
||||
|
||||
def load_document_checker():
|
||||
"""The real scripts/check-docs.py as a module, to hold N6 to the rules the gate uses."""
|
||||
spec = importlib.util.spec_from_file_location("check_docs", SCRIPTS / "check-docs.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules["check_docs"] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def added_context(stdout: str) -> str:
|
||||
return json.loads(stdout)["hookSpecificOutput"]["additionalContext"] if stdout else ""
|
||||
|
||||
@@ -320,11 +330,180 @@ class DocumentNudgeTest(RepositoryTestCase):
|
||||
self.assertEqual(run_event("post-edit", self.repo.payload("docs/guide.md"), self.environment), (0, "", ""))
|
||||
|
||||
|
||||
class RecordBodyNudgeTest(RepositoryTestCase):
|
||||
"""N6 — a record keeps the body after its head block as written; docs/vision.md is the owner's."""
|
||||
|
||||
DESIGN = "docs/design/2026-11-01-example-design.md"
|
||||
ADR = "docs/adr/ADR-EX-001-example.md"
|
||||
REVIEW = "docs/reviews/2026-11-01-example/README.md"
|
||||
BODY = ["", "# 예시", "", "## 배경", "", "옛 방식을 쓴다.", "", "## 결정", "", "새 방식을 쓴다.", ""]
|
||||
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
# The real checker, so N6 reads the record folders and the head block end the gate uses.
|
||||
self.repo.write(hooks.DOC_CHECKER, (REPO / hooks.DOC_CHECKER).read_text(encoding="utf-8"))
|
||||
self.rules = hooks.record_rules(REPO)
|
||||
# N2 runs the document checks on every document edit and has its own tests.
|
||||
quiet = mock.patch.object(hooks, "doc_findings", return_value=[])
|
||||
quiet.start()
|
||||
self.addCleanup(quiet.stop)
|
||||
self.repo.write(self.DESIGN, self.record("상태: 채택", self.BODY))
|
||||
self.repo.write(self.ADR, self.record("상태: 채택", self.BODY))
|
||||
self.repo.write(self.REVIEW, "# 리뷰\n\n발견 0건.\n")
|
||||
self.repo.write(hooks.VISION, "# 비전\n\n> 소유자가 직접 쓴다.\n")
|
||||
for command in (["init", "-q"], ["add", "-A"], ["commit", "-q", "-m", "기록"]):
|
||||
self.git(*command)
|
||||
# The base is ${VERIFY_BASE_REF:-origin/main}; the owner's shell may set one.
|
||||
environment = mock.patch.dict(os.environ)
|
||||
environment.start()
|
||||
self.addCleanup(environment.stop)
|
||||
os.environ.pop(hooks.BASE_REF_VARIABLE, None)
|
||||
|
||||
def git(self, *command: str) -> None:
|
||||
subprocess.run(["git", "-c", "user.name=test", "-c", "user.email=test@example.invalid",
|
||||
"-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *command],
|
||||
cwd=self.repo.root, check=True, capture_output=True)
|
||||
|
||||
def record(self, status: str, body: list[str]) -> str:
|
||||
head = [self.rules["HEAD_START"], "> **기록**", "", f"- {status}", "- 작성일: 2026-11-01", self.rules["HEAD_END"]]
|
||||
return "\n".join(head + body)
|
||||
|
||||
def edit(self, path: str, text: str) -> tuple[int, str]:
|
||||
self.repo.write(path, text)
|
||||
code, out, _ = run_event("post-edit", self.repo.payload(path), self.environment)
|
||||
return code, added_context(out)
|
||||
|
||||
def changed(self, old: str, new: str) -> list[str]:
|
||||
return [new if line == old else line for line in self.BODY]
|
||||
|
||||
def test_the_record_rules_are_the_document_checkers(self) -> None:
|
||||
self.assertIsNotNone(self.rules, "scripts/check-docs.py에서 N6가 읽는 상수를 찾지 못했다")
|
||||
checker = load_document_checker()
|
||||
for path in ("docs/design/a.md", "docs/history/plans/a.md", "docs/adr/a.md", self.REVIEW,
|
||||
"docs/work/README.md", hooks.VISION):
|
||||
self.assertEqual(hooks.is_record(self.rules, path), checker.record_kind(path) is not None, path)
|
||||
for text in (self.record("상태: 채택", self.BODY), "# 머리 블록 없음\n\n본문\n",
|
||||
"\n".join(["# 시작 줄 없음", self.rules["HEAD_END"], "본문"]),
|
||||
"\n".join([self.rules["HEAD_START"]] + ["- 칸"] * 30 + [self.rules["HEAD_END"], "본문"])):
|
||||
body, _ = hooks.record_body(self.rules, text)
|
||||
expected = checker.strip_head_block(text.split("\n"))
|
||||
self.assertEqual(body, expected[:len(body)], text[:40])
|
||||
self.assertFalse("".join(expected[len(body):]).strip(), text[:40])
|
||||
|
||||
def test_changing_only_the_head_block_is_quiet(self) -> None:
|
||||
self.assertEqual(self.edit(self.DESIGN, self.record("상태: 대체됨", self.BODY)), (0, ""))
|
||||
|
||||
def test_a_supplement_appended_to_a_decision_record_is_quiet(self) -> None:
|
||||
supplement = self.BODY[:-1] + ["", "## 보완 (2026-11-22)", "", "보완한 내용이다.", ""]
|
||||
self.assertEqual(self.edit(self.ADR, self.record("상태: 채택(보완)", supplement)), (0, ""))
|
||||
|
||||
def test_a_record_not_committed_yet_is_quiet(self) -> None:
|
||||
path = "docs/history/plans/2026-11-22-new-plan.md"
|
||||
self.assertEqual(self.edit(path, self.record("상태: 실행 중", ["", "새 계획이다."])), (0, ""))
|
||||
|
||||
def test_a_review_record_is_not_checked_here(self) -> None:
|
||||
self.assertEqual(self.edit(self.REVIEW, "# 리뷰\n\n발견 1건.\n"), (0, ""))
|
||||
|
||||
def test_a_changed_body_line_of_a_design_record_is_named(self) -> None:
|
||||
code, text = self.edit(self.DESIGN, self.record("상태: 채택", self.changed("옛 방식을 쓴다.", "옛 방식을 고쳐 쓴다.")))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn(f"기록 본문 알림(N6) {self.DESIGN}:", text)
|
||||
self.assertIn("머리 블록 칸만 고친다", text)
|
||||
# No origin/main in this repository: the base is HEAD.
|
||||
self.assertIn("기준 커밋(HEAD)과 1곳 다르다", text)
|
||||
self.assertIn("12행: 기준 「옛 방식을 쓴다.」 → 지금 「옛 방식을 고쳐 쓴다.」", text)
|
||||
|
||||
def test_a_record_written_and_committed_on_this_branch_is_quiet(self) -> None:
|
||||
# The base is where this branch left origin/main, before the branch wrote and committed this plan.
|
||||
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
|
||||
path = "docs/history/plans/2026-11-22-branch-plan.md"
|
||||
self.repo.write(path, self.record("상태: 실행 중", ["", "- [ ] 1단계"]))
|
||||
self.git("add", "-A")
|
||||
self.git("commit", "-q", "-m", "계획")
|
||||
self.assertEqual(self.edit(path, self.record("상태: 실행 중", ["", "- [x] 1단계"])), (0, ""))
|
||||
|
||||
def test_a_body_change_committed_on_this_branch_is_named_at_the_next_edit(self) -> None:
|
||||
self.git("branch", "trunk")
|
||||
changed = self.changed("옛 방식을 쓴다.", "옛 방식을 고쳐 쓴다.")
|
||||
self.repo.write(self.DESIGN, self.record("상태: 채택", changed))
|
||||
self.git("commit", "-q", "-am", "본문 고침")
|
||||
# VERIFY_BASE_REF moves the base, as it does for scripts/verify.sh.
|
||||
os.environ[hooks.BASE_REF_VARIABLE] = "trunk"
|
||||
code, text = self.edit(self.DESIGN, self.record("상태: 대체됨", changed))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("기준 커밋(merge-base trunk)과 1곳 다르다", text)
|
||||
self.assertIn("12행: 기준 「옛 방식을 쓴다.」 → 지금 「옛 방식을 고쳐 쓴다.」", text)
|
||||
|
||||
def test_the_base_is_the_one_verify_sh_compares_with(self) -> None:
|
||||
script = (REPO / "scripts/verify.sh").read_text(encoding="utf-8")
|
||||
self.assertIn(f'git merge-base HEAD "${{{hooks.BASE_REF_VARIABLE}:-{hooks.BASE_REF_DEFAULT}}}"', script)
|
||||
|
||||
def test_a_section_appended_to_a_design_record_is_named(self) -> None:
|
||||
appended = self.BODY[:-1] + ["", "## 덧붙인 절", ""]
|
||||
self.assertIn("기록 본문 알림(N6)", self.edit(self.DESIGN, self.record("상태: 채택", appended))[1])
|
||||
|
||||
def test_a_changed_middle_of_a_decision_record_is_named_even_with_a_supplement(self) -> None:
|
||||
body = self.changed("옛 방식을 쓴다.", "다른 방식을 쓴다.")[:-1] + ["", "## 보완 (2026-11-22)", ""]
|
||||
code, text = self.edit(self.ADR, self.record("상태: 채택(보완)", body))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn(f"기록 본문 알림(N6) {self.ADR}:", text)
|
||||
self.assertIn("보완 절로 덧붙이고", text)
|
||||
self.assertEqual([line for line in text.splitlines() if line.startswith("- ")],
|
||||
["- 12행: 기준 「옛 방식을 쓴다.」 → 지금 「다른 방식을 쓴다.」"])
|
||||
|
||||
def test_blank_lines_added_at_the_end_are_quiet(self) -> None:
|
||||
self.assertEqual(self.edit(self.DESIGN, self.record("상태: 채택", self.BODY + ["", ""])), (0, ""))
|
||||
|
||||
def test_an_appended_section_is_shown_by_its_first_written_line(self) -> None:
|
||||
appended = self.BODY[:-1] + ["", "## 덧붙인 절", ""]
|
||||
self.assertIn("18행: 기준 「」 → 지금 「## 덧붙인 절」", self.edit(self.DESIGN, self.record("상태: 채택", appended))[1])
|
||||
|
||||
def test_many_changes_stay_within_five_lines(self) -> None:
|
||||
body = ["" if not line else f"{line} 고침" for line in self.BODY]
|
||||
text = self.edit(self.DESIGN, self.record("상태: 채택", body))[1]
|
||||
self.assertLessEqual(len(text.splitlines()), hooks.MAX_LINES)
|
||||
self.assertIn("곳 더", text)
|
||||
|
||||
def test_an_edit_of_the_vision_says_it_is_the_owners(self) -> None:
|
||||
code, text = self.edit(hooks.VISION, "# 비전\n\n1. 에이전트가 채웠다.\n")
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("(N6) docs/vision.md: 소유자만 쓴다(docs/vision.md:3-4). 되돌리고 제안만 한다.", text)
|
||||
|
||||
def test_without_the_document_checker_the_edit_is_not_failed(self) -> None:
|
||||
(self.repo.root / hooks.DOC_CHECKER).unlink()
|
||||
changed = self.record("상태: 채택", self.changed("옛 방식을 쓴다.", "옛 방식을 고쳐 쓴다."))
|
||||
self.assertEqual(self.edit(self.DESIGN, changed), (0, ""))
|
||||
|
||||
def test_a_checker_missing_a_constant_or_computing_one_keeps_n6_quiet(self) -> None:
|
||||
changed = self.record("상태: 채택", self.changed("옛 방식을 쓴다.", "옛 방식을 고쳐 쓴다."))
|
||||
literals = "".join(f"{name} = {self.rules[name]!r}\n" for name in hooks.DOC_CHECKER_NAMES if name != "HEAD_END")
|
||||
for checker in (literals, literals + "HEAD_END = make_end()\n"):
|
||||
with self.subTest(checker=checker[-30:]):
|
||||
self.repo.write(hooks.DOC_CHECKER, checker)
|
||||
self.assertEqual(self.edit(self.DESIGN, changed), (0, ""))
|
||||
|
||||
def test_next_to_n2_failure_lines_n6_keeps_only_its_first_line(self) -> None:
|
||||
failures = ["문서 검사 알림(N2) 실패 줄:", "- [head] 머리 블록 둘째 줄", "- [link] 깨진 링크"]
|
||||
body = ["" if not line else f"{line} 고침" for line in self.BODY]
|
||||
with mock.patch.object(hooks, "doc_findings", return_value=failures):
|
||||
text = self.edit(self.DESIGN, self.record("상태: 채택", body))[1]
|
||||
self.assertEqual(text.splitlines(), [text.splitlines()[0]] + failures)
|
||||
self.assertIn("기록 본문 알림(N6)", text.splitlines()[0])
|
||||
|
||||
|
||||
class TurnEndNudgeTest(RepositoryTestCase):
|
||||
"""N5 — Java edited and no desktop Gradle run since: the turn end says so once."""
|
||||
|
||||
SOURCE = "src/domain/core/src/main/java/dev/caskeleton/domain/order/Order.java"
|
||||
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
# scripts/verify.sh reads VERIFY_HOST for its default host; the owner's shell may set one.
|
||||
environment = mock.patch.dict(os.environ)
|
||||
environment.start()
|
||||
self.addCleanup(environment.stop)
|
||||
os.environ.pop("VERIFY_HOST", None)
|
||||
|
||||
def edit_java(self) -> None:
|
||||
run_event("post-edit", self.repo.payload(self.SOURCE), self.environment)
|
||||
|
||||
@@ -332,9 +511,9 @@ class TurnEndNudgeTest(RepositoryTestCase):
|
||||
out = run_event("stop", {"session_id": "s1", "cwd": str(self.repo.root), **extra})[1]
|
||||
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 bash(self, command: str, response: dict | None = None) -> None:
|
||||
payload = {"session_id": "s1", "cwd": str(self.repo.root), "tool_name": "Bash", "tool_input": {"command": command}}
|
||||
run_event("post-bash", payload if response is None else {**payload, "tool_response": response})
|
||||
|
||||
def test_a_java_edit_blocks_the_turn_end_once_with_the_reason(self) -> None:
|
||||
self.edit_java()
|
||||
@@ -355,6 +534,165 @@ class TurnEndNudgeTest(RepositoryTestCase):
|
||||
self.bash("ssh buildbox ./gradlew check")
|
||||
self.assertEqual(self.stop()["decision"], "block")
|
||||
|
||||
def blocks_after(self, command: str, response: dict | None = None) -> bool:
|
||||
"""A Java edit, then `command` (with what it printed): does the turn end still block?"""
|
||||
self.edit_java()
|
||||
self.bash(command, response)
|
||||
reply = self.stop()
|
||||
return reply is not None and reply["decision"] == "block"
|
||||
|
||||
def test_a_verify_sh_gradle_stage_on_the_desktop_clears_the_pending_edits(self) -> None:
|
||||
for command in ("scripts/verify.sh leaf :domain-core",
|
||||
"ssh desktop 'cd ~/wt && scripts/verify.sh app --on here'",
|
||||
"cd /home/me/wt && ./scripts/verify.sh pr --no-cache 2>&1 | tail -3; echo rc=$?",
|
||||
"scripts/verify.sh nightly --on desktop",
|
||||
"scripts/verify.sh leaf :domain-core && scripts/verify.sh docs --on here",
|
||||
"ssh -o BatchMode=yes desktop bash -s <<'EOF'\ncd ~/wt && scripts/verify.sh main --on here\nEOF",
|
||||
"ssh desktop bash -s <<'EOF' && echo done\nscripts/verify.sh pr --on here\nEOF",
|
||||
"ssh desktop bash -s <<< 'scripts/verify.sh pr --on here'",
|
||||
"ssh desktop \"bash -lc 'cd ~/wt && scripts/verify.sh pr --on here'\"",
|
||||
"bash -c 'scripts/verify.sh leaf :domain-core'",
|
||||
"ssh desktop scripts/verify.sh leaf :domain-core --on here",
|
||||
"VERIFY_HOST=buildbox scripts/verify.sh docs && scripts/verify.sh pr",
|
||||
"VERIFY_HOST= scripts/verify.sh pr",
|
||||
"scripts/verify.sh pr --on here --on desktop",
|
||||
"scripts/verify.sh pr --log hooks --include-untracked 2>&1 | tee /tmp/pr.log",
|
||||
"scripts/verify.sh pr \\\n --no-cache",
|
||||
"echo start # it's a note\nscripts/verify.sh pr"):
|
||||
with self.subTest(command=command):
|
||||
self.assertFalse(self.blocks_after(command))
|
||||
|
||||
def test_verify_sh_docs_or_a_run_off_the_desktop_still_blocks(self) -> None:
|
||||
for command in ("scripts/verify.sh docs",
|
||||
"scripts/verify.sh pr --on here",
|
||||
"scripts/verify.sh leaf :domain-core --on buildbox",
|
||||
"VERIFY_HOST=buildbox scripts/verify.sh pr",
|
||||
"ssh buildbox 'cd ~/wt && scripts/verify.sh pr --on here'",
|
||||
"ssh desktop 'cd ~/wt && scripts/verify.sh docs'",
|
||||
"ssh desktop uptime && scripts/verify.sh pr --on here",
|
||||
"grep -n verify.sh docs/work/README.md",
|
||||
"ssh desktop uptime\nscripts/verify.sh pr --on here",
|
||||
"ssh desktop bash -s <<'EOF'\nuptime\nEOF\nscripts/verify.sh pr --on here",
|
||||
"ssh desktop 'VERIFY_HOST=buildbox scripts/verify.sh pr'",
|
||||
"export VERIFY_HOST=buildbox; scripts/verify.sh pr",
|
||||
"scripts/verify.sh pr --on desktop --on here",
|
||||
"scripts/verify.sh pr :domain-core",
|
||||
"scripts/verify.sh leaf --no-cache",
|
||||
"cat scripts/verify.sh",
|
||||
"# scripts/verify.sh pr",
|
||||
"echo 'unclosed && scripts/verify.sh pr",
|
||||
"scripts/verify.sh pr \\\n --on here",
|
||||
"scripts/verify.sh docs && ssh"):
|
||||
with self.subTest(command=command):
|
||||
self.assertTrue(self.blocks_after(command))
|
||||
|
||||
def test_a_here_document_written_as_text_is_not_a_run(self) -> None:
|
||||
for command in ("cat > /tmp/brief.md <<'EOF'\n검증: scripts/verify.sh leaf :domain-core 못 돌림\nEOF",
|
||||
"git commit -F - <<'EOF'\nfix: scripts/verify.sh pr 결과를 적는다\nEOF",
|
||||
"cat <<-EOF > notes.md\n\tscripts/verify.sh pr\n\tEOF\nscripts/verify.sh docs"):
|
||||
with self.subTest(command=command):
|
||||
self.assertTrue(self.blocks_after(command))
|
||||
self.assertFalse(self.blocks_after("bash <<'EOF'\nscripts/verify.sh leaf :domain-core\nEOF"))
|
||||
|
||||
def test_a_here_document_delimiter_may_be_escaped_quoted_with_spaces_or_tab_indented(self) -> None:
|
||||
for command in ("cat > /tmp/b.md <<\\EOF\nscripts/verify.sh pr\nEOF",
|
||||
"cat > /tmp/b.md <<'END NOTE'\nscripts/verify.sh pr\nEND NOTE",
|
||||
"cat > /tmp/b.md <<\"END NOTE\"\nscripts/verify.sh pr\nEND NOTE"):
|
||||
with self.subTest(command=command):
|
||||
self.assertTrue(self.blocks_after(command))
|
||||
# The run after the body is still read: the body ended at its delimiter line.
|
||||
self.assertFalse(self.blocks_after("cat <<-EOF > n.md\n\tx\n\tEOF\nscripts/verify.sh pr"))
|
||||
|
||||
def test_quotes_and_comments_are_read_as_the_shell_reads_them(self) -> None:
|
||||
for command in ('echo "a\\" #b"; scripts/verify.sh pr', "echo a#b && scripts/verify.sh pr"):
|
||||
with self.subTest(command=command):
|
||||
self.assertFalse(self.blocks_after(command))
|
||||
self.assertTrue(self.blocks_after('echo "\\"" # ; scripts/verify.sh pr'))
|
||||
|
||||
def test_only_the_word_a_command_runs_counts(self) -> None:
|
||||
for command in ("timeout -k 10 3600 scripts/verify.sh pr",
|
||||
"env VERIFY_HOST=desktop nohup scripts/verify.sh pr",
|
||||
"bash -x scripts/verify.sh leaf :domain-core",
|
||||
"ssh desktop 'cd ~/w && timeout 600 flock -w 600 /tmp/claude-gates/heavy.lock ./gradlew check'",
|
||||
"ssh desktop bash <<'EOF'\ncd ~/w && sh ./gradlew check\nEOF",
|
||||
# ssh sends its remote words, not the redirections the laptop shell applies to ssh.
|
||||
"ssh desktop 'cd ~/wt && scripts/verify.sh pr --on here' > /tmp/pr.log 2>&1",
|
||||
"bash -o pipefail -c 'scripts/verify.sh pr | tail -3'",
|
||||
"bash -- scripts/verify.sh pr",
|
||||
"bash -s x <<'EOF'\nscripts/verify.sh leaf :domain-core\nEOF"):
|
||||
with self.subTest(command=command):
|
||||
self.assertFalse(self.blocks_after(command))
|
||||
for command in ("echo scripts/verify.sh pr",
|
||||
"bash -n scripts/verify.sh pr",
|
||||
"printf '%s\\n' scripts/verify.sh leaf :domain-core",
|
||||
"grep -c bash <<'EOF'\nscripts/verify.sh pr\nEOF",
|
||||
"cat > /tmp/x/sh <<'EOF'\nscripts/verify.sh pr\nEOF",
|
||||
"ssh desktop 'grep -n gradlew ~/w/README.md'",
|
||||
"git commit -F - <<'EOF'\n검증: ssh desktop ./gradlew check 못 돌림\nEOF",
|
||||
"ssh desktop uptime\n./gradlew check",
|
||||
"# ssh desktop ./gradlew check\nls",
|
||||
"./gradlew check",
|
||||
# A shell given a script file reads the here-document as that script's input.
|
||||
"bash scripts/notes.sh <<'EOF'\nscripts/verify.sh pr\nEOF",
|
||||
# A script a laptop shell runs is on the laptop, so `--on here` is the laptop.
|
||||
"bash -c 'scripts/verify.sh pr --on here'",
|
||||
"bash <<'EOF'\nscripts/verify.sh pr --on here\nEOF"):
|
||||
with self.subTest(command=command):
|
||||
self.assertTrue(self.blocks_after(command))
|
||||
|
||||
def test_scripts_nested_past_the_limit_are_not_read_and_do_not_fail_the_hook(self) -> None:
|
||||
within = "ssh desktop " * hooks.MAX_NESTING + "./gradlew check"
|
||||
self.assertFalse(self.blocks_after(within))
|
||||
code, _, _ = run_event("post-bash", {"session_id": "s1", "cwd": str(self.repo.root), "tool_name": "Bash",
|
||||
"tool_input": {"command": "ssh desktop " * 2000 + "./gradlew check"}})
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(self.blocks_after("ssh desktop " * (hooks.MAX_NESTING + 2) + "./gradlew check"))
|
||||
|
||||
def test_a_leaf_target_outside_the_registry_stops_before_gradle(self) -> None:
|
||||
self.assertTrue(self.blocks_after("scripts/verify.sh leaf src/domain/core 2>&1 | tail -5"))
|
||||
# Without a readable registry the target is not checked (N1 reads it on the Java edit, so break it after).
|
||||
self.edit_java()
|
||||
(self.repo.root / hooks.REGISTRY).write_text("{", encoding="utf-8")
|
||||
self.bash("scripts/verify.sh leaf :elsewhere")
|
||||
self.assertIsNone(self.stop())
|
||||
|
||||
def test_a_run_verify_sh_refused_to_send_does_not_count(self) -> None:
|
||||
refusal = (REPO / "scripts/verify.sh").read_text(encoding="utf-8")
|
||||
self.assertIn(f'echo "{hooks.VERIFY_REFUSED}.', refusal)
|
||||
message = f"{hooks.VERIFY_REFUSED}. 보낼 것이면 git add 하거나 --include-untracked를 주고,\n .codex/\n"
|
||||
for response in ({"stdout": message, "stderr": ""}, {"stdout": "", "stderr": message}):
|
||||
with self.subTest(response=response):
|
||||
self.assertTrue(self.blocks_after("scripts/verify.sh pr 2>&1 | tail -3", response))
|
||||
# The same run with Gradle output counts; a refusal does not hide a desktop gradlew in the same command.
|
||||
self.assertFalse(self.blocks_after("scripts/verify.sh pr | tail -3", {"stdout": "BUILD SUCCESSFUL"}))
|
||||
self.assertFalse(self.blocks_after("scripts/verify.sh pr; ssh desktop 'cd ~/w && ./gradlew check'",
|
||||
{"stderr": message}))
|
||||
|
||||
def test_verify_host_in_the_environment_moves_the_default_host(self) -> None:
|
||||
os.environ["VERIFY_HOST"] = "buildbox"
|
||||
self.assertTrue(self.blocks_after("scripts/verify.sh pr"))
|
||||
self.assertFalse(self.blocks_after("scripts/verify.sh pr --on desktop"))
|
||||
# The remote shell does not have the laptop's environment.
|
||||
self.assertFalse(self.blocks_after("ssh desktop 'cd ~/wt && scripts/verify.sh pr'"))
|
||||
|
||||
def test_the_options_are_the_ones_verify_sh_reads(self) -> None:
|
||||
script = (REPO / "scripts/verify.sh").read_text(encoding="utf-8")
|
||||
body = script[script.index("\nmain() {"):]
|
||||
options = re.findall(r"^\s*(--[a-z-]+)\)(.*)$", body, re.M)
|
||||
self.assertEqual(sorted(name for name, rest in options if "shift 2" in rest), sorted(hooks.VERIFY_VALUE_OPTIONS))
|
||||
self.assertEqual(sorted(name for name, rest in options if "shift 2" not in rest), sorted(hooks.VERIFY_FLAGS))
|
||||
|
||||
def test_the_gradle_stages_are_the_ones_verify_sh_runs_with_gradle(self) -> None:
|
||||
script = (REPO / "scripts/verify.sh").read_text(encoding="utf-8")
|
||||
heavy = re.search(r"^\s*docs\) run_docs ;;\n\s*([a-z| ]+)\)", script, re.M)
|
||||
self.assertIsNotNone(heavy, "scripts/verify.sh run_here의 단계 목록을 찾지 못했다")
|
||||
self.assertEqual(sorted(stage.strip() for stage in heavy.group(1).split("|")),
|
||||
sorted(hooks.VERIFY_HEAVY_STAGES))
|
||||
|
||||
def test_the_reason_points_at_the_verify_entry_point(self) -> None:
|
||||
self.edit_java()
|
||||
self.assertIn("`scripts/verify.sh leaf <gradle-path>`", self.stop()["reason"])
|
||||
|
||||
def test_a_new_java_edit_after_the_reminder_reminds_again(self) -> None:
|
||||
self.edit_java()
|
||||
self.stop()
|
||||
|
||||
Reference in New Issue
Block a user