ci(docs): 문서 지도와 루트 README 절을 문서 검사가 본다

문제: 「모든 문서 폴더가 `docs/README.md` 지도에 있다」와 「루트 README가 정해진 절을
가진다」(design-docs `conventions/docs-system.md` 7절 K5·K6)를 아무것도 지키지 않는다.
테스트 자원 `broken-readme.md`(일부러 깨뜨린 입력)를 살아 있는 문서로 보고 언어 검사
예외에 둔다.

고른 방법: `scripts/check-docs.py`에 검사 둘을 더한다. docs-check workflow가 인자 없이
돌리므로 PR에서 바로 실패로 돈다.
- `map`: `docs/` 바로 아래 폴더가 모두 지도 표의 첫 칸에 있어야 한다. 파일 없이 폴더만
  가진 묶음 폴더(`history/`)는 그 바로 아래 폴더가 대신한다. `.md`가 없는 폴더(스냅숏,
  yaml)도 본다. 지도에 있지만 없는 폴더도 실패다.
- `readme`: 첫 줄 `# 제목`, 그 아래 한 문단, `README_SECTIONS`의 `##` 절이 그 순서로
  있어야 한다. 사이에 다른 절은 있어도 된다.
- 소스 세트 resources 폴더 아래 `.md`(`/src/<세트>/resources/`)는 문서로 보지 않는다.
  그래서 `broken-readme.md` 예외 줄을 지운다.

버린 대안: 지도 폴더를 모든 깊이까지 요구하기. 리뷰 라운드 폴더, 납품 패키지 폴더마다
행이 생겨 지도가 목록이 된다. 절을 정확히 일곱 개만 허용하기. 서비스가 절을 더할 수
없게 된다.

위험·한계: `FROZEN` 지문은 건드리지 않았다. leaf·family README 절 검사(K6 뒷부분)와 파일
이름 규칙·실행 산출물 검사(K5 뒷부분)는 넣지 않았다.

