폴더 지역 규칙은 이제 src/**/AGENTS.md이고 옆의 CLAUDE.md는 `@AGENTS.md` 한 줄이다. 누가 CLAUDE.md에 규칙을 다시 쓰거나, AGENTS.md만 만들고 CLAUDE.md를 빠뜨리면 Claude Code가 그 폴더 규칙을 못 읽거나 규칙이 두 벌이 된다. 그리고 check-work-docs.py에는 자기 시험이 하나도 없었다. - check-work-docs.py: src/**/AGENTS.md마다 옆 CLAUDE.md가 있고, 모든 src/**/CLAUDE.md가 정확히 `@AGENTS.md`이며 옆에 AGENTS.md가 있는지 본다 (build 출력 제외). - scripts/tests/test_check_work_docs.py(13건): 최소 매뉴얼 통과, 지도 41줄· CLAUDE.md 11줄 실패, CLAUDE.md 첫 줄이 가져오기가 아니면 실패, 진입 경로가 네 파일(AGENTS.md + CLAUDE.md + README + playbook) 합인지, 짝 셋, 하위 규칙과 .claude/rules·skills·agents의 이력 ID, 로컬 .claude 상태는 안 봄, 하위 규칙의 깨진 링크. - gates.md 「링크 검사」: lychee 범위 밖 지침 문서는 check-docs.py `link`가 보고, 손으로 돌리는 범위를 src/**/AGENTS.md로 바꿨다. docs/README.md의 검사 설명에서 링크 문법 예를 뺐다(링크 검사기가 링크로 읽었다). 위험: 진입 경로 상한 350은 파일별 상한의 합(40+10+80+150=280)보다 커서 지금 구조에서는 닿지 않는다. 옛 상한(120+80+150=350)도 같았다. 상한은 그대로 두고 시험은 상한을 낮춰 계산식을 본다. 검증: unittest(전체), check-work-docs, check-docs, 같은 범위 --links 모두 rc=0(깨진 링크 0). 조건 다섯(짝 검사, 지도 상한, 진입 경로의 CLAUDE.md, 첫 줄 가져오기, .claude 문서 이력)을 하나씩 끈 사본마다 시험이 1~3건 실패했다.
370 lines
16 KiB
Python
Executable File
370 lines
16 KiB
Python
Executable File
#!/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 rule book) 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 1101/05-01" 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`, and every folder rule book `src/**/AGENTS.md` (owner decision 2026-11-07). Module
|
|
READMEs, design documents and `docs/reviews/**` keep their IDs, because a reader can follow them
|
|
from inside the repository.
|
|
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: vision, map and HARD-STOP only).
|
|
|
|
It also checks that every playbook keeps the shared nine-section skeleton, that the
|
|
"common mistakes" section stays short, that every folder rule book src/**/AGENTS.md has a CLAUDE.md
|
|
beside it that only imports it, and that relative links in the checked files resolve.
|
|
|
|
This lives outside Gradle on purpose: the build does not parse documents.
|
|
|
|
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
|
|
|
|
The --links form is for machines without lychee (the link checker the pull-request workflow runs).
|
|
The --history form applies the same history-ID patterns to documents outside docs/work/.
|
|
"""
|
|
|
|
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/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 = 10
|
|
README_LIMIT = 80
|
|
PLAYBOOK_LIMIT = 150
|
|
ENTRY_PATH_LIMIT = 350
|
|
MISTAKES_LIMIT = 10
|
|
|
|
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 "RR6-01-07과" would otherwise slip through.
|
|
HISTORY_PATTERNS = [
|
|
("review ID with a date prefix (MMDD/...)",
|
|
re.compile(r"(?<![\w./-])(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])/[\w-]", re.ASCII)),
|
|
("review round prefix (RR-, RR2-, ...)", re.compile(r"\bRR\d*-", re.ASCII)),
|
|
("fix bundle name (r2-05a, r9-a, r10-03)", re.compile(r"\br\d{1,2}-(?:\d{2}[a-z]?|[A-Za-z])\b", 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, with no folder date in front:
|
|
# "리뷰 02-01", "1라운드 06-01", "리뷰 README 13.2, 09-02", "review 2026-11-01 05-15". The number
|
|
# must stand alone, so a date such as 2026-11-01 is not a finding number by itself.
|
|
("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, 06-01)", "01-01·07-09". One
|
|
# bare NN-NN stays allowed, because a lone pair is often an ordinary range or chapter number.
|
|
# Line ranges after a colon ("Foo.java:10-12,20-24") are not findings.
|
|
("list of finding numbers (05-01, 04-01)",
|
|
re.compile(r"(?<![\w./:,-])\d{2}-\d{2}(?:, |·)\d{2}-\d{2}(?![\w-])", re.ASCII)),
|
|
("review area number (리뷰 01 영역, 01 영역 5.2절)",
|
|
re.compile(r"리뷰 ?\d{2} ?영역|(?<![\w.])\d{2} ?영역 \d+(?:\.\d+)*절", re.ASCII)),
|
|
# Review-followup fix bundles ran from P1 to P34. P50 and above are left to percentiles (P95).
|
|
("review-followup fix bundle (P30, W3-P30)", re.compile(r"\b(?:W\d-)?P[1-4]\d\b", re.ASCII)),
|
|
# A count of rounds ("2~3라운드 동안", "3라운드마다") is not a name for one past round.
|
|
("round number in Korean (1라운드, 라운드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)),
|
|
("old manual decision number (M-3)", re.compile(r"\bM-\d+\b", re.ASCII)),
|
|
("design decision number (D5)", re.compile(r"\bD\d{1,2}\b", re.ASCII)),
|
|
# Module code reviews before 2026-11 numbered findings per module: MSG-023, BOOT-006, GQL-012.
|
|
("module review finding (MSG-023, BOOT-006)",
|
|
re.compile(r"(?<![\w-])(?:BOOT|MSG|JPA|MNG|GQL|NTF)-\d{3}\b", re.ASCII)),
|
|
# The 2026-09-24 reviews and their follow-up named findings S6-#10a, X2-P1-5, S5-lead-4.
|
|
("review follow-up finding (S6-#10a, X2-P1-5)",
|
|
re.compile(r"\b[SX]\d-(?:#\d+|P\d-\d+|lead-\d+)", re.ASCII)),
|
|
("finding number with its chosen option (03-11 (b))",
|
|
re.compile(r"(?<![\w./:-])\d{2}-\d{2} \([a-e]\)", re.ASCII)),
|
|
("review README section (review README §15)", re.compile(r"review README §", 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)"
|
|
)
|
|
|
|
|
|
SKIPPED_PARTS = {"build", ".gradle", "node_modules"}
|
|
|
|
|
|
def module_guides() -> list[Path]:
|
|
"""Every src/**/AGENTS.md, the local rule book of a leaf or a family, outside build output."""
|
|
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_guide_pairs(errors: list[str]) -> None:
|
|
"""Every folder rule book src/**/AGENTS.md has a CLAUDE.md beside it that only imports it, so Claude
|
|
Code reads the same book when it opens a file there. A CLAUDE.md that holds rules is a second book."""
|
|
for guide in module_guides():
|
|
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")
|
|
|
|
|
|
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 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, 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()
|
|
for path in sorted(WORK.rglob("*.md")):
|
|
if path.relative_to(WORK).as_posix() not in HISTORY_ALLOWED:
|
|
files.append(path)
|
|
return files + module_guides()
|
|
|
|
|
|
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\n2026-11-01 07-10")."""
|
|
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")) + module_guides()
|
|
+ claude_documents())
|
|
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_guide_pairs(errors)
|
|
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())
|