Files
clean-architecture-frontend…/scripts/check-work-docs.py
DongHyeonka d87f6792d5 fix(docs): 드릴이 사본에서만 지우는 시험을 문서가 경로로 적으면 노트북에서 실패한다
문제: 기능 제거 드릴(FE-GATE-020)은 사본에서만 네 시험 파일을 지우고
(scripts/test-sample-removal.ts의 excludedFixtureTest 목록), 사본에서 문서를
두 번 검사한다. 드릴의 documentation 검사와, 사본 test:coverage 안의
tests/unit/documentation-readiness.test.ts가 인자 없이 띄우는
verify:documentation이다. 살아 있는 문서가 그 파일을 경로로 읽히는 자리에
적으면 저장소의 검사는 통과하고 desktop 020에서야 실패했다(#78 때
decisions.md FE-6 행). b6bfc9b7은 docs/operations/adapter-remediation-ledger.md
세 줄에서 백틱을 빼 피했고, 드릴 주석은 그 규칙이 없는
docs/manual/reference/patterns.md를 가리켰다. 지금 규칙(.claude/rules/docs.md)은
「검사를 피하려고 백틱을 빼지 않는다」다.

고른 방법:
- 원장 세 줄(321·348·353)은 폴더와 파일 이름을 따로 백틱으로 적는다
  (`tests/unit/`의 `removal-fixture.test.ts`). 폴더는 경로로 검사되고, `/`가
  없는 이름은 경로로 읽히지 않는다.
- scripts/check-work-docs.py(scripts/verify.sh docs)가 사본의
  verify:documentation과 같은 규칙으로 사본을 그려 보고, 지우는 목록의 파일을
  경로로 읽는 자리가 있으면 file:line으로 실패한다.
  - 드릴: package.json `test:sample-removal`이 마지막에 node로 돌리는 파일.
    목록은 그 파일의 excludedFixtureTest 배열이고 큰따옴표 경로만 받는다.
    목록을 못 찾거나 다른 꼴이면 실패하고, 스크립트가 없으면 건너뛴다.
  - 사본: config/repository-layout.json의 fixture-copy·fixture-documents
    (`sets`와 `setPaths`, selectRepositoryPaths와 같다).
  - 문서: docs/README.md 1절 링크와 살아 있는 문서(docs-system.ts
    checkedForDrift)에서 이력 문서(HISTORY_HOLDERS)를 뺀 것.
  - 읽는 자리: 백틱 span 전체, span과 shell 코드 블록 줄의 명령 인자
    (COMMAND_HEADS, `scripts/verify.sh exec --`, `--flag=`와 따옴표를 뗀다),
    문서 전체의 상대 링크, 기록 문서 머리 블록의 「현재 정본」「대체」「대체됨」.
  - 실패 줄은 그 문서 말고 다른 문서 경로를 적지 않는다. N2 훅
    (scripts/hooks/hooks.py)이 편집한 경로가 든 줄을 고르기 때문이다.
- 이 규칙의 정본은 TypeScript(verify-documentation-readiness.ts,
  docs-system.ts, removal-fixture.ts, repository-layout.ts)다.
  scripts/tests/test_check_work_docs.py의 TypeScriptRulesTest가 그 파일의 목록
  값과 규칙 글자를 읽어 Python 쪽과 대조하고, 한쪽만 바뀌면 실패한다.
- 드릴 주석을 고친다: 사본의 두 문서 검사, 이름을 따로 적는 꼴, 규칙 인용,
  노트북 검사가 드릴과 목록을 찾는 법.

버린 안:
- (A) 드릴이 그 목록을 사본의 문서 검사에만 넘기기(인자): 드릴의
  documentation 검사에는 넘길 수 있지만, 사본 test:coverage 안의
  documentation-readiness 시험은 vitest가 띄워 인자를 받을 길이 없다(vitest에
  값을 넘기는 CLI가 없고, 환경 변수와 파일 표지는 쓰지 않는다). #78 때 020
  로그 37-39행에서도 documentation과 coverage가 둘 다 실패했다. 그 시험이
  목록을 직접 읽게 하면 파생 프로젝트의 merge 단계에서도 그 경로가 검사 밖이
  된다.