검증:
- `python3 -m unittest discover -s scripts/tests` 65건 rc=0(새 시험 22건).
- 판정 조건 18개를 하나씩 끈 사본마다 자기 시험이 실패했다(rc=1).
- `python3 scripts/check-docs.py` rc=0.
This commit is contained in:
DongHyeonka
2026-11-07 17:18:19 +09:00
parent d8afffce9e
commit f56a100528
3 changed files with 261 additions and 7 deletions
+140 -6
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""문서 검사 넷: 언어, 기록의 머리 블록, 참조, 복사한 숫자. 하나라도 걸리면 rc=1이다.
"""문서 검사 여섯: 언어, 기록의 머리 블록, 참조, 복사한 숫자, 문서 지도, 루트 README 절. 하나라도 걸리면 rc=1이다.
규칙의 정본은 design-docs `conventions/docs-system.md`이고, 이 repo의 적용은 `docs/README.md`
「문서 수명과 언어」다. 이 스크립트는 그 규칙 중 기계로 볼 수 있는 것만 본다.
@@ -15,6 +15,14 @@
registry에 있다. 코드 블록과 「이력」으로 시작하는 인용 블록은 건너뛴다. 마크다운
링크는 lychee와 check-work-docs.py --links가 본다.
number 살아 있는 문서가 정본이 정하는 숫자를 복사하지 않는다: Spring Boot 버전, leaf 개수.
map docs/README.md의 문서 지도가 지금 있는 문서 폴더를 모두 덮는다. 지도는 표의 첫 칸에 적은
`폴더/`다. docs/ 바로 아래 폴더가 대상이고, 파일 없이 폴더만 가진 묶음 폴더(history/)는
그 아래 폴더가 대신한다. 지도에 있지만 없는 폴더도 실패다.
readme 루트 README.md가 정해진 절을 정해진 순서로 가진다: 첫 줄의 제목, 그 아래 한 문단, 그리고
README_SECTIONS의 ## 제목. 그 사이에 다른 절이 있어도 된다.
소스 세트의 resources 폴더 아래 .md(src/**/src/<세트>/resources/)는 시험 입력이나 실행 자원이라 문서로
보지 않는다.
예외 목록(scripts/check-docs-exceptions.txt)은 줄기만 한다.
- 목록의 줄은 아래 FROZEN(2026-11-07 기준선의 지문)에 있어야 한다. 목록에 새 줄을 더하면 실패한다.
@@ -44,7 +52,7 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
EXCEPTIONS_FILE = "scripts/check-docs-exceptions.txt"
REGISTRY_FILE = "src/config/architecture/modules.json"
CHECKS = ("language", "head", "reference", "number")
CHECKS = ("language", "head", "reference", "number", "map", "readme")
# 기록: 본문은 쓴 때의 원문이다. 머리 블록만 고친다. 종류는 폴더가 정한다.
RECORD_KINDS = [
@@ -80,6 +88,16 @@ HEAD_FIELDS = ("상태", "작성일", "요약", "현재 정본")
HEAD_OPTIONAL = ("대체", "대체됨")
HEAD_SEARCH_LINES = 20
# 문서가 아닌 .md: 소스 세트의 resources 폴더 아래 파일은 테스트가 읽는 입력이나 실행 자원이다.
NOT_DOCUMENT = re.compile(r"/src/[A-Za-z]+/resources/")
# 문서 지도(K5)와 루트 README(K6). 절 목록의 정본은 design-docs `conventions/docs-system.md` 6.1절이다.
MAP_FILE = "docs/README.md"
DOCS_ROOT = "docs/"
README_FILE = "README.md"
README_SECTIONS = ("프로젝트 구조", "시작하기", "기능 켜고 끄기", "문서 지도", "검증", "새 서비스로 시작하기",
"규칙과 기여")
# 2026-11-07 기준선. 예외 목록의 줄마다 sha256 앞 16자. 늘리지 않는다(맨 위 설명).
FROZEN: frozenset[str] = frozenset({
"0176963415821bbe", "01984fd96d72b997", "02810bf817c5098f", "02f77e3cc483fa7b", "05fff3c3ff8a5c9a",
@@ -179,15 +197,19 @@ def fingerprint(line: str) -> str:
return hashlib.sha256(line.encode("utf-8")).hexdigest()[:16]
def tracked_markdown(root: Path) -> list[str]:
"""Markdown files git knows or would add: tracked plus untracked files that are not ignored."""
def tracked_files(root: Path, pathspec: str) -> list[str]:
"""Files git knows or would add: tracked plus untracked files that are not ignored."""
result = subprocess.run(
["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "*.md"],
["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", pathspec],
capture_output=True, check=True)
names = {name for name in result.stdout.decode("utf-8").split("\0") if name}
return sorted(name for name in names if (root / name).is_file())
def tracked_markdown(root: Path) -> list[str]:
return [name for name in tracked_files(root, "*.md") if not NOT_DOCUMENT.search(name)]
def record_kind(path: str) -> str | None:
for prefix, kind in RECORD_KINDS:
if path.startswith(prefix):
@@ -485,7 +507,119 @@ def check_number(root: Path, files: list[str]) -> list[Problem]:
return problems
RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number}
def required_folders(paths: list[str]) -> set[str]:
"""지도에 있어야 하는 폴더(`docs/` 기준): docs/ 바로 아래 폴더. 파일 없이 폴더만 가진 묶음 폴더는
그 바로 아래 폴더가 대신한다(history/ → history/plans/ 등). 더 깊이는 내려가지 않는다."""
def children(paths: list[str]) -> dict[str, list[str]]:
found: dict[str, list[str]] = {}
for path in paths:
name, slash, rest = path.partition("/")
if slash:
found.setdefault(name, []).append(rest)
return found
folders: set[str] = set()
for name, inside in children(paths).items():
if any("/" not in path for path in inside):
folders.add(f"{name}/")
else:
folders |= {f"{name}/{child}/" for child in children(inside)}
return folders
def outside_code(lines: list[str]) -> list[tuple[int, str]]:
"""(줄 번호, 줄) — 코드 블록 밖의 줄만."""
kept, fence = [], None
for number, line in enumerate(lines, start=1):
match = FENCE.match(line)
if fence:
if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence):
fence = None
continue
if match:
fence = match.group(1)
continue
kept.append((number, line))
return kept
def map_entries(lines: list[str]) -> list[tuple[int, str]]:
"""(줄 번호, `docs/` 기준 폴더) — 코드 블록 밖 표 행의 첫 칸에 인라인 코드로 적은 `폴더/`."""
entries = []
for number, line in outside_code(lines):
cells = line.strip().split("|")
if not line.strip().startswith("|") or len(cells) < 3:
continue
for found in INLINE.finditer(cells[1]):
token = found.group(0).strip("`").strip()
if token.startswith(DOCS_ROOT):
token = token[len(DOCS_ROOT):]
if token.endswith("/") and not PLACEHOLDER.search(token):
entries.append((number, token))
return entries
def check_map(root: Path, files: list[str]) -> list[Problem]:
del files # 지도는 .md만이 아니라 docs/ 아래 모든 파일의 폴더를 본다(스냅숏·yaml만 있는 폴더도 있다).
if not (root / MAP_FILE).is_file():
return [Problem("map", MAP_FILE, "", "문서 지도가 없다")]
documents = [path[len(DOCS_ROOT):] for path in tracked_files(root, DOCS_ROOT)]
entries = map_entries((root / MAP_FILE).read_text(encoding="utf-8").split("\n"))
mapped = {folder for _, folder in entries}
problems = [Problem("map", MAP_FILE, folder, f"지도에 없는 문서 폴더다: {DOCS_ROOT}{folder}. 지도에 행을 더한다")
for folder in sorted(required_folders(documents) - mapped)]
for number, folder in entries:
if not any(path.startswith(folder) for path in documents):
problems.append(Problem("map", MAP_FILE, folder, f"지도의 폴더가 없다: {DOCS_ROOT}{folder}", number))
return problems
def headings(lines: list[str]) -> list[tuple[int, int, str]]:
"""(줄 번호, 수준, 제목) — 코드 블록 밖의 # 제목."""
found = []
for number, line in outside_code(lines):
heading = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", line)
if heading:
found.append((number, len(heading.group(1)), heading.group(2)))
return found
def check_readme(root: Path, files: list[str]) -> list[Problem]:
del files
def fail(key: str, message: str, line: int = 0) -> None:
problems.append(Problem("readme", README_FILE, key, message, line))
problems: list[Problem] = []
if not (root / README_FILE).is_file():
fail("", "루트 README가 없다")
return problems
lines = (root / README_FILE).read_text(encoding="utf-8").split("\n")
found = headings(lines)
first = next((number for number, line in enumerate(lines, start=1) if line.strip()), 0)
if not found or found[0][:2] != (first, 1):
fail("제목", "첫 줄은 `# 제목`이다", first)
else:
sections = [number for number, level, _ in found if level == 2]
intro = lines[first:sections[0] - 1] if sections else lines[first:]
if not any(line.strip() and not line.lstrip().startswith(("#", "|", "```", "~~~")) for line in intro):
fail("소개", "제목 아래, 첫 ## 절 앞에 무엇인지·누가 쓰나 한 문단을 둔다", first)
positions = {}
for number, level, title in found:
if level == 2 and title in README_SECTIONS and title not in positions:
positions[title] = number
for title in README_SECTIONS:
if title not in positions:
fail(title, f"「## {title}」 절이 없다. 절 목록은 {' → '.join(README_SECTIONS)}다")
present = [title for title in README_SECTIONS if title in positions]
for before, after in zip(present, present[1:]):
if positions[before] > positions[after]:
fail(after, f"「## {after}」 절은 「## {before}」 절 뒤에 온다", positions[after])
return problems
RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number,
"map": check_map, "readme": check_readme}
def read_exceptions(text: str) -> list[str]: