chore(merge): main을 받은 정리 3단계 브랜치를 받는다
PR #16은 PR #14(chore/layout-3-merge) 위에 쌓았다. #14가 하네스 PR #13이
들어간 main을 합친 커밋(568f3328)을 받는다. 충돌은 없었다.
This commit is contained in:
Executable
+358
@@ -0,0 +1,358 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when the work manual stops being readable without history or grows past its size limits.
|
||||
|
||||
The work manual is the root `AGENTS.md` (the map and the rules that must hold) plus `docs/work/`. A
|
||||
Claude Code session reads the map through the root `CLAUDE.md`, which imports it (`@AGENTS.md`) and
|
||||
adds a few Claude-only lines. A session that has never seen this repository's history reads the map,
|
||||
`docs/work/README.md` and one playbook, and must be able to finish the job from those alone. Two
|
||||
things break that, and both are mechanical:
|
||||
|
||||
1. History IDs in the body. A sentence such as "fixed as in 1103/11-07" means nothing to a reader
|
||||
who does not know that review. History belongs in `docs/work/evidence.md` and the two reference
|
||||
files that are indexes of history (`reference/decisions.md`, `reference/defect-patterns.md`). The
|
||||
same rule covers the other files a new session reads first: the root `AGENTS.md` and `CLAUDE.md`,
|
||||
every folder rule book `src/**/AGENTS.md` and the documents under `.claude/` (rules, skills,
|
||||
subagents). Review documents keep their IDs.
|
||||
2. Length. Each entry file has a line limit and the entry path (map + root `CLAUDE.md` + README +
|
||||
one playbook) has a total limit, so a session reads the whole path instead of skimming it. The
|
||||
map limit is 40 lines (owner decision 2026-11-07: the root holds the rules, the map and the
|
||||
router only).
|
||||
|
||||
It also checks that every playbook keeps the shared nine-section skeleton, that the "common
|
||||
mistakes" section stays short, that `CLAUDE.md` starts with the import, that every folder rule book
|
||||
`src/**/AGENTS.md` has a `CLAUDE.md` beside it that only imports it (so Claude Code reads the same
|
||||
book) and stays under 200 lines, and that relative links in the checked files resolve. The same layout and limits as the paired backend template's checker.
|
||||
|
||||
Standard library only, so it runs on the laptop and in the edit hook (scripts/hooks/hooks.py, N2).
|
||||
`verify:documentation` (FE-GATE-017) checks the paths, scripts and gate IDs these documents name.
|
||||
|
||||
python3 scripts/check-work-docs.py
|
||||
python3 scripts/check-work-docs.py --links docs README.md # relative links only, any files
|
||||
python3 scripts/check-work-docs.py --history docs/manual # history IDs only, any files
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
MAP = REPO_ROOT / "AGENTS.md"
|
||||
CLAUDE_ENTRY = REPO_ROOT / "CLAUDE.md"
|
||||
IMPORT_LINE = "@AGENTS.md"
|
||||
CLAUDE_FOLDERS = ("rules", "skills", "agents")
|
||||
WORK = REPO_ROOT / "docs/work"
|
||||
README = WORK / "README.md"
|
||||
|
||||
PLAYBOOKS = [
|
||||
"new-feature.md",
|
||||
"improve.md",
|
||||
"research-design.md",
|
||||
"docs-writing.md",
|
||||
"operate.md",
|
||||
"delegate.md",
|
||||
]
|
||||
REFERENCES = [
|
||||
"reference/gates.md",
|
||||
"reference/review-criteria.md",
|
||||
"reference/structure.md",
|
||||
"reference/testing.md",
|
||||
"reference/performance.md",
|
||||
"reference/defect-patterns.md",
|
||||
"reference/decisions.md",
|
||||
]
|
||||
EVIDENCE = "evidence.md"
|
||||
|
||||
# Files that may name history, relative to docs/work/. Everything else must not.
|
||||
HISTORY_ALLOWED = {EVIDENCE, "reference/decisions.md", "reference/defect-patterns.md"}
|
||||
|
||||
MAP_LIMIT = 40
|
||||
CLAUDE_ENTRY_LIMIT = 15
|
||||
README_LIMIT = 80
|
||||
PLAYBOOK_LIMIT = 150
|
||||
ENTRY_PATH_LIMIT = 350
|
||||
MISTAKES_LIMIT = 10
|
||||
# A folder rule book is read whole whenever a file in that folder is opened (Claude Code: under 200).
|
||||
MODULE_GUIDE_LIMIT = 200
|
||||
SKIPPED_PARTS = {"node_modules", ".generated", "dist"}
|
||||
|
||||
SKELETON = [
|
||||
"1. 언제 쓰나",
|
||||
"2. 받아야 할 것",
|
||||
"3. 크기와 사고 순서",
|
||||
"4. 절차",
|
||||
"5. 완료 기준",
|
||||
"6. 하지 말 것",
|
||||
"7. 막혔을 때",
|
||||
"8. 보고 형식",
|
||||
"9. 자주 하는 실수",
|
||||
]
|
||||
|
||||
# Each pattern names a kind of history identifier. A match is a sentence that only a reader who
|
||||
# knows the past can follow. re.ASCII keeps \b and \w to ASCII: Python counts Korean letters as
|
||||
# word characters, so "1105/12-01과" would otherwise slip through.
|
||||
HISTORY_PATTERNS = [
|
||||
("review ID with a date prefix (MMDD/NN-MM)",
|
||||
re.compile(r"(?<![\w./-])(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])/[\w-]", re.ASCII)),
|
||||
("review README named by its date (1105 README)",
|
||||
re.compile(r"(?<![\w./-])(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01]) (?:README|조치|리뷰)", re.ASCII)),
|
||||
("review round folder name (round6)", re.compile(r"\bround\d+\b", re.ASCII)),
|
||||
# A finding number written after the word for review or round: "리뷰 02-01", "review 12-03".
|
||||
("finding number after a review or round word (리뷰 02-01)",
|
||||
re.compile(r"(?:리뷰|라운드|(?<![A-Za-z])[Rr]eview)[^|()\n]{0,20}?(?<![\w./-])\d{2}-\d{2}(?![\w-])",
|
||||
re.ASCII)),
|
||||
# Finding numbers listed with no word in front: "(05-01, 04-01)". One bare NN-NN stays allowed,
|
||||
# because a lone pair is often an ordinary range or chapter number.
|
||||
("list of finding numbers (05-01, 04-01)",
|
||||
re.compile(r"(?<![\w./:,-])\d{2}-\d{2}(?:, |·)\d{2}-\d{2}(?![\w-])", re.ASCII)),
|
||||
# A count of rounds ("3라운드마다") is not a name for one past round.
|
||||
("round number in Korean (4라운드, 라운드6)",
|
||||
re.compile(r"(?<![\w.~-])\d{1,2} ?라운드(?! ?(?:동안|마다|씩|간))|라운드 ?\d{1,2}(?![\w.])", re.ASCII)),
|
||||
("review README section number (리뷰 README 13절)", re.compile(r"리뷰 README \d", re.ASCII)),
|
||||
# A decision named by its date ("owner decision 2026-11-06") is content plus a date, not a number.
|
||||
("decision named by number only",
|
||||
re.compile(r"결정 ?(?!\d{4}-)(?:\d+|[①-⑳])(?!\s*(?:개|건|가지|번째))"
|
||||
r"|(?<![A-Za-z])[Dd]ecision (?!\d{4}-)\d+", re.ASCII)),
|
||||
# The improvement manual's own numbers: decisions M-3, owner orders O-12, round defaults D-14, and
|
||||
# the defect pattern catalogue P-43.
|
||||
("old manual number (M-3, O-12, D-14, P-43)", re.compile(r"\b[MODP]-\d{1,2}\b", re.ASCII)),
|
||||
("design decision number (D5)", re.compile(r"\bD\d{1,2}\b", re.ASCII)),
|
||||
("finding number with its chosen option (03-11 (b))",
|
||||
re.compile(r"(?<![\w./:-])\d{2}-\d{2} \([a-e]\)", re.ASCII)),
|
||||
("commit sha", re.compile(r"\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b", re.ASCII)),
|
||||
]
|
||||
|
||||
LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)", re.ASCII)
|
||||
|
||||
|
||||
def rel(path: Path) -> str:
|
||||
return path.relative_to(REPO_ROOT).as_posix()
|
||||
|
||||
|
||||
def line_count(path: Path) -> int:
|
||||
return len(path.read_text(encoding="utf-8").splitlines())
|
||||
|
||||
|
||||
def check_exists(errors: list[str]) -> bool:
|
||||
expected = [MAP, CLAUDE_ENTRY, README, WORK / EVIDENCE]
|
||||
expected += [WORK / name for name in PLAYBOOKS + REFERENCES]
|
||||
missing = [rel(path) for path in expected if not path.is_file()]
|
||||
for name in missing:
|
||||
errors.append(f"{name}: missing")
|
||||
return not missing
|
||||
|
||||
|
||||
def check_limits(errors: list[str], report: list[str]) -> None:
|
||||
for path, limit in [(MAP, MAP_LIMIT), (CLAUDE_ENTRY, CLAUDE_ENTRY_LIMIT), (README, README_LIMIT)]:
|
||||
lines = line_count(path)
|
||||
report.append(f"{rel(path)}: {lines}/{limit}")
|
||||
if lines > limit:
|
||||
errors.append(f"{rel(path)}: {lines} lines, limit {limit}")
|
||||
base = line_count(MAP) + line_count(CLAUDE_ENTRY) + line_count(README)
|
||||
for name in PLAYBOOKS:
|
||||
path = WORK / name
|
||||
lines = line_count(path)
|
||||
entry = base + lines
|
||||
report.append(f"{rel(path)}: {lines}/{PLAYBOOK_LIMIT}, entry path {entry}/{ENTRY_PATH_LIMIT}")
|
||||
if lines > PLAYBOOK_LIMIT:
|
||||
errors.append(f"{rel(path)}: {lines} lines, limit {PLAYBOOK_LIMIT}")
|
||||
if entry > ENTRY_PATH_LIMIT:
|
||||
errors.append(
|
||||
f"{rel(path)}: entry path AGENTS.md + CLAUDE.md + docs/work/README.md + this file is {entry} lines,"
|
||||
f" limit {ENTRY_PATH_LIMIT}"
|
||||
)
|
||||
|
||||
|
||||
def outside_code_blocks(lines: list[str]) -> list[str]:
|
||||
"""Blank out fenced code blocks, so an example such as a report template is not a section."""
|
||||
kept: list[str] = []
|
||||
fenced = False
|
||||
for line in lines:
|
||||
if line.lstrip().startswith("```"):
|
||||
fenced = not fenced
|
||||
kept.append("")
|
||||
else:
|
||||
kept.append("" if fenced else line)
|
||||
return kept
|
||||
|
||||
|
||||
def check_skeleton(errors: list[str]) -> None:
|
||||
for name in PLAYBOOKS:
|
||||
path = WORK / name
|
||||
lines = outside_code_blocks(path.read_text(encoding="utf-8").splitlines())
|
||||
headings = [line[3:].strip() for line in lines if line.startswith("## ")]
|
||||
if headings != SKELETON:
|
||||
errors.append(f"{rel(path)}: sections must be exactly {SKELETON} in that order, found {headings}")
|
||||
continue
|
||||
start = lines.index("## " + SKELETON[-1])
|
||||
items = [line for line in lines[start + 1:] if re.match(r"^(?:[-*]|\d+\.) ", line)]
|
||||
if len(items) > MISTAKES_LIMIT:
|
||||
errors.append(
|
||||
f"{rel(path)}: '{SKELETON[-1]}' has {len(items)} items, limit {MISTAKES_LIMIT}"
|
||||
" (move one to a reference file or delete one)"
|
||||
)
|
||||
|
||||
|
||||
def check_claude_entry(errors: list[str]) -> None:
|
||||
"""The root CLAUDE.md starts with the import, so a Claude Code session reads the map."""
|
||||
lines = CLAUDE_ENTRY.read_text(encoding="utf-8").splitlines()
|
||||
if not lines or lines[0].strip() != IMPORT_LINE:
|
||||
errors.append(f"{rel(CLAUDE_ENTRY)}: the first line must be '{IMPORT_LINE}'")
|
||||
|
||||
|
||||
def module_guides() -> list[Path]:
|
||||
"""Every src/**/AGENTS.md, the local rule book of a layer folder."""
|
||||
return sorted(path for path in (REPO_ROOT / "src").rglob("AGENTS.md")
|
||||
if not SKIPPED_PARTS.intersection(path.relative_to(REPO_ROOT).parts))
|
||||
|
||||
|
||||
def check_guides(errors: list[str], report: list[str]) -> None:
|
||||
longest = 0
|
||||
for guide in module_guides():
|
||||
lines = line_count(guide)
|
||||
longest = max(longest, lines)
|
||||
if lines > MODULE_GUIDE_LIMIT:
|
||||
errors.append(f"{rel(guide)}: {lines} lines, limit {MODULE_GUIDE_LIMIT}")
|
||||
if not guide.with_name("CLAUDE.md").is_file():
|
||||
errors.append(f"{rel(guide.with_name('CLAUDE.md'))}: missing; it must be the one line '{IMPORT_LINE}'")
|
||||
for entry in sorted(path for path in (REPO_ROOT / "src").rglob("CLAUDE.md")
|
||||
if not SKIPPED_PARTS.intersection(path.relative_to(REPO_ROOT).parts)):
|
||||
lines = [line.strip() for line in entry.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
if lines != [IMPORT_LINE]:
|
||||
errors.append(f"{rel(entry)}: must be exactly '{IMPORT_LINE}'; the rules live in AGENTS.md beside it")
|
||||
if not entry.with_name("AGENTS.md").is_file():
|
||||
errors.append(f"{rel(entry)}: imports {rel(entry.with_name('AGENTS.md'))}, which does not exist")
|
||||
report.append(f"src/**/AGENTS.md: {len(module_guides())} files, longest {longest}/{MODULE_GUIDE_LIMIT}")
|
||||
|
||||
|
||||
def claude_documents() -> list[Path]:
|
||||
"""The tracked Claude Code documents a session reads: path rules, skills, subagent definitions.
|
||||
Only these folders: the rest of .claude/ is local state (worktrees, hook state, settings.local.json)."""
|
||||
return sorted(path for folder in CLAUDE_FOLDERS for path in (REPO_ROOT / ".claude" / folder).rglob("*.md"))
|
||||
|
||||
|
||||
def history_checked_files() -> list[Path]:
|
||||
files = [MAP, CLAUDE_ENTRY] + claude_documents() + module_guides()
|
||||
for path in sorted(WORK.rglob("*.md")):
|
||||
if path.relative_to(WORK).as_posix() not in HISTORY_ALLOWED:
|
||||
files.append(path)
|
||||
return files
|
||||
|
||||
|
||||
def history_match(line: str, following: str) -> tuple[str, str] | None:
|
||||
"""The first history ID on this line, or one that a line break splits ("review\n1103/11-07")."""
|
||||
for label, pattern in HISTORY_PATTERNS:
|
||||
match = pattern.search(line)
|
||||
if match:
|
||||
return label, match.group(0)
|
||||
if not following.strip():
|
||||
return None
|
||||
joined = line.rstrip() + " " + following.strip()
|
||||
for label, pattern in HISTORY_PATTERNS:
|
||||
for match in pattern.finditer(joined):
|
||||
if match.start() < len(line.rstrip()) < match.end():
|
||||
return label, match.group(0)
|
||||
return None
|
||||
|
||||
|
||||
def history_hits(files: list[Path]) -> list[tuple[Path, int, str, str]]:
|
||||
hits = []
|
||||
for path in files:
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
for number, line in enumerate(lines, start=1):
|
||||
found = history_match(line, lines[number] if number < len(lines) else "")
|
||||
if found:
|
||||
hits.append((path, number, *found))
|
||||
return hits
|
||||
|
||||
|
||||
def broken_links(files: list[Path]) -> tuple[int, list[tuple[Path, int, str]]]:
|
||||
checked = 0
|
||||
broken = []
|
||||
for path in files:
|
||||
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
for target in LINK.findall(line):
|
||||
if re.match(r"^[a-z][a-z0-9+.-]*:", target) or target.startswith("#"):
|
||||
continue
|
||||
checked += 1
|
||||
if not (path.parent / target.split("#", 1)[0]).exists():
|
||||
broken.append((path, number, target))
|
||||
return checked, broken
|
||||
|
||||
|
||||
def check_history(errors: list[str], report: list[str]) -> None:
|
||||
hits = history_hits(history_checked_files())
|
||||
for path, number, label, text in hits:
|
||||
errors.append(
|
||||
f"{rel(path)}:{number}: {label} '{text}'"
|
||||
" - write the content instead, and move the ID to docs/work/evidence.md"
|
||||
)
|
||||
report.append(f"history ID lines in checked files: {len(hits)}")
|
||||
|
||||
|
||||
def check_links(errors: list[str], report: list[str]) -> None:
|
||||
checked, broken = broken_links([MAP, CLAUDE_ENTRY] + sorted(WORK.rglob("*.md")) + claude_documents()
|
||||
+ module_guides())
|
||||
for path, number, target in broken:
|
||||
errors.append(f"{rel(path)}:{number}: broken relative link '{target}'")
|
||||
report.append(f"relative links checked: {checked}")
|
||||
|
||||
|
||||
def markdown_files(targets: list[str]) -> list[Path]:
|
||||
files: list[Path] = []
|
||||
for target in targets:
|
||||
path = (Path.cwd() / target).resolve()
|
||||
files += sorted(path.rglob("*.md")) if path.is_dir() else [path]
|
||||
return files
|
||||
|
||||
|
||||
def links_only(targets: list[str]) -> int:
|
||||
files = markdown_files(targets)
|
||||
checked, broken = broken_links(files)
|
||||
print(f"files: {len(files)}, relative links checked: {checked}, broken: {len(broken)}")
|
||||
for path, number, target in broken:
|
||||
print(f" {path}:{number}: broken relative link '{target}'", file=sys.stderr)
|
||||
return 1 if broken else 0
|
||||
|
||||
|
||||
def history_only(targets: list[str]) -> int:
|
||||
files = markdown_files(targets)
|
||||
hits = history_hits(files)
|
||||
print(f"files: {len(files)}, lines with history IDs: {len(hits)}")
|
||||
for path, number, label, text in hits:
|
||||
print(f" {path}:{number}: {label} '{text}'", file=sys.stderr)
|
||||
return 1 if hits else 0
|
||||
|
||||
|
||||
MODES = {"--links": links_only, "--history": history_only}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if sys.argv[1:2] and sys.argv[1] in MODES:
|
||||
if len(sys.argv) < 3:
|
||||
print(f"usage: check-work-docs.py {sys.argv[1]} <file or directory>...", file=sys.stderr)
|
||||
return 2
|
||||
return MODES[sys.argv[1]](sys.argv[2:])
|
||||
errors: list[str] = []
|
||||
report: list[str] = []
|
||||
if check_exists(errors):
|
||||
check_limits(errors, report)
|
||||
check_claude_entry(errors)
|
||||
check_guides(errors, report)
|
||||
check_skeleton(errors)
|
||||
check_history(errors, report)
|
||||
check_links(errors, report)
|
||||
for line in report:
|
||||
print(line)
|
||||
if errors:
|
||||
print(f"\nFAILED: {len(errors)} problem(s)", file=sys.stderr)
|
||||
for error in errors:
|
||||
print(f" {error}", file=sys.stderr)
|
||||
return 1
|
||||
print("\nOK")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,46 @@
|
||||
# repo 훅
|
||||
|
||||
Claude Code가 정해진 때에 대신 실행하는 명령이다. 연결은 `.claude/settings.json`, 본체는 `hooks.py` 하나, 시험은 `scripts/tests/test_hooks.py`다. 모델이 잊어도 돈다.
|
||||
|
||||
```text
|
||||
Edit·Write 직후 ──> post-edit ──> src TypeScript면 N3 경계 알림, 테스트·기준 파일이면 N6 게이트 기준 알림, 문서면 N2 문서 검사 알림
|
||||
Bash 직후 ──> post-bash ──> desktop에서 pnpm·게이트를 돌렸으면 N5 기록을 비운다
|
||||
턴 끝 ──> stop ──> N5 desktop이 확인해야 할 파일을 고쳤는데 desktop 실행이 없으면 한 번 알린다
|
||||
```
|
||||
|
||||
## 1. 원칙
|
||||
|
||||
- 막지 않는다. 모두 알리기만 한다(넛지). 알림은 종료 코드 0이고, 모델 컨텍스트에 몇 줄(최대 5줄)만 더한다. 이 repo 안에서 편집 하나가 되돌릴 수 없는 일을 하지 않아서, 편집 전 차단 훅은 없다. 되돌릴 수 없는 명령 차단(force push, 범위 밖 `rm -rf`, DB·볼륨 삭제)과 비밀 값 알림은 repo가 아니라 소유자 전역 훅과 하네스 플러그인 `harness@claude-harness` 몫이다.
|
||||
- 훅은 게이트의 일부만 본다. 정본은 게이트(desktop `check:architecture`, `lint`, `check:types`, `verify:documentation`)다. 훅이 틀리면 훅을 고치거나 끄고, 게이트는 그대로 둔다.
|
||||
- 노트북에서 pnpm·node·eslint·브라우저를 돌리지 않는다. 포맷·린트·타입 검사는 desktop의 `scripts/verify.sh`에서 돈다(소유자 결정 2026-11-08, `docs/work/reference/decisions.md`). 그래서 편집 직후 훅은 Python 표준 라이브러리와 git만 쓰는 정적 검사이고, 1초 안에 끝난다.
|
||||
- 받거나 설치하지 않는다. 의존성이 없다.
|
||||
|
||||
## 2. 훅마다
|
||||
|
||||
| ID | 때 | 하는 일 | 결과 |
|
||||
| --- | --- | --- | --- |
|
||||
| N3 | PostToolUse `Edit\|Write\|MultiEdit`, `src/**/*.{ts,tsx}`(`.d.ts` 제외) | 편집한 파일의 import(정적·type-only·re-export·리터럴 dynamic import·require)를 경로로 풀고, `.dependency-cruiser.json`의 `forbidden` 규칙(`from`·`to`의 `path`·`pathNot`, `$1` 치환)에 대 본다. 사이클 규칙은 그래프 전체가 필요해 보지 않는다 | 「꼭 지킬 것 N 의심」 줄(규칙 이름과 import), 정본 게이트 안내 |
|
||||
| N6 | 같은 때, 테스트 파일(`tests/**`, `*.test.*`·`*.spec.*`·`*.stories.*`) | 마지막 커밋(`git show HEAD:<path>`)보다 `.skip`·`.only`·`.fixme`·`.todo`가 늘었는지 센다 | 늘어난 수와 「꼭 지킬 것 4」 |
|
||||
| N6 | 같은 때, 게이트 기준 파일(`config/performance/budgets.json`, `config/scale/`, `config/testing/`, `config/ci/ungated-*.json`, `config/**/*baseline*.json`, `vitest.config.ts`, 스냅숏) | 편집 자체를 알린다 | 「게이트의 기준 파일」 한 줄과 「꼭 지킬 것 4」 |
|
||||
| N2 | 같은 때, `*.md` | `scripts/check-work-docs.py`를 돌린다(작업 매뉴얼의 분량·이력 ID·뼈대·상대 링크) | 실패 줄. 고친 문서를 가리키는 줄이 있으면 그것만 |
|
||||
| N5 | Stop | 이 세션에서 desktop만 확인할 수 있는 파일(아래 밖의 모든 파일)을 고친 뒤 desktop 실행이 없으면 턴을 한 번 막고 이유를 준다 | `decision: block`, 다음 편집 전까지 한 번 |
|
||||
|
||||
- N5가 "desktop 실행"으로 치는 것: `ssh <desktop 호스트> …`로 pnpm·`ci:gate`·`verify.sh`·vitest·playwright·`node scripts/…`를 돌린 명령, 또는 `scripts/verify.sh`를 `docs`·`hooks` 밖 단계로(`--on here` 없이) 돌린 명령.
|
||||
- N5가 세지 않는 파일(노트북에서 확인되는 것): `.claude/`, `scripts/hooks/`, `scripts/tests/`, `scripts/check-work-docs.py`, `docs/ledger/`, `CLAUDE.md`, `src/**/AGENTS.md`·`CLAUDE.md`. 이것들은 `scripts/verify.sh docs`·`hooks`가 노트북에서 본다.
|
||||
- N5가 기억하는 것은 `.claude/hook-state/<session_id>.json`이다(git이 무시한다).
|
||||
- 권한 쪽 차단: `.claude/settings.json`의 `permissions.deny`가 실제 `.env`·`.env.local`·`.env.*.local`·`.env.<mode>` 읽기·쓰기를 막는다. `.env.example`은 막지 않는다.
|
||||
|
||||
## 3. 시험
|
||||
|
||||
```bash
|
||||
scripts/verify.sh hooks
|
||||
```
|
||||
|
||||
- `python3 -m unittest discover -s scripts/tests`와 같다. 노트북에서 돈다.
|
||||
- 고장 낸 입력(배럴 밖 import, kernel 밖 adapter 간 import, 늘어난 `.only`, 깨진 링크)에서 알림이 나오고, 맞는 입력에서 조용한지 본다. N3는 실제 `.dependency-cruiser.json`과 `src/` 전체에서 알림이 0인지도 본다(거짓 양성 시험).
|
||||
- 훅을 고치면 조건을 끈 사본에서도 시험이 실패하는지 본다(변이 시험). 조건 하나를 끄는 것마다 시험 하나 이상이 실패해야 한다.
|
||||
- 이 시험은 아직 CI workflow가 부르지 않는다. 훅·검사기를 고친 PR은 보고에 `scripts/verify.sh hooks` 결과를 적는다.
|
||||
|
||||
## 4. 끄기
|
||||
|
||||
훅이 시끄럽거나 틀리면 `.claude/settings.json`에서 그 항목을 지우고, 이유를 커밋 본문에 쓴다. 개인적으로만 끄려면 `.claude/settings.local.json`(git이 무시한다)에 `"disableAllHooks": true`를 둔다.
|
||||
Executable
+375
@@ -0,0 +1,375 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Claude Code repo hooks: nudge right after an edit, remind at the end of a turn.
|
||||
|
||||
Called by `.claude/settings.json`, one event per invocation, with the hook input JSON on stdin:
|
||||
|
||||
python3 scripts/hooks/hooks.py post-edit # PostToolUse Edit|Write|MultiEdit N3, N6, N2
|
||||
python3 scripts/hooks/hooks.py post-bash # PostToolUse Bash records desktop runs
|
||||
python3 scripts/hooks/hooks.py stop # Stop N5
|
||||
|
||||
What each ID does, and why it nudges instead of blocking, is in scripts/hooks/README.md. A nudge
|
||||
exits 0 and adds at most a few lines to the model's context. No hook blocks an edit: nothing an edit
|
||||
does inside this repository is irreversible, and the commands that are (force push, wide `rm -r`)
|
||||
are the owner's global hook and the harness plugin. No hook runs pnpm, node, eslint or a browser:
|
||||
the owner's laptop never does (docs/work/operate.md 4.1). The format, lint and type checks run on
|
||||
the desktop through scripts/verify.sh. Standard library and git only. The tests are
|
||||
scripts/tests/test_hooks.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
RULES = ".dependency-cruiser.json"
|
||||
STATE_DIR = ".claude/hook-state"
|
||||
EDIT_TOOLS = ("Edit", "Write", "MultiEdit")
|
||||
MAX_LINES = 5
|
||||
|
||||
# --- N3: the import rules check:architecture holds, checked on the imports of one edited source -----------
|
||||
SOURCE = re.compile(r"^src/.+\.(?:ts|tsx|mts|cts)$")
|
||||
# Static imports and re-exports (type-only ones too: the architecture graph counts them), side-effect
|
||||
# imports, dynamic import() with a literal and require() with a literal.
|
||||
SPECIFIER = re.compile(
|
||||
r"""(?:^|[\s;}])(?:import|export)\s+[^'"`;]*?\bfrom\s*['"]([^'"\n]+)['"]"""
|
||||
r"""|(?:^|[\s;])import\s*['"]([^'"\n]+)['"]"""
|
||||
r"""|\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)"""
|
||||
r"""|\brequire\s*\(\s*['"]([^'"\n]+)['"]\s*\)""",
|
||||
re.M | re.S,
|
||||
)
|
||||
RESOLVE_SUFFIXES = ("", ".ts", ".tsx", ".mts", ".js", ".jsx", "/index.ts", "/index.tsx")
|
||||
# Which of AGENTS.md's "꼭 지킬 것" a broken rule is; every other rule is item 3 (the import rules).
|
||||
RULE_ITEMS = {
|
||||
"adapter-groups-are-reached-through-their-barrel": "꼭 지킬 것 1",
|
||||
"adapters-do-not-know-other-concrete-adapters": "꼭 지킬 것 2",
|
||||
}
|
||||
|
||||
# --- N6: gate standards that an edit can lower -------------------------------------------------------------
|
||||
TEST_SOURCE = re.compile(r"(?:^tests/.+|\.(?:test|spec|stories)\.[cm]?[jt]sx?)$")
|
||||
LOWERING = re.compile(r"\b(?:it|test|describe|suite|bench|context)(?:\.\w+)*\.(skip|only|fixme|todo)\b")
|
||||
# Files whose numbers or lists are the gates' standards: budgets, ceilings, baselines, the ungated
|
||||
# allow-lists, coverage thresholds, snapshots and visual goldens.
|
||||
GATE_STANDARDS = (
|
||||
re.compile(r"^config/performance/budgets\.json$"),
|
||||
re.compile(r"^config/scale/.+\.json$"),
|
||||
re.compile(r"^config/testing/.+\.json$"),
|
||||
re.compile(r"^config/ci/ungated-[^/]+\.json$"),
|
||||
re.compile(r"^config/.*baseline[^/]*\.json$"),
|
||||
re.compile(r"^vitest\.config\.ts$"),
|
||||
re.compile(r"(?:^|/)__snapshots__/"),
|
||||
re.compile(r"\.snap$"),
|
||||
)
|
||||
|
||||
# --- N2: the work-manual check a document edit can break ---------------------------------------------------
|
||||
DOC_CHECK = ("scripts/check-work-docs.py",)
|
||||
DOC_TIMEOUT = 20
|
||||
|
||||
# --- N5: an edit that only the desktop can check, until a desktop run --------------------------------------
|
||||
# Laptop-checkable on their own: the hooks and their tests, the work-manual checker, the ledger, Claude
|
||||
# settings, CLAUDE.md and the folder rule books under src/ (scripts/check-work-docs.py checks them). Everything else is checked by gates that need pnpm.
|
||||
LAPTOP_ONLY = (
|
||||
re.compile(r"^\.claude/"),
|
||||
re.compile(r"^scripts/hooks/"),
|
||||
re.compile(r"^scripts/tests/"),
|
||||
re.compile(r"^scripts/check-work-docs\.py$"),
|
||||
re.compile(r"^docs/ledger/"),
|
||||
re.compile(r"^CLAUDE\.md$"),
|
||||
re.compile(r"^src/(?:.+/)?(?:AGENTS|CLAUDE)\.md$"),
|
||||
)
|
||||
DESKTOP_HOST = re.compile(r"desktop")
|
||||
DESKTOP_WORK = re.compile(r"\b(?:pnpm|ci:gate|verify\.sh|vitest|playwright)\b|\bnode\s+scripts/")
|
||||
VERIFY = re.compile(r"(?:^|[\s;&|(])(?:\./)?scripts/verify\.sh\s+(\S+)(.*)")
|
||||
LAPTOP_STAGES = {"docs", "hooks"}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
# plumbing
|
||||
|
||||
|
||||
def project_root(payload: dict) -> Path:
|
||||
root = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd()
|
||||
return Path(root).resolve()
|
||||
|
||||
|
||||
def relative(root: Path, file_path: str | None) -> str | None:
|
||||
if not file_path:
|
||||
return None
|
||||
path = Path(file_path)
|
||||
if not path.is_absolute():
|
||||
path = root / path
|
||||
try:
|
||||
return path.resolve().relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def edited_path(payload: dict) -> str | None:
|
||||
if payload.get("tool_name") not in EDIT_TOOLS:
|
||||
return None
|
||||
return relative(project_root(payload), (payload.get("tool_input") or {}).get("file_path"))
|
||||
|
||||
|
||||
def context(event: str, lines: list[str]) -> str:
|
||||
"""The PostToolUse output that adds lines to the model's context without blocking."""
|
||||
text = "\n".join(lines[:MAX_LINES] + ([f"(… {len(lines) - MAX_LINES}줄 더)"] if len(lines) > MAX_LINES else []))
|
||||
return json.dumps({"hookSpecificOutput": {"hookEventName": event, "additionalContext": text}},
|
||||
ensure_ascii=False)
|
||||
|
||||
|
||||
def state_file(root: Path, session_id: str) -> Path:
|
||||
safe = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "unknown")
|
||||
return root / STATE_DIR / f"{safe}.json"
|
||||
|
||||
|
||||
def load_state(root: Path, session_id: str) -> dict:
|
||||
try:
|
||||
state = json.loads(state_file(root, session_id).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
state = {}
|
||||
state.setdefault("pending", [])
|
||||
state.setdefault("reminded", False)
|
||||
return state
|
||||
|
||||
|
||||
def save_state(root: Path, session_id: str, state: dict) -> None:
|
||||
path = state_file(root, session_id)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
# N3 — imports of one edited source against the forbidden rules of .dependency-cruiser.json
|
||||
|
||||
|
||||
def load_rules(root: Path) -> list[dict]:
|
||||
try:
|
||||
rules = json.loads((root / RULES).read_text(encoding="utf-8")).get("forbidden", [])
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
# The cycle rule needs the whole graph; the gate holds it.
|
||||
return [rule for rule in rules if "path" in (rule.get("to") or {})]
|
||||
|
||||
|
||||
def specifiers(source: str) -> list[str]:
|
||||
found = []
|
||||
for groups in SPECIFIER.findall(source):
|
||||
value = next((group for group in groups if group), None)
|
||||
if value and value not in found:
|
||||
found.append(value)
|
||||
return found
|
||||
|
||||
|
||||
def resolve(root: Path, path: str, specifier: str) -> str:
|
||||
"""A relative specifier as a repository path (the file it names when one exists); a package as itself."""
|
||||
if not specifier.startswith("."):
|
||||
return specifier
|
||||
base = os.path.normpath(os.path.join(os.path.dirname(path), specifier)).replace(os.sep, "/")
|
||||
stem = re.sub(r"\.(?:js|jsx|mjs)$", "", base)
|
||||
for candidate in (base, *(stem + suffix for suffix in RESOLVE_SUFFIXES)):
|
||||
if (root / candidate).is_file():
|
||||
return candidate
|
||||
return base
|
||||
|
||||
|
||||
def broken_rules(rules: list[dict], path: str, target: str) -> list[str]:
|
||||
broken = []
|
||||
for rule in rules:
|
||||
origin, to = rule.get("from") or {}, rule.get("to") or {}
|
||||
match = re.search(origin.get("path", ""), path)
|
||||
if match is None or ("pathNot" in origin and re.search(origin["pathNot"], path)):
|
||||
continue
|
||||
group = re.escape(match.group(1)) if match.re.groups and match.group(1) is not None else ""
|
||||
if not re.search(to["path"].replace("$1", group), target):
|
||||
continue
|
||||
if "pathNot" in to and re.search(to["pathNot"].replace("$1", group), target):
|
||||
continue
|
||||
broken.append(rule["name"])
|
||||
return broken
|
||||
|
||||
|
||||
def boundary_findings(root: Path, path: str, source: str) -> list[str]:
|
||||
if not SOURCE.match(path) or path.endswith(".d.ts"):
|
||||
return []
|
||||
rules = load_rules(root)
|
||||
findings = []
|
||||
for specifier in specifiers(source):
|
||||
target = resolve(root, path, specifier)
|
||||
for name in broken_rules(rules, path, target):
|
||||
findings.append(f"- {RULE_ITEMS.get(name, '꼭 지킬 것 3')} 의심: `{name}` — `{specifier}`(→ `{target}`)")
|
||||
if len(findings) > 2:
|
||||
# One wrong import usually breaks several rules; the first two say what to look at.
|
||||
findings = findings[:2] + [f"- 외 {len(findings) - 2}개"]
|
||||
if findings:
|
||||
findings.insert(0, f"경계 알림(N3) {path}")
|
||||
findings.append("정본은 게이트다: desktop `scripts/verify.sh gate FE-GATE-010`(check:architecture). "
|
||||
"kernel 예외를 늘려 풀지 않는다.")
|
||||
return findings
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
# N6 — skip·only·fixme·todo added to a test, or a gate standard file changed
|
||||
|
||||
|
||||
def committed(root: Path, path: str) -> str:
|
||||
try:
|
||||
result = subprocess.run(["git", "show", f"HEAD:{path}"], cwd=root, capture_output=True, text=True,
|
||||
timeout=5)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return ""
|
||||
return result.stdout if result.returncode == 0 else ""
|
||||
|
||||
|
||||
def lowering_counts(source: str) -> dict[str, int]:
|
||||
counts: dict[str, int] = {}
|
||||
for word in LOWERING.findall(source):
|
||||
counts[word] = counts.get(word, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def standard_findings(root: Path, path: str, source: str) -> list[str]:
|
||||
lines = []
|
||||
if any(pattern.search(path) for pattern in GATE_STANDARDS):
|
||||
lines.append(f"게이트 기준 알림(N6) {path}는 게이트의 기준 파일(예산·기준선·ungated 목록·스냅숏)이다.")
|
||||
elif TEST_SOURCE.search(path):
|
||||
before, after = lowering_counts(committed(root, path)), lowering_counts(source)
|
||||
grown = [f"`.{word}` {before.get(word, 0)}→{count}" for word, count in sorted(after.items())
|
||||
if count > before.get(word, 0)]
|
||||
if grown:
|
||||
lines.append(f"게이트 기준 알림(N6) {path}: 마지막 커밋보다 {', '.join(grown)}.")
|
||||
if lines:
|
||||
lines.append("꼭 지킬 것 4: 기준을 낮춰 통과시키지 않는다. 의도한 변경이면 이유와 결정 출처를 커밋 본문에 적는다.")
|
||||
return lines
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
# N2 — the work-manual check, failures only
|
||||
|
||||
|
||||
def wants_doc_check(path: str | None) -> bool:
|
||||
return bool(path) and path.endswith(".md") and not path.startswith(STATE_DIR + "/")
|
||||
|
||||
|
||||
def doc_findings(root: Path, path: str) -> list[str]:
|
||||
if not (root / DOC_CHECK[0]).is_file():
|
||||
return []
|
||||
try:
|
||||
result = subprocess.run([sys.executable, *DOC_CHECK], cwd=root, capture_output=True, text=True,
|
||||
timeout=DOC_TIMEOUT)
|
||||
except subprocess.TimeoutExpired:
|
||||
return [f"문서 검사 알림(N2): {DOC_CHECK[0]}가 {DOC_TIMEOUT}초 안에 끝나지 않았다"]
|
||||
if result.returncode == 0:
|
||||
return []
|
||||
lines = [line.strip() for line in result.stderr.splitlines() if line.startswith(" ") and line.strip()]
|
||||
mine = [line for line in lines if path in line]
|
||||
return [f"문서 검사 알림(N2) {path} 편집 뒤 실패 줄:", *[f"- {line}" for line in (mine or lines)]]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
# N5 — something only the desktop can check changed, and the desktop has not run since
|
||||
|
||||
|
||||
def needs_desktop(path: str) -> bool:
|
||||
return not any(pattern.search(path) for pattern in LAPTOP_ONLY)
|
||||
|
||||
|
||||
def ran_on_desktop(command: str) -> bool:
|
||||
"""An `ssh <desktop> …` running pnpm or a gate, or scripts/verify.sh with a stage that goes there."""
|
||||
try:
|
||||
words = shlex.split(command)
|
||||
except ValueError:
|
||||
words = command.split()
|
||||
for position, word in enumerate(words):
|
||||
if word.endswith("ssh"):
|
||||
hosts = [w for w in words[position + 1:position + 5] if not w.startswith("-")][:2]
|
||||
if any(DESKTOP_HOST.search(host) for host in hosts) and DESKTOP_WORK.search(command):
|
||||
return True
|
||||
for match in VERIFY.finditer(command):
|
||||
stage, rest = match.group(1), match.group(2)
|
||||
if stage not in LAPTOP_STAGES and not re.search(r"--on\s+here\b", rest):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def turn_end_reason(state: dict) -> str | None:
|
||||
edits = state.get("pending") or []
|
||||
if not edits or state.get("reminded"):
|
||||
return None
|
||||
shown = ", ".join(f"`{edit}`" for edit in edits[:3]) + (f" 외 {len(edits) - 3}개" if len(edits) > 3 else "")
|
||||
return (f"[N5 턴 끝 알림] 이 세션에서 파일 {len(edits)}개를 고쳤고({shown}) 그 뒤 desktop 실행이 없다. "
|
||||
"포맷·린트·타입·테스트·문서 검사는 노트북이 아니라 desktop에서 `scripts/verify.sh gate FE-GATE-0NN`이나 "
|
||||
"`scripts/verify.sh merge`로 한다(docs/work/operate.md 4.1절). 이번 턴에 돌릴 수 없으면 완료를 말하지 말고, "
|
||||
"보고의 확인 줄에 돌리지 못한 것과 이유를 적는다(꼭 지킬 것 5). 이 알림은 다음 편집 전까지 한 번만 나온다.")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------
|
||||
# events
|
||||
|
||||
|
||||
def post_edit(payload: dict) -> int:
|
||||
root = project_root(payload)
|
||||
path = edited_path(payload)
|
||||
if path is None or not (root / path).is_file():
|
||||
return 0
|
||||
try:
|
||||
source = (root / path).read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
source = ""
|
||||
lines = boundary_findings(root, path, source) + standard_findings(root, path, source)
|
||||
if wants_doc_check(path):
|
||||
lines += doc_findings(root, path)
|
||||
if needs_desktop(path):
|
||||
state = load_state(root, payload.get("session_id", ""))
|
||||
if path not in state["pending"]:
|
||||
state["pending"].append(path)
|
||||
state["reminded"] = False
|
||||
save_state(root, payload.get("session_id", ""), state)
|
||||
if lines:
|
||||
print(context("PostToolUse", lines))
|
||||
return 0
|
||||
|
||||
|
||||
def post_bash(payload: dict) -> int:
|
||||
command = (payload.get("tool_input") or {}).get("command", "")
|
||||
if ran_on_desktop(command):
|
||||
root = project_root(payload)
|
||||
state = load_state(root, payload.get("session_id", ""))
|
||||
state["pending"] = []
|
||||
state["reminded"] = False
|
||||
save_state(root, payload.get("session_id", ""), state)
|
||||
return 0
|
||||
|
||||
|
||||
def stop(payload: dict) -> int:
|
||||
if payload.get("stop_hook_active"):
|
||||
return 0
|
||||
root = project_root(payload)
|
||||
state = load_state(root, payload.get("session_id", ""))
|
||||
reason = turn_end_reason(state)
|
||||
if reason:
|
||||
state["reminded"] = True
|
||||
save_state(root, payload.get("session_id", ""), state)
|
||||
print(json.dumps({"decision": "block", "reason": reason}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
EVENTS = {"post-edit": post_edit, "post-bash": post_bash, "stop": stop}
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if len(argv) != 1 or argv[0] not in EVENTS:
|
||||
print(f"usage: hooks.py {{{'|'.join(EVENTS)}}} < hook-input.json", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
payload = json.load(sys.stdin)
|
||||
except ValueError:
|
||||
return 0
|
||||
return EVENTS[argv[0]](payload if isinstance(payload, dict) else {})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -78,6 +78,8 @@ export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([
|
||||
"tests/unit/manual-paired-backend-settings.test.ts",
|
||||
// Reads the marked code blocks of docs/manual.
|
||||
"tests/unit/manual-code-blocks.test.ts",
|
||||
// Reads the README deletable-files table and the docs/README.md index.
|
||||
"tests/unit/template-contract-documents.test.ts",
|
||||
] as const);
|
||||
|
||||
/** The tests a fixture copied from `copyTargets` cannot run. */
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""scripts/check-work-docs.py의 시험. 이 repo의 작업 매뉴얼이 통과하고, 고장 낸 사본이 실패하는지 본다.
|
||||
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parent.parent
|
||||
REPO = SCRIPTS.parent
|
||||
CHECKER = SCRIPTS / "check-work-docs.py"
|
||||
_spec = importlib.util.spec_from_file_location("check_work_docs", CHECKER)
|
||||
check = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(check)
|
||||
|
||||
|
||||
def history(line: str) -> tuple[str, str] | None:
|
||||
return check.history_match(line, "")
|
||||
|
||||
|
||||
class HistoryPatternTest(unittest.TestCase):
|
||||
def test_this_repository_history_ids_are_caught(self) -> None:
|
||||
for line in ("1103/11-07처럼 고쳤다", "1105 README 11.4절", "1103 조치의 고침", "결함 패턴 P-43",
|
||||
"0925 라운드 D-14", "소유자 O-12", "4라운드 리뷰", "결정 D8을 따른다", "리뷰 12-03에서",
|
||||
"(05-01, 04-01)", "커밋 ad3a071f"):
|
||||
with self.subTest(line=line):
|
||||
self.assertIsNotNone(history(line))
|
||||
|
||||
def test_ordinary_sentences_are_not_history(self) -> None:
|
||||
for line in ("FE-GATE-013은 desktop에서 실패한다", "소유자 결정 2026-11-05", "P1과 P0~P3", "M0~M4, E0~E4",
|
||||
"결정 대기로 남긴다", "Node 24.14.0", "결함 패턴 G13", "세 라운드를 더", "3라운드마다",
|
||||
"`MMDD/NN-MM` 꼴", "초기 JS 206,848 B", "a11y·e2e", "9~15분"):
|
||||
with self.subTest(line=line):
|
||||
self.assertIsNone(history(line))
|
||||
|
||||
|
||||
class RepositoryManualTest(unittest.TestCase):
|
||||
def test_the_manual_in_this_repository_passes(self) -> None:
|
||||
result = subprocess.run([sys.executable, str(CHECKER)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
|
||||
class BrokenCopyTest(unittest.TestCase):
|
||||
"""A copy of the manual with one thing broken at a time; the checker in the copy must fail on it."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self._directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._directory.cleanup)
|
||||
self.root = Path(self._directory.name)
|
||||
for path in ("AGENTS.md", "CLAUDE.md", "docs/work", ".claude/rules", ".claude/skills", ".claude/agents"):
|
||||
source = REPO / path
|
||||
target = self.root / path
|
||||
if not source.exists():
|
||||
continue
|
||||
if source.is_dir():
|
||||
shutil.copytree(source, target)
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(source, target)
|
||||
(self.root / "scripts").mkdir()
|
||||
shutil.copy(CHECKER, self.root / "scripts/check-work-docs.py")
|
||||
|
||||
def run_checker(self) -> subprocess.CompletedProcess:
|
||||
return subprocess.run([sys.executable, str(self.root / "scripts/check-work-docs.py")], capture_output=True,
|
||||
text=True, timeout=30)
|
||||
|
||||
def append(self, path: str, text: str) -> None:
|
||||
with (self.root / path).open("a", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
|
||||
def test_the_copy_passes_before_it_is_broken(self) -> None:
|
||||
self.assertEqual(self.run_checker().returncode, 0)
|
||||
|
||||
def test_a_long_map_fails(self) -> None:
|
||||
self.append("AGENTS.md", "\n" * 10)
|
||||
self.assertIn("AGENTS.md: ", self.run_checker().stderr)
|
||||
|
||||
def test_claude_md_must_start_with_the_import(self) -> None:
|
||||
text = (self.root / "CLAUDE.md").read_text(encoding="utf-8")
|
||||
(self.root / "CLAUDE.md").write_text("# CLAUDE.md\n" + text, encoding="utf-8")
|
||||
self.assertIn("the first line must be '@AGENTS.md'", self.run_checker().stderr)
|
||||
|
||||
def test_a_history_id_in_a_playbook_or_rule_fails_but_not_in_the_evidence(self) -> None:
|
||||
self.append("docs/work/evidence.md", "\n1103/11-07\n")
|
||||
self.assertEqual(self.run_checker().returncode, 0)
|
||||
for path in ("docs/work/improve.md", ".claude/rules/tests.md", "docs/work/reference/gates.md"):
|
||||
with self.subTest(path=path):
|
||||
original = (self.root / path).read_text(encoding="utf-8")
|
||||
self.append(path, "\n고친 방법은 1105/12-04와 같다.\n")
|
||||
self.assertIn(f"{path}:", self.run_checker().stderr)
|
||||
(self.root / path).write_text(original, encoding="utf-8")
|
||||
|
||||
def test_a_playbook_without_the_skeleton_fails(self) -> None:
|
||||
path = self.root / "docs/work/operate.md"
|
||||
path.write_text(path.read_text(encoding="utf-8").replace("## 6. 하지 말 것", "## 6. 금지"), encoding="utf-8")
|
||||
self.assertIn("sections must be exactly", self.run_checker().stderr)
|
||||
|
||||
def test_a_broken_relative_link_fails(self) -> None:
|
||||
self.append("docs/work/README.md", "\n[x](missing.md)\n")
|
||||
self.assertIn("broken relative link 'missing.md'", self.run_checker().stderr)
|
||||
|
||||
def test_a_folder_rule_book_needs_its_import_beside_it_and_no_history(self) -> None:
|
||||
guide = self.root / "src/adapters/AGENTS.md"
|
||||
guide.parent.mkdir(parents=True)
|
||||
guide.write_text("# AGENTS.md\n\n- 규칙\n", encoding="utf-8")
|
||||
self.assertIn("src/adapters/CLAUDE.md: missing", self.run_checker().stderr)
|
||||
(self.root / "src/adapters/CLAUDE.md").write_text("@AGENTS.md\n", encoding="utf-8")
|
||||
self.assertEqual(self.run_checker().returncode, 0)
|
||||
(self.root / "src/adapters/CLAUDE.md").write_text("@AGENTS.md\n- 둘째 규칙\n", encoding="utf-8")
|
||||
self.assertIn("must be exactly '@AGENTS.md'", self.run_checker().stderr)
|
||||
(self.root / "src/adapters/CLAUDE.md").write_text("@AGENTS.md\n", encoding="utf-8")
|
||||
guide.write_text("# AGENTS.md\n\n- 1105/12-04처럼 고친다\n", encoding="utf-8")
|
||||
self.assertIn("src/adapters/AGENTS.md:3:", self.run_checker().stderr)
|
||||
|
||||
def test_a_missing_reference_fails(self) -> None:
|
||||
(self.root / "docs/work/reference/testing.md").unlink()
|
||||
self.assertIn("docs/work/reference/testing.md: missing", self.run_checker().stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""루트 지침과 `.claude/`의 규칙·스킬·서브에이전트가 소유자 결정(2026-11-07)대로인지 본다.
|
||||
|
||||
결과만 받는 일은 서브에이전트, 파일을 바꾸는 위임은 하위 세션이다(docs/work/delegate.md 4.3절).
|
||||
새 스킬은 모두 모델이 부를 수 있고, 설명에 발동 조건을 문단으로 적는다.
|
||||
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent.parent
|
||||
CLAUDE = REPO / ".claude"
|
||||
# Claude Code cuts a skill description at this many characters in the listing.
|
||||
DESCRIPTION_LIMIT = 1536
|
||||
WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"}
|
||||
|
||||
|
||||
def front_matter(path: Path) -> tuple[dict[str, str], list[str]]:
|
||||
"""The scalar fields and the list items of a document's YAML front matter."""
|
||||
match = re.match(r"^---\n(.*?)\n---\n", path.read_text(encoding="utf-8"), re.S)
|
||||
if not match:
|
||||
return {}, []
|
||||
fields, items = {}, []
|
||||
for line in match.group(1).splitlines():
|
||||
if line.lstrip().startswith("- "):
|
||||
items.append(line.strip()[2:].strip('"'))
|
||||
continue
|
||||
key, _, value = line.partition(":")
|
||||
fields[key.strip()] = value.strip()
|
||||
return fields, items
|
||||
|
||||
|
||||
class RootInstructionsTest(unittest.TestCase):
|
||||
def test_claude_md_imports_the_map_and_says_how_to_install_the_plugin_non_interactively(self) -> None:
|
||||
text = (REPO / "CLAUDE.md").read_text(encoding="utf-8")
|
||||
self.assertEqual(text.splitlines()[0], "@AGENTS.md")
|
||||
for command in ("claude plugin marketplace add https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness.git"
|
||||
" --scope project", "claude plugin install harness@claude-harness --scope project"):
|
||||
self.assertIn(command, text)
|
||||
|
||||
def test_the_map_holds_the_five_rules_the_router_and_the_entry_point(self) -> None:
|
||||
text = (REPO / "AGENTS.md").read_text(encoding="utf-8")
|
||||
self.assertEqual(len(re.findall(r"^[1-5]\. ", text.split("## 지도")[0], re.M)), 5)
|
||||
for fragment in ("docs/work/README.md", "scripts/verify.sh", "config/ci/gates.json", ".dependency-cruiser.json",
|
||||
"하위 세션", "서브에이전트"):
|
||||
self.assertIn(fragment, text)
|
||||
|
||||
def test_the_review_criteria_left_the_session_instructions(self) -> None:
|
||||
for path in ("AGENTS.md", "CLAUDE.md"):
|
||||
text = (REPO / path).read_text(encoding="utf-8")
|
||||
self.assertNotIn("28개 관점", text, path)
|
||||
self.assertNotIn("서브에이전트를 병렬로", text, path)
|
||||
|
||||
|
||||
class LayerGuideTest(unittest.TestCase):
|
||||
"""Every top-level src/ folder has its rule book, readable by any agent, and Claude Code imports it."""
|
||||
|
||||
def test_every_layer_folder_has_a_rule_book_and_the_import_beside_it(self) -> None:
|
||||
folders = sorted(path for path in (REPO / "src").iterdir() if path.is_dir() and not path.name.startswith("."))
|
||||
self.assertTrue(folders)
|
||||
for folder in folders:
|
||||
guide = folder / "AGENTS.md"
|
||||
self.assertTrue(guide.is_file(), f"{folder.name}: no AGENTS.md")
|
||||
self.assertTrue(guide.read_text(encoding="utf-8").startswith(f"# AGENTS.md — `src/{folder.name}`"))
|
||||
self.assertEqual((folder / "CLAUDE.md").read_text(encoding="utf-8"), "@AGENTS.md\n", folder.name)
|
||||
|
||||
def test_path_rules_point_at_the_folder_books_instead_of_copying_them(self) -> None:
|
||||
for rule, book in (("adapters", "src/adapters/AGENTS.md"), ("features", "src/features/AGENTS.md")):
|
||||
self.assertIn(f"`{book}`", (CLAUDE / "rules" / f"{rule}.md").read_text(encoding="utf-8"))
|
||||
|
||||
def test_the_owner_forms_exist_and_the_map_points_at_them(self) -> None:
|
||||
for form in ("docs/vision.md", "docs/problem-statement.md"):
|
||||
self.assertIn("(채울 것", (REPO / form).read_text(encoding="utf-8"), form)
|
||||
self.assertIn(f"`{form}`", (REPO / "AGENTS.md").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class SubagentTest(unittest.TestCase):
|
||||
AGENTS = CLAUDE / "agents"
|
||||
|
||||
def test_the_agent_tool_is_not_denied(self) -> None:
|
||||
settings = json.loads((CLAUDE / "settings.json").read_text(encoding="utf-8"))
|
||||
deny = settings.get("permissions", {}).get("deny", [])
|
||||
self.assertFalse([rule for rule in deny if rule == "Agent" or rule.startswith("Agent(")])
|
||||
|
||||
def test_each_definition_names_itself_and_says_when_to_use_it(self) -> None:
|
||||
definitions = sorted(self.AGENTS.glob("*.md"))
|
||||
self.assertEqual([path.stem for path in definitions], ["arch-reviewer", "code-simplifier", "verify-app"])
|
||||
for path in definitions:
|
||||
fields, _ = front_matter(path)
|
||||
self.assertEqual(fields.get("name"), path.stem, path)
|
||||
self.assertIn("쓴다", fields.get("description", ""), path)
|
||||
self.assertTrue(fields.get("tools"), f"{path} must list its tools; an empty list inherits every tool")
|
||||
|
||||
def test_no_subagent_can_edit_files(self) -> None:
|
||||
for path in self.AGENTS.glob("*.md"):
|
||||
tools = {tool.strip() for tool in front_matter(path)[0].get("tools", "").split(",")}
|
||||
self.assertFalse(tools & WRITE_TOOLS, f"{path} returns results only; it must not hold {tools & WRITE_TOOLS}")
|
||||
|
||||
def test_the_reviewers_run_nothing_heavy(self) -> None:
|
||||
self.assertNotIn("Bash", front_matter(self.AGENTS / "code-simplifier.md")[0]["tools"])
|
||||
reviewer = (self.AGENTS / "arch-reviewer.md").read_text(encoding="utf-8")
|
||||
self.assertIn("파일을 쓰거나 고치지 않는다", reviewer)
|
||||
self.assertIn("pnpm·node·게이트는 돌리지 않는다", reviewer)
|
||||
|
||||
def test_verify_app_runs_on_the_desktop_under_the_shared_lock(self) -> None:
|
||||
text = (self.AGENTS / "verify-app.md").read_text(encoding="utf-8")
|
||||
for fragment in ("docs/work/operate.md", "scripts/verify.sh", "flock /tmp/claude-gates/heavy.lock",
|
||||
"stash@{0}", "TEST_RUN_ID"):
|
||||
self.assertIn(fragment, text)
|
||||
|
||||
|
||||
class SkillTest(unittest.TestCase):
|
||||
CANON = {"new-feature": "docs/work/new-feature.md", "desktop-gates": "docs/work/operate.md"}
|
||||
|
||||
def test_the_repository_skills_are_the_two_the_manual_names(self) -> None:
|
||||
self.assertEqual(sorted(path.parent.name for path in (CLAUDE / "skills").glob("*/SKILL.md")), sorted(self.CANON))
|
||||
|
||||
def test_each_skill_is_model_invoked_and_says_when_in_its_description(self) -> None:
|
||||
for name in self.CANON:
|
||||
fields, _ = front_matter(CLAUDE / "skills" / name / "SKILL.md")
|
||||
self.assertEqual(fields.get("name"), name)
|
||||
self.assertNotIn("disable-model-invocation", fields)
|
||||
description = fields.get("description", "")
|
||||
self.assertLessEqual(len(description), DESCRIPTION_LIMIT, name)
|
||||
self.assertIn("쓴다", description, f"{name}: say when to use it")
|
||||
self.assertIn("부른다", description, f"{name}: say what the user says that calls it")
|
||||
|
||||
def test_each_skill_points_at_its_canonical_playbook_instead_of_copying_it(self) -> None:
|
||||
for name, canon in self.CANON.items():
|
||||
body = (CLAUDE / "skills" / name / "SKILL.md").read_text(encoding="utf-8")
|
||||
self.assertIn(f"정본은 `{canon}`", body)
|
||||
self.assertIn("정본이 맞다", body)
|
||||
|
||||
|
||||
class PathRuleTest(unittest.TestCase):
|
||||
def test_every_rule_is_scoped_by_paths_that_exist(self) -> None:
|
||||
rules = sorted((CLAUDE / "rules").glob("*.md"))
|
||||
self.assertEqual([path.stem for path in rules], ["adapters", "docs", "features", "gates-and-budgets", "tests"])
|
||||
for path in rules:
|
||||
fields, patterns = front_matter(path)
|
||||
self.assertIn("paths", fields, path)
|
||||
self.assertTrue(patterns, path)
|
||||
for pattern in patterns:
|
||||
# A pattern that matches nothing is a rule nobody reads.
|
||||
self.assertTrue(next(REPO.glob(pattern), None), f"{path}: '{pattern}' matches no file")
|
||||
|
||||
|
||||
class GitignoreTest(unittest.TestCase):
|
||||
def test_the_shared_claude_files_are_tracked_and_session_state_is_not(self) -> None:
|
||||
lines = (REPO / ".gitignore").read_text(encoding="utf-8").splitlines()
|
||||
for line in (".claude/*", "!.claude/settings.json", "!.claude/rules/", "!.claude/agents/", "!.claude/skills/"):
|
||||
self.assertIn(line, lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,307 @@
|
||||
"""scripts/hooks/hooks.py의 시험. 고장 낸 입력에서 알림이 나오고, 맞는 입력에서 조용한지 본다.
|
||||
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parent.parent
|
||||
REPO = SCRIPTS.parent
|
||||
_spec = importlib.util.spec_from_file_location("hooks", SCRIPTS / "hooks/hooks.py")
|
||||
hooks = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["hooks"] = hooks
|
||||
_spec.loader.exec_module(hooks)
|
||||
|
||||
GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath",
|
||||
"GIT_CONFIG_VALUE_0": "/dev/null"}
|
||||
FILES = {
|
||||
"src/adapters/http/index.ts": "export * from './client.ts';\n",
|
||||
"src/adapters/http/client.ts": "export const client = 1;\n",
|
||||
"src/adapters/auth/index.ts": "export const auth = 1;\n",
|
||||
"src/adapters/auth/session.ts": "export const session = 1;\n",
|
||||
"src/adapters/platform/locks.ts": "export const locks = 1;\n",
|
||||
"src/bootstrap/compose.ts": "export {};\n",
|
||||
"src/presentation/pages/home-page.tsx": "export {};\n",
|
||||
"src/domain/order.ts": "export {};\n",
|
||||
}
|
||||
|
||||
|
||||
class Repository:
|
||||
"""A throwaway git checkout with the real import rules and a few adapter groups."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._directory = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self._directory.name).resolve()
|
||||
shutil.copy(REPO / hooks.RULES, self.root / hooks.RULES)
|
||||
for path, text in FILES.items():
|
||||
self.write(path, text)
|
||||
self.git("init", "-q")
|
||||
self.git("add", "-A")
|
||||
self.git("commit", "-q", "-m", "base")
|
||||
|
||||
def git(self, *args: str) -> None:
|
||||
subprocess.run(["git", *args], cwd=self.root, check=True, capture_output=True, env={**os.environ, **GIT_ENV})
|
||||
|
||||
def write(self, path: str, text: str) -> Path:
|
||||
target = self.root / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(text, encoding="utf-8")
|
||||
return target
|
||||
|
||||
def payload(self, path: str, tool: str = "Edit", **extra) -> dict:
|
||||
return {"session_id": "s1", "cwd": str(self.root), "tool_name": tool,
|
||||
"tool_input": {"file_path": str(self.root / path)}, **extra}
|
||||
|
||||
def close(self) -> None:
|
||||
self._directory.cleanup()
|
||||
|
||||
|
||||
def run_event(event: str, payload: dict) -> tuple[int, str, str]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with mock.patch.dict(os.environ, {}, clear=False), \
|
||||
mock.patch.object(sys, "stdin", io.StringIO(json.dumps(payload))), redirect_stdout(out), redirect_stderr(err):
|
||||
os.environ.pop("CLAUDE_PROJECT_DIR", None)
|
||||
code = hooks.main([event])
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
|
||||
def added_context(stdout: str) -> str:
|
||||
return json.loads(stdout)["hookSpecificOutput"]["additionalContext"] if stdout else ""
|
||||
|
||||
|
||||
class RepositoryTestCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.repo = Repository()
|
||||
self.addCleanup(self.repo.close)
|
||||
|
||||
def edit(self, path: str, text: str) -> str:
|
||||
self.repo.write(path, text)
|
||||
code, out, _ = run_event("post-edit", self.repo.payload(path))
|
||||
self.assertEqual(code, 0)
|
||||
return added_context(out)
|
||||
|
||||
|
||||
class BoundaryNudgeTest(RepositoryTestCase):
|
||||
def test_a_deep_import_past_the_barrel_is_item_1(self) -> None:
|
||||
text = self.edit("src/bootstrap/compose.ts", 'import { client } from "../adapters/http/client.ts";\n')
|
||||
self.assertIn("경계 알림(N3) src/bootstrap/compose.ts", text)
|
||||
self.assertIn("꼭 지킬 것 1 의심: `adapter-groups-are-reached-through-their-barrel`", text)
|
||||
self.assertIn("src/adapters/http/client.ts", text)
|
||||
|
||||
def test_the_barrel_is_quiet(self) -> None:
|
||||
self.assertEqual(self.edit("src/bootstrap/compose.ts", 'import { client } from "../adapters/http/index.ts";\n'), "")
|
||||
|
||||
def test_another_adapter_is_item_2_and_the_kernel_is_allowed(self) -> None:
|
||||
text = self.edit("src/adapters/http/client.ts", textwrap.dedent("""\
|
||||
import { session } from "../auth/session.ts";
|
||||
import { locks } from "../platform/locks.ts";
|
||||
"""))
|
||||
self.assertIn("꼭 지킬 것 2 의심: `adapters-do-not-know-other-concrete-adapters`", text)
|
||||
self.assertNotIn("platform/locks", text)
|
||||
|
||||
def test_a_package_import_is_checked_by_its_name(self) -> None:
|
||||
text = self.edit("src/domain/order.ts", 'import { useState } from "react";\n')
|
||||
self.assertIn("꼭 지킬 것 3 의심: `domain-is-framework-neutral` — `react`", text)
|
||||
|
||||
def test_type_only_reexports_and_dynamic_imports_count(self) -> None:
|
||||
for source in ('export type { Client } from "../../adapters/http/client.ts";\n',
|
||||
'const page = () => import("../../adapters/http/client.ts");\n',
|
||||
'import type {\n Client,\n} from "../../adapters/http/client";\n'):
|
||||
with self.subTest(source=source):
|
||||
self.assertIn("presentation-does-not-know-adapters",
|
||||
self.edit("src/presentation/pages/home-page.tsx", source))
|
||||
|
||||
def test_findings_are_capped_and_keep_the_gate_line(self) -> None:
|
||||
text = self.edit("src/presentation/pages/home-page.tsx",
|
||||
'import { client } from "../../adapters/http/client.ts";\nimport z from "zod";\n')
|
||||
lines = text.splitlines()
|
||||
self.assertLessEqual(len(lines), hooks.MAX_LINES)
|
||||
self.assertRegex(lines[-2], r"^- 외 \d+개$")
|
||||
self.assertIn("FE-GATE-010", lines[-1])
|
||||
|
||||
def test_files_outside_src_and_declarations_are_not_checked(self) -> None:
|
||||
self.assertEqual(self.edit("tests/unit/x.test.ts", 'import { c } from "../../src/adapters/http/client.ts";\n'), "")
|
||||
self.assertEqual(self.edit("src/bootstrap/env.d.ts", 'import { c } from "../adapters/http/client.ts";\n'), "")
|
||||
|
||||
def test_the_real_rules_find_nothing_in_the_real_sources(self) -> None:
|
||||
# A nudge the gate would not raise is noise. The repository passes check:architecture, so every
|
||||
# source file here must be quiet; a new false positive fails this test before it reaches a session.
|
||||
noisy = []
|
||||
for path in sorted((REPO / "src").rglob("*")):
|
||||
if path.suffix in (".ts", ".tsx") and path.is_file():
|
||||
relative = path.relative_to(REPO).as_posix()
|
||||
if hooks.boundary_findings(REPO, relative, path.read_text(encoding="utf-8")):
|
||||
noisy.append(relative)
|
||||
self.assertEqual(noisy, [])
|
||||
|
||||
|
||||
class StandardNudgeTest(RepositoryTestCase):
|
||||
TEST = "tests/unit/orders.test.ts"
|
||||
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.repo.write(self.TEST, 'it.skip("a", () => {});\nit("b", () => {});\n')
|
||||
self.repo.git("add", "-A")
|
||||
self.repo.git("commit", "-q", "-m", "test")
|
||||
|
||||
def test_skips_and_only_added_since_the_last_commit_are_reported(self) -> None:
|
||||
text = self.edit(self.TEST, 'it.skip("a", () => {});\nit.skip("b", () => {});\ndescribe.only("c", () => {});\n')
|
||||
self.assertIn("게이트 기준 알림(N6) tests/unit/orders.test.ts", text)
|
||||
self.assertIn("`.only` 0→1", text)
|
||||
self.assertIn("`.skip` 1→2", text)
|
||||
self.assertIn("꼭 지킬 것 4", text)
|
||||
|
||||
def test_an_unchanged_or_smaller_count_is_quiet(self) -> None:
|
||||
self.assertEqual(self.edit(self.TEST, 'it.skip("a", () => { expect(1).toBe(1); });\n'), "")
|
||||
self.assertEqual(self.edit(self.TEST, 'it("a", () => {});\n'), "")
|
||||
|
||||
def test_a_new_test_file_counts_from_zero_and_playwright_fixme_counts(self) -> None:
|
||||
text = self.edit("tests/e2e/new.spec.ts", 'test.fixme("x", async () => {});\n')
|
||||
self.assertIn("`.fixme` 0→1", text)
|
||||
|
||||
def test_a_gate_standard_file_edit_is_reported(self) -> None:
|
||||
for path in ("config/performance/budgets.json", "config/ci/ungated-tests.json",
|
||||
"config/scale/feature-shape-ceilings.json", "vitest.config.ts",
|
||||
"tests/unit/__snapshots__/x.test.ts.snap"):
|
||||
with self.subTest(path=path):
|
||||
self.assertIn("게이트의 기준 파일", self.edit(path, "{}\n"))
|
||||
|
||||
def test_source_text_that_looks_like_a_skip_is_not_counted(self) -> None:
|
||||
self.assertEqual(self.edit("src/domain/order.ts", 'export const note = "use it.only when";\n'), "")
|
||||
|
||||
|
||||
class DocumentNudgeTest(RepositoryTestCase):
|
||||
def checker(self, code: int, stderr_lines: list[str]) -> None:
|
||||
body = "import sys\n" + "".join(f"print({line!r}, file=sys.stderr)\n" for line in stderr_lines)
|
||||
self.repo.write(hooks.DOC_CHECK[0], body + f"sys.exit({code})\n")
|
||||
|
||||
def test_failures_naming_the_edited_document_come_back_first(self) -> None:
|
||||
self.checker(1, ["", "FAILED: 2 problem(s)", " docs/work/improve.md:3: history ID '1103/11-07'",
|
||||
" docs/work/README.md:9: broken relative link 'x.md'"])
|
||||
text = self.edit("docs/work/improve.md", "# x\n")
|
||||
self.assertIn("문서 검사 알림(N2) docs/work/improve.md", text)
|
||||
self.assertIn("1103/11-07", text)
|
||||
self.assertNotIn("broken relative link", text)
|
||||
|
||||
def test_failures_elsewhere_are_shown_when_none_names_the_document(self) -> None:
|
||||
self.checker(1, [" AGENTS.md: 41 lines, limit 40"])
|
||||
self.assertIn("AGENTS.md: 41 lines", self.edit("docs/manual/README.md", "# x\n"))
|
||||
|
||||
def test_a_passing_check_adds_nothing(self) -> None:
|
||||
self.checker(0, [])
|
||||
self.assertEqual(self.edit("docs/work/improve.md", "# x\n"), "")
|
||||
|
||||
|
||||
class TurnEndNudgeTest(RepositoryTestCase):
|
||||
def stop(self, **extra) -> dict | None:
|
||||
_, out, _ = run_event("stop", {"session_id": "s1", "cwd": str(self.repo.root), **extra})
|
||||
return json.loads(out) if out else None
|
||||
|
||||
def bash(self, command: str) -> None:
|
||||
run_event("post-bash", {"session_id": "s1", "cwd": str(self.repo.root), "tool_name": "Bash",
|
||||
"tool_input": {"command": command}})
|
||||
|
||||
def test_an_edit_blocks_the_turn_end_once_with_the_reason(self) -> None:
|
||||
self.edit("src/domain/order.ts", "export const a = 1;\n")
|
||||
first = self.stop()
|
||||
self.assertEqual(first["decision"], "block")
|
||||
self.assertIn("src/domain/order.ts", first["reason"])
|
||||
self.assertIn("scripts/verify.sh", first["reason"])
|
||||
self.assertIsNone(self.stop())
|
||||
|
||||
def test_a_desktop_run_clears_the_pending_edits(self) -> None:
|
||||
for command in ("ssh desktop 'cd ~/workspace/x && corepack pnpm -s lint'",
|
||||
"scripts/verify.sh merge --log fe-x",
|
||||
"./scripts/verify.sh gate FE-GATE-005",
|
||||
"cd /w && scripts/verify.sh script verify:documentation 2>&1 | tail"):
|
||||
with self.subTest(command=command):
|
||||
self.edit("src/domain/order.ts", "export const a = 2;\n")
|
||||
self.bash(command)
|
||||
self.assertIsNone(self.stop())
|
||||
|
||||
def test_laptop_commands_and_other_hosts_do_not_count(self) -> None:
|
||||
for command in ("corepack pnpm lint", "ssh build-box 'corepack pnpm lint'", "scripts/verify.sh docs",
|
||||
"scripts/verify.sh hooks", "scripts/verify.sh gate FE-GATE-005 --on here",
|
||||
"ssh desktop uptime"):
|
||||
with self.subTest(command=command):
|
||||
self.edit("src/domain/order.ts", "export const a = 3;\n")
|
||||
self.bash(command)
|
||||
self.assertIsNotNone(self.stop())
|
||||
|
||||
def test_files_the_laptop_checks_do_not_need_the_desktop(self) -> None:
|
||||
for path in (".claude/rules/x.md", "scripts/hooks/hooks.py", "scripts/tests/test_x.py", "CLAUDE.md",
|
||||
"docs/ledger/estimates.jsonl", "scripts/check-work-docs.py", "src/adapters/AGENTS.md",
|
||||
"src/features/CLAUDE.md"):
|
||||
self.repo.write(path, "x\n")
|
||||
run_event("post-edit", self.repo.payload(path))
|
||||
self.assertIsNone(self.stop())
|
||||
|
||||
def test_a_new_edit_after_the_reminder_reminds_again(self) -> None:
|
||||
self.edit("src/domain/order.ts", "export const a = 4;\n")
|
||||
self.stop()
|
||||
self.edit("docs/work/README.md", "# x\n")
|
||||
self.assertIsNotNone(self.stop())
|
||||
|
||||
def test_an_active_stop_hook_never_blocks_again(self) -> None:
|
||||
self.edit("src/domain/order.ts", "export const a = 5;\n")
|
||||
self.assertIsNone(self.stop(stop_hook_active=True))
|
||||
|
||||
|
||||
class SettingsWiringTest(unittest.TestCase):
|
||||
SETTINGS = REPO / ".claude/settings.json"
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.settings = json.loads(self.SETTINGS.read_text(encoding="utf-8"))
|
||||
|
||||
def commands(self, event: str, matcher: str | None) -> list[str]:
|
||||
return [hook["command"] for entry in self.settings["hooks"].get(event, [])
|
||||
if entry.get("matcher") == matcher for hook in entry["hooks"]]
|
||||
|
||||
def test_every_event_calls_its_hook(self) -> None:
|
||||
self.assertEqual(self.commands("PostToolUse", "Edit|Write|MultiEdit"),
|
||||
['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py post-edit'])
|
||||
self.assertEqual(self.commands("PostToolUse", "Bash"),
|
||||
['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py post-bash'])
|
||||
self.assertEqual(self.commands("Stop", None), ['python3 "$CLAUDE_PROJECT_DIR"/scripts/hooks/hooks.py stop'])
|
||||
self.assertNotIn("PreToolUse", self.settings["hooks"])
|
||||
|
||||
def test_real_env_files_are_denied_and_the_example_is_not(self) -> None:
|
||||
deny = self.settings["permissions"]["deny"]
|
||||
for tool in ("Read", "Edit"):
|
||||
self.assertIn(f"{tool}(**/.env)", deny)
|
||||
self.assertIn(f"{tool}(**/.env.local)", deny)
|
||||
self.assertFalse([rule for rule in deny if "example" in rule or rule in ("Read(**/.env.*)", "Edit(**/.env.*)")])
|
||||
|
||||
def test_the_harness_plugin_is_enabled_from_its_marketplace(self) -> None:
|
||||
self.assertEqual(self.settings["enabledPlugins"], {"harness@claude-harness": True})
|
||||
source = self.settings["extraKnownMarketplaces"]["claude-harness"]["source"]
|
||||
self.assertEqual(source, {"source": "git",
|
||||
"url": "https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness.git"})
|
||||
|
||||
def test_the_hook_script_runs_from_the_command_line(self) -> None:
|
||||
for event in hooks.EVENTS:
|
||||
result = subprocess.run([sys.executable, str(SCRIPTS / "hooks/hooks.py"), event], input="{}",
|
||||
capture_output=True, text=True, timeout=10, cwd=tempfile.gettempdir())
|
||||
self.assertEqual(result.returncode, 0, event + result.stderr)
|
||||
result = subprocess.run([sys.executable, str(SCRIPTS / "hooks/hooks.py"), "nope"], input="{}",
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""docs/ledger/estimates.jsonl의 줄이 docs/ledger/README.md 형식인지 본다. 빈 파일(복사한 프로젝트)도 통과한다.
|
||||
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent.parent
|
||||
LEDGER = REPO / "docs/ledger/estimates.jsonl"
|
||||
KINDS = {"estimate", "actual", "retro"}
|
||||
COMMON = ("schema", "kind", "task", "recorded_at")
|
||||
RANGES = ("minutes", "calls", "output_tokens")
|
||||
|
||||
|
||||
def lines() -> list[dict]:
|
||||
if not LEDGER.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in LEDGER.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
|
||||
|
||||
class LedgerTest(unittest.TestCase):
|
||||
def test_lines_merge_by_union(self) -> None:
|
||||
self.assertIn("docs/ledger/estimates.jsonl merge=union",
|
||||
(REPO / ".gitattributes").read_text(encoding="utf-8").splitlines())
|
||||
|
||||
def test_every_line_is_json_with_the_common_fields(self) -> None:
|
||||
for number, entry in enumerate(lines(), start=1):
|
||||
self.assertTrue(set(COMMON) <= entry.keys(), f"line {number}: {sorted(set(COMMON) - entry.keys())}")
|
||||
self.assertEqual(entry["schema"], 1, number)
|
||||
self.assertIn(entry["kind"], KINDS, number)
|
||||
datetime.fromisoformat(entry["recorded_at"])
|
||||
|
||||
def test_an_estimate_has_ordered_ranges_and_a_basis(self) -> None:
|
||||
for entry in (e for e in lines() if e["kind"] == "estimate"):
|
||||
for field in RANGES:
|
||||
values = entry[field]
|
||||
self.assertLessEqual(values["p30"], values["p50"], (entry["task"], field))
|
||||
self.assertLessEqual(values["p50"], values["p80"], (entry["task"], field))
|
||||
self.assertTrue(entry["basis"].strip(), entry["task"])
|
||||
|
||||
def test_an_actual_follows_its_estimate_and_names_the_band_it_fell_in(self) -> None:
|
||||
entries = lines()
|
||||
for position, entry in enumerate(entries):
|
||||
if entry["kind"] != "actual":
|
||||
continue
|
||||
estimates = [e for e in entries[:position] if e["kind"] == "estimate" and e["task"] == entry["task"]]
|
||||
self.assertTrue(estimates, f"{entry['task']}: an actual line needs an earlier estimate line")
|
||||
bands = estimates[-1]["minutes"]
|
||||
expected = next((band for band in ("p30", "p50", "p80") if entry["active_minutes"] <= bands[band]), "over")
|
||||
self.assertEqual(entry["within"], expected, entry["task"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,150 @@
|
||||
"""scripts/verify.sh의 시험. 단계를 계약 파일에서 읽는지, 잘못된 인자를 원격에 보내기 전에 거절하는지,
|
||||
지금 트리를 원격 worktree로 옮겨 같은 트리에서 돌리고 지우는지를 표준 라이브러리와 git·bash·flock으로 본다.
|
||||
원격은 가짜 ssh(호스트를 무시하고 이 기계에서 실행)다. pnpm은 돌리지 않는다.
|
||||
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent.parent
|
||||
VERIFY = REPO / "scripts/verify.sh"
|
||||
GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath",
|
||||
"GIT_CONFIG_VALUE_0": "/dev/null"}
|
||||
|
||||
|
||||
def sh(args: list[str], cwd: Path, env: dict | None = None, check: bool = True) -> subprocess.CompletedProcess:
|
||||
result = subprocess.run(args, cwd=cwd, env={**os.environ, **GIT_ENV, **(env or {})}, capture_output=True,
|
||||
text=True, timeout=60)
|
||||
if check and result.returncode != 0:
|
||||
raise AssertionError(f"{args} → {result.returncode}\n{result.stdout}\n{result.stderr}")
|
||||
return result
|
||||
|
||||
|
||||
def gates() -> dict:
|
||||
return json.loads((REPO / "config/ci/gates.json").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class StagePlanTest(unittest.TestCase):
|
||||
def test_a_stage_runs_every_gate_the_contract_lists(self) -> None:
|
||||
for stage in gates()["stages"]:
|
||||
with self.subTest(stage=stage["id"]):
|
||||
result = sh([str(VERIFY), stage["id"], "--dry-run"], cwd=REPO)
|
||||
planned = [line.split(":")[0] for line in result.stdout.splitlines()]
|
||||
self.assertEqual(planned, stage["gateIds"])
|
||||
self.assertIn(f"ci:gate {stage['gateIds'][0]}", result.stdout)
|
||||
|
||||
def test_parts_runs_each_command_of_the_gate(self) -> None:
|
||||
contract = gates()
|
||||
gate = next(g for g in contract["gates"] if g["id"] == "FE-GATE-013")
|
||||
scripts = {c["id"]: c["script"] for c in contract["commands"]}
|
||||
result = sh([str(VERIFY), "parts", "FE-GATE-013", "--dry-run"], cwd=REPO)
|
||||
self.assertEqual([line.split(": ", 1)[1] for line in result.stdout.splitlines()],
|
||||
[f"corepack pnpm -s {scripts[c]}" for c in gate["commandIds"]])
|
||||
|
||||
def test_arguments_after_the_separator_go_to_the_one_script_or_command_as_given(self) -> None:
|
||||
result = sh([str(VERIFY), "script", "test:sample-removal", "--dry-run", "--", "--feature=invoice-feature"],
|
||||
cwd=REPO)
|
||||
self.assertEqual(result.stdout.strip(),
|
||||
"test:sample-removal: corepack pnpm -s test:sample-removal --feature=invoice-feature")
|
||||
result = sh([str(VERIFY), "exec", "--dry-run", "--", "node", "scripts/run-vitest.ts", "run", "tests/a b.test.ts"],
|
||||
cwd=REPO)
|
||||
self.assertEqual(result.stdout.strip(), r"exec node: node scripts/run-vitest.ts run tests/a\ b.test.ts")
|
||||
|
||||
def test_wrong_arguments_are_refused_here_before_anything_is_sent(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
calls = Path(folder) / "calls"
|
||||
fake_ssh = Path(folder) / "ssh"
|
||||
fake_ssh.write_text(f'#!/bin/sh\necho "$@" >> {calls}\n', encoding="utf-8")
|
||||
fake_ssh.chmod(0o755)
|
||||
for args in (["nope"], ["gate", "FE-GATE-999"], ["parts"], ["gate"], ["merge", "extra"], ["docs", "x"],
|
||||
["script", "a", "b", "--", "--x"], ["exec"], ["exec", "--"], ["script", "--", "x"]):
|
||||
with self.subTest(args=args):
|
||||
result = sh([str(VERIFY), *args], cwd=REPO, env={"VERIFY_SSH": str(fake_ssh)}, check=False)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertFalse(calls.exists(), "a refused command must not reach the remote host")
|
||||
|
||||
|
||||
class CiEnvironmentTest(unittest.TestCase):
|
||||
def test_the_ci_env_names_the_head_commit_and_its_time(self) -> None:
|
||||
# parts and script run the gate commands without ci:gate, which would otherwise set SOURCE_DATE_EPOCH.
|
||||
script = (f'eval "$(sed -n "/^ci_env()/,/^}}/p" {VERIFY})"; ci_env; '
|
||||
'echo "$CI $VITE_COMMIT_SHA $SOURCE_DATE_EPOCH $CI_RUNNER_IMAGE"')
|
||||
ci, sha, epoch, image = sh(["bash", "-c", script], cwd=REPO).stdout.split()
|
||||
self.assertEqual(ci, "true")
|
||||
self.assertEqual(sha, sh(["git", "rev-parse", "HEAD"], cwd=REPO).stdout.strip())
|
||||
self.assertEqual(epoch, sh(["git", "log", "-1", "--format=%ct"], cwd=REPO).stdout.strip())
|
||||
self.assertRegex(image, r"@sha256:[0-9a-f]{64}$")
|
||||
|
||||
|
||||
class RemoteTransportTest(unittest.TestCase):
|
||||
"""--on <호스트>: the patch lands in a fresh worktree, the tree matches, the run is logged, the worktree goes."""
|
||||
|
||||
def test_the_working_tree_is_run_remotely_on_the_same_tree_and_cleaned_up(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
base = Path(folder)
|
||||
project, bare, remote, logs = (base / name for name in ("project", "origin.git", "remote", "logs"))
|
||||
(project / "scripts").mkdir(parents=True)
|
||||
(project / "config/ci").mkdir(parents=True)
|
||||
shutil.copy(VERIFY, project / "scripts/verify.sh")
|
||||
shutil.copy(REPO / "config/ci/gates.json", project / "config/ci/gates.json")
|
||||
shutil.copy(REPO / ".nvmrc", project / ".nvmrc")
|
||||
(project / "scripts/check-work-docs.py").write_text("print('docs checked')\n", encoding="utf-8")
|
||||
sh(["git", "init", "-q", "-b", "main"], cwd=project)
|
||||
sh(["git", "add", "-A"], cwd=project)
|
||||
sh(["git", "commit", "-q", "-m", "init"], cwd=project)
|
||||
sh(["git", "clone", "-q", "--bare", str(project), str(bare)], cwd=base)
|
||||
sh(["git", "remote", "add", "origin", str(bare)], cwd=project)
|
||||
sh(["git", "fetch", "-q", "origin"], cwd=project)
|
||||
sh(["git", "clone", "-q", str(bare), str(remote)], cwd=base)
|
||||
(project / "notes.md").write_text("커밋 안 한 새 파일\n", encoding="utf-8")
|
||||
with (project / "scripts/check-work-docs.py").open("a", encoding="utf-8") as handle:
|
||||
handle.write("print('changed here')\n")
|
||||
fake_ssh = base / "fake-ssh"
|
||||
fake_ssh.write_text('#!/bin/sh\nshift\nexec bash -c "$*"\n', encoding="utf-8")
|
||||
fake_ssh.chmod(0o755)
|
||||
env = {"VERIFY_SSH": str(fake_ssh), "VERIFY_REMOTE_REPO": str(remote), "VERIFY_LOCK": str(base / "lock"),
|
||||
"VERIFY_LOG_ROOT": str(logs), "VERIFY_NODE_BIN": "/nonexistent"}
|
||||
temp_index = base / "index"
|
||||
shutil.copy(project / ".git/index", temp_index)
|
||||
sh(["git", "add", "-A"], cwd=project, env={"GIT_INDEX_FILE": str(temp_index)})
|
||||
here = sh(["git", "write-tree"], cwd=project, env={"GIT_INDEX_FILE": str(temp_index)}).stdout.strip()
|
||||
|
||||
result = sh(["scripts/verify.sh", "docs", "--on", "build-host", "--log", "t"], cwd=project, env=env,
|
||||
check=False)
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
summary = (logs / "t/summary.txt").read_text(encoding="utf-8")
|
||||
self.assertTrue(summary.startswith(f"tree {here} commit "), summary)
|
||||
self.assertIn("rc=0", summary)
|
||||
self.assertIn("changed here", (logs / "t/run.log").read_text(encoding="utf-8"))
|
||||
self.assertFalse((logs / "t/install.log").exists(), "a laptop stage installs nothing")
|
||||
worktrees = sh(["git", "worktree", "list"], cwd=remote).stdout.strip().splitlines()
|
||||
self.assertEqual(len(worktrees), 1, worktrees)
|
||||
self.assertEqual(sh(["git", "status", "--porcelain"], cwd=remote).stdout, "")
|
||||
self.assertEqual((logs / "t/changes.patch").read_text(encoding="utf-8"), "")
|
||||
|
||||
made = sh(["scripts/verify.sh", "exec", "--on", "build-host", "--log", "t2", "--apply-back", "--", "bash", "-c",
|
||||
"echo made > made.txt && echo more >> notes.md"], cwd=project,
|
||||
env={**env, "VERIFY_INSTALL": "0"}, check=False)
|
||||
self.assertEqual(made.returncode, 0, made.stdout + made.stderr)
|
||||
self.assertEqual((project / "made.txt").read_text(encoding="utf-8"), "made\n")
|
||||
self.assertEqual((project / "notes.md").read_text(encoding="utf-8"), "커밋 안 한 새 파일\nmore\n")
|
||||
self.assertIn("2개를 이 작업 트리에 얹었다", made.stderr)
|
||||
|
||||
missing = sh(["scripts/verify.sh", "docs", "--on", "build-host"], cwd=project,
|
||||
env={**env, "VERIFY_REMOTE_REPO": str(base / "missing")}, check=False)
|
||||
self.assertEqual(missing.returncode, 4)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+321
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env bash
|
||||
# 검증 진입점. 사람·CI·에이전트가 같은 명령을 쓴다(docs/work/reference/gates.md).
|
||||
#
|
||||
# scripts/verify.sh <단계> [대상…] [--on here|<호스트>] [--log <이름>] [--apply-back] [--dry-run] [-- 인자…]
|
||||
#
|
||||
# 단계 무엇 기본 위치
|
||||
# docs 작업 매뉴얼 검사(check-work-docs.py)와 장부 형식 여기
|
||||
# hooks repo 훅·검사기·장부 시험(python3 unittest) 여기
|
||||
# gate <FE-GATE-NNN>… 게이트마다 `corepack pnpm ci:gate <ID>`, CI env로 desktop
|
||||
# parts <FE-GATE-NNN> 그 게이트의 명령을 하나씩 끝까지(첫 실패에서 멈추지 않음) desktop
|
||||
# script <이름>… [-- 인자] package script를 하나씩. `--` 뒤 인자는 script가 하나일 때만 desktop
|
||||
# exec -- <명령…> 명령 하나(예: node scripts/run-vitest.ts run <파일>) desktop
|
||||
# <stage id> config/ci/gates.json stages의 gateIds 전부(merge 등) desktop
|
||||
#
|
||||
# 게이트·stage는 실패가 있어도 끝까지 돌고, 끝에 게이트마다 rc와 초를 적는다. 실패가 하나라도 있으면 rc=1.
|
||||
# --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를
|
||||
# 만들어 패치를 적용하고 트리 해시가 여기와 같은지 본 뒤, 그 트리를 커밋 하나로 만들어(깨끗한 HEAD) 의존성을
|
||||
# 오프라인으로 설치하고 잠금 아래에서 같은 단계를 돌린다. 로그를 남기고 worktree를 지운다. push하지 않는다.
|
||||
# 원격에서 바뀐 파일은 로그 폴더의 changes.patch에 남는다. --apply-back이면 그 패치를 여기 작업 트리에 얹는다
|
||||
# (create:feature, 기준선 다시 쓰기처럼 파일을 만드는 명령). VERIFY_SNAPSHOT=1이면 artifacts·dist·test-results를
|
||||
# 로그 폴더의 snapshot/에 복사한다(리뷰어가 함께 읽는 사본).
|
||||
# 환경 변수: VERIFY_HOST(desktop 단계의 --on 기본값, 기본 desktop), VERIFY_REMOTE_REPO(원격 checkout, 기본
|
||||
# workspace/<repo 이름>, 홈 기준), VERIFY_BASE_REF(기본 origin/main), VERIFY_LOCK(기본 /tmp/claude-gates/heavy.lock),
|
||||
# VERIFY_LOG_ROOT(원격 로그 폴더, 기본 /tmp/claude-gates), VERIFY_SSH(기본 ssh), VERIFY_NODE_BIN(원격 node 폴더,
|
||||
# 기본 ~/.nvm/versions/node/v<.nvmrc>/bin), VERIFY_INSTALL(0이면 원격 의존성 설치를 건너뛴다).
|
||||
# 종료 코드: 0 통과, 1 실패, 2 사용법, 4 원격 준비 실패.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=$(git rev-parse --show-toplevel)
|
||||
cd "$ROOT"
|
||||
TMP_FILES=()
|
||||
trap '[ ${#TMP_FILES[@]} -eq 0 ] || rm -f "${TMP_FILES[@]}"' EXIT # 빈 배열 + set -u는 옛 bash에서 오류다
|
||||
DRY_RUN=0
|
||||
APPLY_BACK=0
|
||||
|
||||
usage() {
|
||||
sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//' >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- config/ci/gates.json 읽기
|
||||
|
||||
gates_json() {
|
||||
python3 - "$@" <<'PY'
|
||||
import json, sys
|
||||
contract = json.load(open("config/ci/gates.json", encoding="utf-8"))
|
||||
kind, *names = sys.argv[1:]
|
||||
if kind == "stages":
|
||||
print("\n".join(stage["id"] for stage in contract["stages"]))
|
||||
elif kind == "stage":
|
||||
found = [stage for stage in contract["stages"] if stage["id"] == names[0]]
|
||||
if not found:
|
||||
sys.exit(1)
|
||||
print("\n".join(found[0]["gateIds"]))
|
||||
elif kind == "gate":
|
||||
if not any(gate["id"] == names[0] for gate in contract["gates"]):
|
||||
sys.exit(1)
|
||||
elif kind == "scripts":
|
||||
gate = next((gate for gate in contract["gates"] if gate["id"] == names[0]), None)
|
||||
if gate is None:
|
||||
sys.exit(1)
|
||||
commands = {command["id"]: command for command in contract["commands"]}
|
||||
for command_id in gate["commandIds"]:
|
||||
command = commands[command_id]
|
||||
print(f'{command["script"]}\t{command.get("expect", "pass")}\t{command.get("expectedExitCode", "")}')
|
||||
PY
|
||||
}
|
||||
|
||||
is_stage() { gates_json stages | grep -qx -- "$1"; }
|
||||
|
||||
# ---------------------------------------------------------------- 단계 본문
|
||||
|
||||
run_docs() {
|
||||
local rc=0
|
||||
python3 scripts/check-work-docs.py || rc=1
|
||||
if [ -s docs/ledger/estimates.jsonl ] && ! python3 -c '
|
||||
import json, sys
|
||||
for number, line in enumerate(open(sys.argv[1], encoding="utf-8"), 1):
|
||||
if line.strip():
|
||||
json.loads(line)
|
||||
' docs/ledger/estimates.jsonl; then
|
||||
echo "docs/ledger/estimates.jsonl에 JSON이 아닌 줄이 있다." >&2
|
||||
rc=1
|
||||
fi
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
run_hooks() { python3 -m unittest discover -s scripts/tests; }
|
||||
|
||||
# CI workflow의 전역 env(.gitea/workflows/quality-gates.yml)와 같은 꼴. CI=true가 있어야 빌드 식별값을 엄격하게 본다.
|
||||
ci_env() {
|
||||
local sha
|
||||
sha=$(git rev-parse HEAD)
|
||||
export CI=true VITE_COMMIT_SHA="$sha" VITE_BUILD_ID="gitea-${VERIFY_RUN:-1}-1" \
|
||||
RELEASE_ID="refs/heads/${VERIFY_REF:-verify}-${VERIFY_RUN:-1}-1" \
|
||||
CI_RUNNER_IMAGE="local/runner@sha256:$(printf 'a%.0s' $(seq 64))" \
|
||||
SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)"
|
||||
# ci:gate makes SOURCE_DATE_EPOCH from HEAD itself; parts and script call the commands directly.
|
||||
}
|
||||
|
||||
# 한 줄 결과: "<이름> rc=<n> <초>s". 로그는 VERIFY_STEP_LOGS가 있으면 그 폴더에 이름별로.
|
||||
step() {
|
||||
local name=$1 rc start log
|
||||
shift
|
||||
if [ "$DRY_RUN" = 1 ]; then
|
||||
local shown
|
||||
shown=$(printf '%q ' "$@")
|
||||
echo "$name: ${shown% }"
|
||||
return 0
|
||||
fi
|
||||
start=$(date +%s)
|
||||
log=${VERIFY_STEP_LOGS:+$VERIFY_STEP_LOGS/$(printf '%s' "$name" | tr ' /:' '___').log}
|
||||
set +e
|
||||
if [ -n "$log" ]; then "$@" > "$log" 2>&1; else "$@"; fi
|
||||
rc=$?
|
||||
set -e
|
||||
echo "$name rc=$rc $(( $(date +%s) - start ))s" | tee -a "${VERIFY_SUMMARY:-/dev/null}"
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
run_gates() {
|
||||
local failed=0 gate
|
||||
[ "$DRY_RUN" = 1 ] || ci_env
|
||||
for gate in "$@"; do
|
||||
gates_json gate "$gate" || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; return 2; }
|
||||
step "$gate" corepack pnpm -s ci:gate "$gate" || failed=1
|
||||
done
|
||||
return "$failed"
|
||||
}
|
||||
|
||||
run_parts() {
|
||||
local gate=$1 failed=0 script expect code rc
|
||||
[ "$DRY_RUN" = 1 ] || ci_env
|
||||
gates_json scripts "$gate" > /dev/null || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; return 2; }
|
||||
while IFS=$'\t' read -r script expect code; do
|
||||
rc=0
|
||||
step "$gate $script" corepack pnpm -s "$script" || rc=$?
|
||||
# expect=fail인 명령(음성 fixture)은 정해진 종료 코드로 실패해야 통과다.
|
||||
if [ "$expect" = fail ]; then
|
||||
[ "$DRY_RUN" = 1 ] || [ "$rc" = "${code:-1}" ] || failed=1
|
||||
elif [ "$rc" != 0 ]; then
|
||||
failed=1
|
||||
fi
|
||||
done < <(gates_json scripts "$gate")
|
||||
return "$failed"
|
||||
}
|
||||
|
||||
# script 이름들, 그 뒤에 `--`와 인자(script가 하나일 때만, check_args가 본다).
|
||||
run_scripts() {
|
||||
local failed=0 names=() script
|
||||
while [ $# -gt 0 ] && [ "$1" != -- ]; do names+=("$1"); shift; done
|
||||
[ $# -eq 0 ] || shift
|
||||
for script in "${names[@]}"; do
|
||||
step "$script" corepack pnpm -s "$script" "$@" || failed=1
|
||||
done
|
||||
return "$failed"
|
||||
}
|
||||
|
||||
run_exec() {
|
||||
[ "${1:-}" = -- ] && shift
|
||||
step "exec $1" "$@"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- 실행 위치
|
||||
|
||||
laptop_stage() { [ "$1" = docs ] || [ "$1" = hooks ]; }
|
||||
|
||||
# 원격으로 보내기 전에 여기서 사용법을 본다. 잘못된 단계 때문에 desktop에 worktree를 만들지 않는다.
|
||||
check_args() {
|
||||
local stage=$1 gate
|
||||
shift
|
||||
case "$stage" in
|
||||
docs | hooks) [ $# -eq 0 ] || usage ;;
|
||||
gate) [ $# -gt 0 ] || usage
|
||||
for gate in "$@"; do gates_json gate "$gate" || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; exit 2; }; done ;;
|
||||
parts) [ $# -eq 1 ] || usage
|
||||
gates_json gate "$1" || { echo "verify: config/ci/gates.json에 없는 게이트: $1" >&2; exit 2; } ;;
|
||||
script)
|
||||
local names=0
|
||||
while [ $# -gt 0 ] && [ "$1" != -- ]; do names=$((names + 1)); shift; done
|
||||
[ "$names" -gt 0 ] || usage
|
||||
# 인자는 script 하나에만 준다. 여럿에 같은 인자를 주면 뜻이 갈린다.
|
||||
[ $# -le 1 ] || [ "$names" -eq 1 ] || usage ;;
|
||||
exec) { [ "${1:-}" = -- ] && [ $# -gt 1 ]; } || usage ;;
|
||||
*) is_stage "$stage" || usage; [ $# -eq 0 ] || usage ;;
|
||||
esac
|
||||
}
|
||||
|
||||
run_here() {
|
||||
local stage=$1
|
||||
shift
|
||||
case "$stage" in
|
||||
docs | hooks) [ $# -eq 0 ] || usage; [ "$DRY_RUN" = 1 ] && { echo "$stage"; return 0; }; "run_$stage" ;;
|
||||
gate) [ $# -gt 0 ] || usage; run_gates "$@" ;;
|
||||
parts) [ $# -eq 1 ] || usage; run_parts "$1" ;;
|
||||
script) [ $# -gt 0 ] || usage; run_scripts "$@" ;;
|
||||
exec) run_exec "$@" ;;
|
||||
*)
|
||||
is_stage "$stage" || usage
|
||||
[ $# -eq 0 ] || usage
|
||||
# shellcheck disable=SC2046 # 게이트 ID는 공백 없는 낱말이다
|
||||
run_gates $(gates_json stage "$stage")
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
run_remote() {
|
||||
local host=$1 log=$2 ssh=${VERIFY_SSH:-ssh}
|
||||
shift 2
|
||||
local name base tree tmp_index patch id remote_repo lock log_root node_bin args ref install=${VERIFY_INSTALL:-1} rc=0 back
|
||||
name=$(basename "$(dirname "$(git rev-parse --path-format=absolute --git-common-dir)")")
|
||||
remote_repo=${VERIFY_REMOTE_REPO:-"workspace/$name"}
|
||||
lock=${VERIFY_LOCK:-/tmp/claude-gates/heavy.lock}
|
||||
log_root=${VERIFY_LOG_ROOT:-/tmp/claude-gates}
|
||||
node_bin=${VERIFY_NODE_BIN:-"\$HOME/.nvm/versions/node/v$(tr -d '[:space:]' < .nvmrc)/bin"}
|
||||
base=$(git merge-base HEAD "${VERIFY_BASE_REF:-origin/main}")
|
||||
ref=$(git branch --show-current | tr '/' '-')
|
||||
laptop_stage "$1" && install=0
|
||||
tmp_index=$(mktemp)
|
||||
patch=$(mktemp)
|
||||
TMP_FILES+=("$tmp_index" "$patch")
|
||||
cp "$(git rev-parse --git-path index)" "$tmp_index"
|
||||
GIT_INDEX_FILE=$tmp_index git add -A
|
||||
tree=$(GIT_INDEX_FILE=$tmp_index git write-tree)
|
||||
git diff --binary "$base" "$tree" > "$patch"
|
||||
id="verify-$(date +%s)-$$"
|
||||
# The stage first, then --on here, then the rest: an option after `--` would reach the command instead.
|
||||
args="$(printf '%q' "$1") --on here"
|
||||
[ $# -lt 2 ] || args+=" $(printf '%q ' "${@:2}")"
|
||||
echo "verify: $host에서 '$*' (기준 ${base:0:12}, 트리 ${tree:0:12}, 로그 $log_root/$log/)" >&2
|
||||
$ssh "$host" "cat > /tmp/$id.patch" < "$patch"
|
||||
$ssh "$host" bash -s <<EOF || rc=$?
|
||||
set -u
|
||||
export PATH="$node_bin:\$PATH"
|
||||
trap 'rm -f /tmp/$id.patch' EXIT
|
||||
cd $remote_repo || exit 4
|
||||
repo=\$(pwd)
|
||||
git cat-file -e $base^{commit} 2>/dev/null || git fetch -q origin || exit 4
|
||||
git cat-file -e $base^{commit} || { echo "기준 커밋 ${base:0:12}이 원격에 없다. 그 커밋을 push한다." >&2; exit 4; }
|
||||
wt=\$(mktemp -d /tmp/$id.XXXXXX)
|
||||
logs=$log_root/$log
|
||||
git worktree add -q --detach "\$wt" $base || exit 4
|
||||
cleanup() {
|
||||
cp -r "\$wt/artifacts/quality/gates" "\$logs/gate-artifacts" 2>/dev/null
|
||||
if [ "${VERIFY_SNAPSHOT:-0}" = 1 ]; then
|
||||
mkdir -p "\$logs/snapshot"
|
||||
for kept in artifacts dist test-results; do cp -r "\$wt/\$kept" "\$logs/snapshot/" 2>/dev/null; done
|
||||
fi
|
||||
cd "\$repo"
|
||||
git worktree remove --force "\$wt"
|
||||
rm -f /tmp/$id.patch
|
||||
}
|
||||
trap cleanup EXIT
|
||||
cd "\$wt"
|
||||
if [ -s /tmp/$id.patch ]; then git apply --binary --index /tmp/$id.patch || exit 4; fi
|
||||
got=\$(git write-tree)
|
||||
if [ "\$got" != "$tree" ]; then echo "트리 해시가 다르다: 원격 \$got, 여기 $tree" >&2; exit 4; fi
|
||||
# 게이트는 깨끗한 HEAD(커밋 식별값 = 트리)를 본다. 훅을 거치지 않는 commit-tree로 이 worktree에만 만든다.
|
||||
commit=\$(git -c user.name=verify -c user.email=verify@localhost commit-tree "\$got" -p HEAD -m "verify $id")
|
||||
git checkout -q --detach "\$commit"
|
||||
mkdir -p "\$(dirname $lock)" "\$logs"
|
||||
: > "\$logs/summary.txt"
|
||||
echo "tree $tree commit \$commit \$(date '+%F %T') load \$(cut -d' ' -f1 /proc/loadavg)" >> "\$logs/summary.txt"
|
||||
if [ $install = 1 ]; then
|
||||
CI=true corepack pnpm install --frozen-lockfile --offline > "\$logs/install.log" 2>&1 \
|
||||
|| CI=true corepack pnpm install --frozen-lockfile >> "\$logs/install.log" 2>&1 \
|
||||
|| { echo "의존성 설치 실패: \$logs/install.log" >&2; exit 4; }
|
||||
fi
|
||||
export VERIFY_SUMMARY="\$logs/summary.txt" VERIFY_STEP_LOGS="\$logs" VERIFY_REF="$ref"
|
||||
flock $lock ./scripts/verify.sh $args 2>&1 | tee "\$logs/run.log"
|
||||
rc=\${PIPESTATUS[0]}
|
||||
git status --porcelain > "\$logs/status-after.txt"
|
||||
git add -A > /dev/null 2>&1
|
||||
git diff --cached --binary HEAD > "\$logs/changes.patch"
|
||||
echo "rc=\$rc" >> "\$logs/summary.txt"
|
||||
exit \$rc
|
||||
EOF
|
||||
if [ "$APPLY_BACK" = 1 ]; then
|
||||
back=$(mktemp)
|
||||
TMP_FILES+=("$back")
|
||||
$ssh "$host" "cat $log_root/$log/changes.patch" > "$back" 2>/dev/null || :
|
||||
if [ ! -s "$back" ]; then
|
||||
echo "verify: 원격에서 바뀐 파일이 없다." >&2
|
||||
elif git apply --binary "$back"; then
|
||||
echo "verify: 원격에서 바뀐 파일 $(grep -c '^diff --git' "$back")개를 이 작업 트리에 얹었다(git status로 본다)." >&2
|
||||
else
|
||||
echo "verify: 원격 변경을 얹지 못했다. 패치는 $host:$log_root/$log/changes.patch" >&2
|
||||
[ "$rc" != 0 ] || rc=4
|
||||
fi
|
||||
fi
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
main() {
|
||||
local stage=${1:-} on="" log="" rest=()
|
||||
[ -n "$stage" ] || usage
|
||||
shift
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--on) on=${2:?--on 뒤에 호스트}; shift 2 ;;
|
||||
--log) log=${2:?--log 뒤에 이름}; shift 2 ;;
|
||||
--dry-run) DRY_RUN=1; shift ;;
|
||||
--apply-back) APPLY_BACK=1; shift ;;
|
||||
--) rest+=("$@"); break ;;
|
||||
-*) usage ;;
|
||||
*) rest+=("$1"); shift ;;
|
||||
esac
|
||||
done
|
||||
check_args "$stage" ${rest[@]+"${rest[@]}"}
|
||||
if [ -z "$on" ]; then
|
||||
if laptop_stage "$stage"; then on=here; else on=${VERIFY_HOST:-desktop}; fi
|
||||
fi
|
||||
if [ "$on" = here ] || [ "$DRY_RUN" = 1 ]; then
|
||||
run_here "$stage" ${rest[@]+"${rest[@]}"}
|
||||
else
|
||||
log=${log:-"$(git branch --show-current | tr '/' '-')-$stage"}
|
||||
run_remote "$on" "${log:-detached}" "$stage" ${rest[@]+"${rest[@]}"}
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Reference in New Issue
Block a user