- 문서 검사기가 그 목록을 늘 예외로 두기: 같은 이유로 파생 프로젝트에서
  검사가 빠진다.

위험·한계: 노트북 검사는 TS 규칙을 Python으로 다시 쓴다. 어긋남 시험은 목록
값과 규칙을 쓴 글자를 대조하므로, TS를 같은 뜻의 다른 글자로 고쳐 써도
실패한다(실패 쪽). 대조하는 줄 밖에 TS가 새 읽는 자리를 더하면 잡지 못한다.
이름만 적은 span은 검사되지 않는다(그 시험 이름이 바뀌면 문서가 조용히
낡는다).

검증:
- 노트북 RED: 원장 세 줄을 백틱 경로로 둔 트리 f57c9f5c에서 check-work-docs
  rc=1(:321·:348·:353). decisions.md:76에 FE-6 행 꼴 경로를 넣으면 rc=1
  (decisions.md:76).
- desktop RED: 트리 f57c9f5c에서 FE-GATE-020 rc=1(documentation과 coverage,
  #78과 같은 실패).
- 시험: 첫 리뷰 반영 시험(21개)을 1204e2b7 검사기로 돌리면 18 failed·
  2 errors. 확인 리뷰 반영 뒤 이 커밋에서 22 OK.
- 변이, 모두 이 시험이 실패한다(괄호는 failures, 시험 22개). 검사기:
  `--flag=`·따옴표 떼기 제거(5), 링크 줄 단위(2), setPaths 무시(1), 머리
  블록 안 읽음(6), 목록 꼴 검사 제거(2), fixture-copy 뺌(20),
  LIVING_IN_RECORDS 비움(2), NOT_DOCUMENT 무력화(1), fence 언어 무시(1),
  문서 옆 폴더 분기 제거(1), 실패 줄 권고에 원장 경로(20). TS:
  COMMAND_HEADS에 deno(1), FLAG 정규식(1), RECORD_FOLDERS에 폴더(1). 변이
  없이 22 OK. subtest가 고친 파일을 되돌리지 않게 한 시험에 fence 변이를
  겹치면 실패 1이 7로 번진다(고친 시험은 1).
- scripts/verify.sh docs rc=0, hooks rc=0.
2026-11-21 04:02:51 +09:00

621 lines
29 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 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.
One check is about the feature removal drill (FE-GATE-020, desktop): the drill deletes a few tests
from its copy only (the list in `scripts/test-sample-removal.ts`) and runs `verify:documentation`
there. A document the drill copies that names one of them where that check reads paths (a backtick
path, a command word, a link, a record's head block) fails that gate, so it fails here first with
its line. The rules for what the copy holds and reads are TypeScript; this file repeats them, and
`TypeScriptRulesTest` in `scripts/tests/test_check_work_docs.py` fails when the two drift apart.
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 json
import posixpath
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)
# --- The removal drill's copy (FE-GATE-020). Each group repeats the TypeScript file named above it;
# TypeScriptRulesTest (scripts/tests/test_check_work_docs.py) reads those files and fails on a change
# made to one side only.
PACKAGE = REPO_ROOT / "package.json"
# The drill is the last file the package script runs with node (it first generates the feature index).
DRILL_SCRIPT = "test:sample-removal"
DRILL_RUNS = re.compile(r"\bnode\s+(\S+)")
# scripts/test-sample-removal.ts. The drill has other loops over array literals; this one is found by
# its variable, and it may hold only double-quoted paths.
DRILL_DELETIONS = re.compile(r"for \(const excludedFixtureTest of \[([^\]]*)\]\)")
DRILL_LIST = re.compile(r'\s*(?:"[^"\\\n]*"\s*,\s*)*(?:"[^"\\\n]*"\s*,?\s*)?')
DRILL_ITEM = re.compile(r'"([^"\\\n]*)"')
# scripts/lib/removal-fixture.ts (what prepareRemovalFixture copies) and scripts/lib/repository-layout.ts
# (selectRepositoryPaths: an entry in the set, or the entry's setPaths for it).
LAYOUT = REPO_ROOT / "config/repository-layout.json"
COPIED_SETS = ("fixture-copy", "fixture-documents")
# scripts/lib/docs-system.ts: which documents are living, which are records, and a record's head block.
RECORD_FOLDERS = ("docs/design/", "docs/history/", "docs/reviews/")
DECISION_FOLDER = "docs/adr/"
LIVING_IN_RECORDS = frozenset({"docs/reviews/adapters/INVENTORY.md"})
HISTORY_HOLDERS = frozenset({"CHANGELOG.md", "docs/architecture/review-evidence.md", "docs/work/evidence.md"})
NOT_DOCUMENT = re.compile(r"^docs\/accessibility\/route-reviews\/")
RECORD_KINDS = ("docs/design/", "docs/history/plans/", "docs/history/evidence/", "docs/history/packages/",
"docs/history/study/", "docs/adr/")
HEAD_START = "<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->"
HEAD_END = "<!-- 머리 블록 끝 -->"
HEAD_SEARCH_LINES = 20
HEAD_FIELD = re.compile(r"^- ([^:]+): (.+)$")
HEAD_CANONICAL = "현재 정본"
HEAD_OPTIONAL = ("대체", "대체됨")
HEAD_PATH = re.compile(r"`([^`]+)`")
# scripts/verify-documentation-readiness.ts: the documents it reads (the index's first section and the
# living documents) and where it reads paths in them.
DOCUMENT_INDEX = "docs/README.md"
INDEX_SECTION = re.compile(r"^## 1\.[\s\S]*?(?=^## )", re.MULTILINE)
INDEX_LINK = re.compile(r"\]\(([^)#\s]+)\)")
SPAN = re.compile(r"`([^`\n]+)`")
DOCUMENT_LINK = re.compile(r"\]\(([^)\s]+)\)")
ANCHOR = re.compile(r"#.*$")
LINE_NUMBER = re.compile(r":\d[\d,:-]*$")
NOT_A_PATH = re.compile(r"[\s*<>{}$()|…]|\.\.\.")
OUTSIDE_LINK = re.compile(r"^(?:[a-z][a-z+.-]*:|#)", re.IGNORECASE)
COMMAND_HEADS = frozenset({"corepack", "pnpm", "npx", "node", "vitest", "playwright", "tsc", "eslint", "bash", "sh",
"python3"})
VERIFY_ENTRY = re.compile(r"^(?:\.\/)?scripts\/verify\.sh$")
PROMPT = re.compile(r"^\$\s+")
ASSIGNMENT = re.compile(r"^[A-Z_][A-Z0-9_]*=")
FLAG = re.compile(r"^--?[\w.-]+=", re.ASCII)
QUOTES = re.compile(r"""^["']|["']$""")
FENCE = re.compile(r"^\s*```(\w*)", re.ASCII)
SHELL_FENCE = re.compile(r"^(?:bash|sh|shell|console|zsh)?$")
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 drill_file(errors: list[str]) -> Path | None:
"""The drill the package script runs; none where a project removed it."""
if not PACKAGE.exists():
return None
script = json.loads(PACKAGE.read_text(encoding="utf-8")).get("scripts", {}).get(DRILL_SCRIPT)
if script is None:
return None
runs = DRILL_RUNS.findall(script)
if not runs or not (REPO_ROOT / runs[-1]).is_file():
errors.append(f"{rel(PACKAGE)}: `{DRILL_SCRIPT}` runs no drill file this check can read: {script!r}")
return None
return REPO_ROOT / runs[-1]
def drill_copy_only_deletions(errors: list[str]) -> tuple[Path | None, list[str]]:
"""The drill and the files it deletes from its copy only."""
drill = drill_file(errors)
if drill is None:
return None, []
match = DRILL_DELETIONS.search(drill.read_text(encoding="utf-8"))
if match is None:
errors.append(f"{rel(drill)}: the list of files the drill deletes from its copy was not found")
return drill, []
if not DRILL_LIST.fullmatch(match.group(1)):
errors.append(f"{rel(drill)}: the list of files the drill deletes from its copy holds more than"
" double-quoted paths, so this check cannot read it")
return drill, []
return drill, DRILL_ITEM.findall(match.group(1))
class DrillCopy:
"""What the drill's copy holds: the paths the layout's copied sets select, less its deletions."""
def __init__(self, targets: list[str], deleted: list[str]) -> None:
self.targets = [target for target in dict.fromkeys(targets) if (REPO_ROOT / target).exists()]
self.deleted = set(deleted)
self.top_level = {target.split("/")[0] for target in self.targets}
def has(self, path: str) -> bool:
return (path not in self.deleted and (REPO_ROOT / path).exists()
and any(path == target or path.startswith(f"{target}/") or target.startswith(f"{path}/")
for target in self.targets))
def documents(self) -> list[str]:
"""The copy's markdown files, as docs-system.ts readDocuments reads them."""
found = set()
for target in self.targets:
source = REPO_ROOT / target
for path in sorted(source.rglob("*.md")) if source.is_dir() else [source]:
name = rel(path)
if (name.endswith(".md") and path.is_file() and not SKIPPED_PARTS & set(Path(name).parts)
and not NOT_DOCUMENT.search(name)):
found.add(name)
return sorted(found)
def checked(self) -> list[str]:
"""The documents whose named paths the copy's verify:documentation checks."""
index = (REPO_ROOT / DOCUMENT_INDEX).read_text(encoding="utf-8") if self.has(DOCUMENT_INDEX) else ""
section = INDEX_SECTION.search(index)
named = {DOCUMENT_INDEX}
for target in INDEX_LINK.findall(section.group(0) if section else ""):
linked = posixpath.normpath(f"{posixpath.dirname(DOCUMENT_INDEX)}/{target}")
if (REPO_ROOT / linked).is_dir():
named.update(f"{linked}/{entry.name}" for entry in (REPO_ROOT / linked).iterdir()
if entry.name.endswith(".md"))
else:
named.add(linked)
named.update(path for path in self.documents() if checked_for_drift(path))
return sorted(path for path in named if path not in HISTORY_HOLDERS and self.has(path)
and (REPO_ROOT / path).is_file())
def records(self) -> list[str]:
"""The documents whose head block the copy's docs-system check reads."""
return [path for path in self.documents() if path.startswith(RECORD_KINDS)]
def checked_for_drift(path: str) -> bool:
living = path in LIVING_IN_RECORDS or not path.startswith(RECORD_FOLDERS)
return living and not path.startswith(DECISION_FOLDER) and path not in HISTORY_HOLDERS
def drill_copy(errors: list[str], deleted: list[str]) -> DrillCopy | None:
if not LAYOUT.exists():
errors.append(f"{rel(LAYOUT)}: missing (it lists what the removal drill copies)")
return None
targets = []
for entry in json.loads(LAYOUT.read_text(encoding="utf-8"))["entries"]:
for name in COPIED_SETS:
targets += [entry["path"]] if name in entry.get("sets", []) else entry.get("setPaths", {}).get(name, [])
return DrillCopy(targets, deleted)
def named_path(token: str, document: str, copy: DrillCopy) -> str | None:
"""A backtick span or a command word read as a path, as namedPath reads it; none for a paired repository."""
candidate = LINE_NUMBER.sub("", ANCHOR.sub("", token, count=1), count=1)
if "/" not in candidate or candidate.startswith("/") or NOT_A_PATH.search(candidate):
return None
first = candidate.split("/")[0]
if first in copy.top_level:
return candidate
beside = posixpath.dirname(document) or "."
if first not in (".", "..") and copy.has(posixpath.normpath(f"{beside}/{first}")):
return posixpath.normpath(f"{beside}/{candidate}")
return None
def linked_path(target: str, document: str) -> str | None:
if OUTSIDE_LINK.search(target):
return None
return posixpath.normpath(f"{posixpath.dirname(document) or '.'}/{ANCHOR.sub('', target, count=1)}")
def command_paths(command: str, document: str, copy: DrillCopy) -> list[str | None]:
"""The paths a command takes, as commandPaths reads them."""
words = PROMPT.sub("", command.strip(), count=1).split() or [""]
head = 0
while head < len(words) and ASSIGNMENT.search(words[head]):
head += 1
first = words[head] if head < len(words) else ""
if VERIFY_ENTRY.search(first):
separator = words.index("--", head + 1) if "--" in words[head + 1:] else -1
executed = (" ".join(words[separator + 1:])
if words[head + 1:head + 2] == ["exec"] and separator > head else "")
return [named_path(first, document, copy), *(command_paths(executed, document, copy) if executed else [])]
if first not in COMMAND_HEADS:
return []
return [named_path(QUOTES.sub("", FLAG.sub("", word, count=1)), document, copy) for word in words[head + 1:]]
def fenced_commands(text: str) -> list[tuple[int, str]]:
"""The lines of shell blocks, as fencedCommands reads them, with their line numbers."""
commands = []
fence = None
for number, line in enumerate(text.split("\n"), start=1):
marker = FENCE.search(line)
if marker:
fence = marker.group(1) if fence is None else None
continue
if fence is not None and SHELL_FENCE.search(fence):
commands.append((number, line))
return commands
def head_paths(text: str) -> list[tuple[int, str]]:
"""The paths a record's head block names in 「현재 정본」 and the optional fields, as checkHead reads them."""
lines = text.split("\n")
if lines[0] != HEAD_START or HEAD_END not in lines[:HEAD_SEARCH_LINES]:
return []
fields: dict[str, tuple[int, str]] = {}
for number, line in enumerate(lines[2:lines.index(HEAD_END)], start=3):
match = HEAD_FIELD.search(line)
if match and match.group(1).strip() not in fields:
fields[match.group(1).strip()] = (number, match.group(2).strip())
return [(fields[name][0], target) for name in (HEAD_CANONICAL, *HEAD_OPTIONAL) if name in fields
for target in HEAD_PATH.findall(fields[name][1])]
def drill_copy_hits(copy: DrillCopy) -> list[tuple[str, int, str]]:
"""(document, line, deleted file) where the copy's verify:documentation reads a path the copy lacks."""
hits = set()
def add(document: str, number: int, found: str | None) -> None:
name = posixpath.normpath(found) if found else None
if name in copy.deleted:
hits.add((document, number, name))
for document in copy.checked():
text = (REPO_ROOT / document).read_text(encoding="utf-8")
def line(offset: int) -> int:
return text.count("\n", 0, offset) + 1
for match in SPAN.finditer(text):
for found in (named_path(match.group(1), document, copy), *command_paths(match.group(1), document, copy)):
add(document, line(match.start()), found)
for number, command in fenced_commands(text):
for found in command_paths(command, document, copy):
add(document, number, found)
for match in DOCUMENT_LINK.finditer(text):
add(document, line(match.start()), linked_path(match.group(1), document))
for record in copy.records():
for number, target in head_paths((REPO_ROOT / record).read_text(encoding="utf-8")):
add(record, number, target)
return sorted(hits)
def check_drill_copy(errors: list[str], report: list[str]) -> None:
drill, deleted = drill_copy_only_deletions(errors)
copy = drill_copy(errors, deleted) if drill and deleted else None
if drill is None or copy is None:
return
for document, number, name in drill_copy_hits(copy):
folder, _, file = name.rpartition("/")
advice = ("Name a file the drill keeps" if document.startswith(RECORD_KINDS)
else f"Name the folder and the file apart: `{folder}/`의 `{file}`")
errors.append(f"{document}:{number}: '{name}' - the removal drill deletes it from its copy ({rel(drill)}),"
f" so the copy's verify:documentation fails FE-GATE-020. {advice}")
report.append(f"documents the removal drill copies, checked for its copy-only deletions: {len(copy.checked())},"
f" record head blocks: {len(copy.records())}")
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)
check_drill_copy(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())