#!/usr/bin/env python3 """프로젝트 문서 폴더가 같은 모양인지 본다. 프로젝트 하나가 폴더 하나다. 그 안의 배치는 `docs/_templates/` 가 정본이고 CLAUDE.md 「문서 위치」가 같은 것을 말로 적은 것이다. docs/<프로젝트>/ ├── source/ 밖에서 가져온 원본 ├── state.json · source-index.md ├── analysis/ · notes/ · checkpoints/ ├── final/ SSOT │ ├── document.md │ ├── assets/<이름>/ 그림 하나가 폴더 하나 │ ├── assets/tech-log-studio/ Studio 에 올릴 표현물 │ ├── .techviz/<이름>/ 그림의 정본 │ └── evidence/{raw,meta,rendered,browser} └── tech-log-studio/ python3 scripts/verify-project-layout.py [프로젝트 ...] [--strict] [--samples N] **SVG 는 정본이 아니다.** `.techviz/<이름>/` 없이 남은 그림은 다시 만들 수 없다. 이 검사기는 그것을 세지만 실패로 만들지는 않는다 — 언제 다시 만들지는 편집 판단이다. """ from __future__ import annotations import argparse import glob import json import os import re import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from techlog import Report # noqa: E402 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EVIDENCE_DIRS = {"raw", "meta", "rendered", "browser"} # 분석하는 동안에만 있는 작업 재료. 분석이 끝나면 final/document.md 로 합치고 지운다. # 끝난 프로젝트의 폴더는 final/ 과 tech-log-studio/ (밖에서 가져왔으면 source/) 뿐이다 WORKING_MATERIAL = ("analysis", "notes", "checkpoints", "state.json", "source-index.md") # 밖에서 가져올 때만 있는 재료. final/ 이 그 내용을 담으면 원본은 사본이 된다 IMPORT_MATERIAL = "source" # Studio 에 올릴 표현물이 사는 곳. 여기 SVG 는 그림의 정본을 따로 갖지 않는다 STUDIO_ASSETS = "tech-log-studio" def _svg_stems(assets: str) -> list[tuple[str, str]]: """(stem, 상대경로). assets/tech-log-studio/ 아래는 표현물이라 뺀다.""" out = [] for path in sorted(glob.glob(os.path.join(assets, "**", "*.svg"), recursive=True)): rel = os.path.relpath(path, assets) if rel.split(os.sep)[0] == STUDIO_ASSETS: continue out.append((os.path.basename(path)[:-4], rel)) return out def verify(project: str) -> Report: rep = Report(project) base = os.path.join(ROOT, "docs", project) final = os.path.join(base, "final") studio = os.path.join(base, "tech-log-studio") # ── SSOT ─────────────────────────────────────────────────────── if not os.path.exists(os.path.join(final, "document.md")): rep.error("final/document.md 가 없다", project) return rep # ── 분석 작업 재료 ───────────────────────────────────────────── # 분석 중이면 있어야 하고, 끝났으면 final 로 합치고 없어야 한다 left = [n for n in WORKING_MATERIAL if os.path.exists(os.path.join(base, n))] status = None state_path = os.path.join(base, "state.json") if os.path.exists(state_path): try: status = json.load(open(state_path, encoding="utf-8")).get("analysisStatus") except (json.JSONDecodeError, OSError): rep.error("state.json 을 읽지 못했다", project) if os.path.isdir(os.path.join(base, "analysis")): for name in ("state.json", "source-index.md"): if not os.path.exists(os.path.join(base, name)): rep.error(f"analysis/ 가 있는데 {name} 이 없다", project) if left: rep.facts["analysis"] = status or "진행 중" if status == "COMPLETE": rep.warn("분석이 끝났는데 작업 재료가 남아 있다", f"{' · '.join(left)} — final/document.md 로 합치고 지운다") imported = os.path.join(base, IMPORT_MATERIAL) if os.path.isdir(imported): n = sum(1 for _ in glob.iglob(os.path.join(imported, "**", "*"), recursive=True)) rep.warn("반입 원본이 남아 있다", f"source/ {n}개 — final/ 이 그 내용을 담고 있으면 사본이다") # ── 증거 ─────────────────────────────────────────────────────── evidence = os.path.join(final, "evidence") if os.path.isdir(evidence): for name in sorted(os.listdir(evidence)): if os.path.isdir(os.path.join(evidence, name)) and name not in EVIDENCE_DIRS: rep.error("evidence 하위 폴더 이름이 규약 밖이다", f"final/evidence/{name} — raw · meta · rendered · browser") raw = os.path.join(evidence, "raw") counts = {} for name in EVIDENCE_DIRS: d = os.path.join(evidence, name) counts[name] = len(glob.glob(os.path.join(d, "**", "*"), recursive=True)) \ if os.path.isdir(d) else 0 rep.facts["evidence"] = counts # 6개월 뒤에 파일 이름만으로는 못 읽는다 for d in sorted(glob.glob(os.path.join(raw, "*"))): if os.path.isdir(d) and not os.path.exists(os.path.join(d, "README.txt")): rep.warn("evidence/raw 하위 폴더에 README.txt 가 없다", os.path.relpath(d, base)) if counts.get("rendered") and not counts.get("meta"): rep.error("터미널 SVG 는 있는데 meta 가 없다", "실행한 명령의 원문과 메타데이터가 정본이다") elif counts.get("raw") and not counts.get("meta"): rep.warn("raw 는 있는데 meta 가 없다", f"raw {counts['raw']}건 — command·cwd·executedAt·exitCode·revision 이 없다") # ── 그림 ─────────────────────────────────────────────────────── assets = os.path.join(final, "assets") techviz = os.path.join(final, ".techviz") if os.path.isdir(assets): # 정본은 그림 이름 폴더다. .techviz 에 놓인 파일은 정본이 아니다 sources = {n for n in os.listdir(techviz) if os.path.isdir(os.path.join(techviz, n))} \ if os.path.isdir(techviz) else set() svgs = _svg_stems(assets) rep.facts["diagrams"] = {"svg": len(svgs), "techviz": len(sources)} for stem, rel in svgs: if stem not in sources: rep.warn("techviz 정본이 없는 그림", f"final/assets/{rel}") if os.path.dirname(rel) in ("", "diagrams"): rep.warn("그림이 이름 폴더로 묶여 있지 않다", f"final/assets/{rel}") stems = {s for s, _ in svgs} for name in sorted(sources - stems): rep.warn("정본만 있고 그림이 없다", f"final/.techviz/{name}") # ── 기록이 가리키는 그림 ─────────────────────────────────────── if os.path.isdir(studio): wrong = 0 broken = 0 for path in sorted(glob.glob(os.path.join(studio, "*", "*", "*.md"))): if os.path.basename(os.path.dirname(os.path.dirname(path))).startswith("_"): continue text = open(path, encoding="utf-8").read() for m in re.finditer(r"^ file: (\S+)$", text, re.M): target = os.path.normpath(os.path.join(os.path.dirname(path), m.group(1))) if not os.path.exists(target): broken += 1 if broken <= 5: rep.error("기록이 가리키는 그림이 없다", f"{os.path.relpath(path, base)} — {m.group(1)}") continue if f"assets{os.sep}{STUDIO_ASSETS}{os.sep}" not in target: wrong += 1 if wrong: rep.warn("Studio 자산이 assets/tech-log-studio/ 밖에 있다", f"{wrong}건 — 다른 프로젝트는 전부 그 폴더를 쓴다") return rep def render(rep: Report, samples: int) -> None: facts = " · ".join(f"{k}={json.dumps(v, ensure_ascii=False) if isinstance(v, dict) else v}" for k, v in rep.facts.items()) print(f" [{rep.project}] {facts or '—'}") for label, bucket, mark in (("error", rep.errors, "✗"), ("warn", rep.warns, "!")): for rule, details in sorted(bucket.items(), key=lambda kv: -len(kv[1])): print(f" {mark} {label} {len(details):>4} {rule}") for d in details[:samples]: if d: print(f" · {d}") if samples and len(details) > samples: print(f" … 외 {len(details) - samples}건") def main() -> int: ap = argparse.ArgumentParser(description="프로젝트 문서 폴더 배치를 본다.") ap.add_argument("projects", nargs="*") ap.add_argument("--samples", type=int, default=3) ap.add_argument("--strict", action="store_true") args = ap.parse_args() projects = args.projects or sorted( name for name in ( os.path.basename(os.path.dirname(os.path.dirname(p))) for p in glob.glob(os.path.join(ROOT, "docs/*/final/document.md")) ) if not name.startswith("_") ) reports = [verify(p) for p in projects] e = sum(r.error_count for r in reports) w = sum(r.warn_count for r in reports) print(f"PROJECT LAYOUT: {'FAIL' if e or (args.strict and w) else 'PASS'}" f" — 프로젝트 {len(reports)} · error {e} · warn {w}") for r in reports: render(r, args.samples) return 1 if e or (args.strict and w) else 0 if __name__ == "__main__": raise SystemExit(main())