Files
document-haness/scripts/verify-project-layout.py
T

599 lines
26 KiB
Python
Executable File

#!/usr/bin/env python3
"""프로젝트 문서 폴더가 같은 모양인지 본다.
프로젝트 하나가 폴더 하나다. 그 안의 배치는 `docs/_templates/` 가 정본이고
CLAUDE.md 「문서 위치」가 같은 것을 말로 적은 것이다.
docs/<프로젝트>/
├── source/ 밖에서 가져온 원본
├── state.json · source-index.md
├── analysis/ · notes/ · checkpoints/
├── final/ SSOT
│ ├── document.md
│ ├── assets/<이름>/ 그림 하나가 폴더 하나. 기록의 assets: file: 도 여기를 가리킨다
│ ├── .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 hashlib
import importlib.util
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__)))
sys.path.insert(0, os.path.join(ROOT, "scripts"))
import techlog # noqa: E402
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"
def _svg_stems(assets: str) -> list[tuple[str, str]]:
"""(stem, 상대경로). 그림은 한 곳에만 산다 — 사본을 두는 폴더를 따로 두지 않는다."""
return [(os.path.basename(path)[:-4], os.path.relpath(path, assets))
for path in sorted(glob.glob(os.path.join(assets, "**", "*.svg"), recursive=True))]
def _load_overlap():
"""`check-figure-overlap.py` 의 검사 함수. 없으면 None."""
path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"check-figure-overlap.py")
if not os.path.exists(path):
return None
spec = importlib.util.spec_from_file_location("check_figure_overlap", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.check
def _context_sha(path: str) -> str | None:
"""`techviz prepare` 가 context 에 적는 것과 같은 해시.
**원본 바이트가 아니다.** prepare 는 문서의 관리 블록(`techviz:begin … end`)을 접은
정규화본을 해싱한다. 원본으로 비교하면 관리 블록이 있는 프로젝트는 그림을 방금 다시
만들어도 영영 「SSOT 가 바뀌었다」로 남는다. 도구가 없으면 대조하지 않는다.
"""
try:
raw = open(path, encoding="utf-8").read()
except OSError:
return None
home = os.environ.get("TECHVIZ_HOME",
"/home/donghyeon/workspace/ai-tool/technical-visualization-haness")
src = os.path.join(home, "src")
if not os.path.isdir(os.path.join(src, "techviz")):
return None
if src not in sys.path:
sys.path.insert(0, src)
try:
from techviz.document import canonicalize_document # noqa: PLC0415
except ImportError:
return None
return hashlib.sha256(canonicalize_document(raw).encode("utf-8")).hexdigest()
TECHVIZ_MANAGED_BLOCK_RE = re.compile(
r"<!-- techviz:begin id=(?P<id>[^\s]+)[^>]*-->.*?"
r"<!-- techviz:end id=(?P=id) -->",
re.DOTALL,
)
def _collapse_techviz_blocks(text: str) -> str:
"""외부 techviz 도구 없이도 context snapshot을 비교할 수 있게 관리 블록을 접는다."""
def replace_block(match):
block = match.group(0)
generated = re.search(r"<!-- techviz:generate id=[^>]+ -->", block)
if generated:
return generated.group(0)
return f"<!-- techviz:generate id={match.group('id')} -->"
return TECHVIZ_MANAGED_BLOCK_RE.sub(replace_block, text)
def _parse_canonical_headings(lines: list[str]) -> list[dict]:
"""TechViz parse_headings와 같은 규칙으로 fence 밖 heading만 읽는다."""
headings: list[dict] = []
in_fence = False
fence_token = ""
for index, line in enumerate(lines, start=1):
stripped = line.lstrip()
if stripped.startswith("```") or stripped.startswith("~~~"):
token = stripped[:3]
if not in_fence:
in_fence = True
fence_token = token
elif token == fence_token:
in_fence = False
fence_token = ""
continue
if in_fence:
continue
match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line)
if match:
headings.append({
"line": index,
"level": len(match.group(1)),
"text": match.group(2).strip(),
})
return headings
def _find_heading_line(headings: list[dict], heading_text: str) -> int | None:
"""TechViz처럼 유일한 exact/casefold heading만 anchor로 인정한다."""
exact = [item for item in headings if item["text"] == heading_text]
if len(exact) == 1:
return int(exact[0]["line"])
if len(exact) > 1:
return None
folded = [
item for item in headings
if item["text"].casefold() == heading_text.casefold()
]
return int(folded[0]["line"]) if len(folded) == 1 else None
def _section_for_line(lines: list[str], headings: list[dict],
line_number: int) -> dict | None:
if line_number < 1 or line_number > max(1, len(lines)):
return None
current = None
for heading in headings:
if heading["line"] <= line_number:
current = heading
else:
break
start_line = int(current["line"]) if current else 1
end_line = len(lines)
if current:
for heading in headings:
if heading["line"] > current["line"] and heading["level"] <= current["level"]:
end_line = int(heading["line"]) - 1
break
elif headings:
end_line = int(headings[0]["line"]) - 1
return {
"heading": current,
"start_line": start_line,
"end_line": end_line,
"text": "\n".join(lines[start_line - 1:end_line]),
}
def _sibling_sections(lines: list[str], headings: list[dict],
current: dict) -> tuple[dict | None, dict | None]:
"""TechViz sibling_sections의 parent-preamble 규칙까지 그대로 재현한다."""
current_heading = current.get("heading")
if current_heading is None:
following = (
_section_for_line(lines, headings, int(headings[0]["line"]))
if headings else None
)
return None, following
same_or_higher = [
item for item in headings
if item["level"] <= current_heading["level"]
]
current_index = next(
(
index for index, item in enumerate(same_or_higher)
if item["line"] == current_heading["line"]
),
None,
)
if current_index is None:
return None, None
previous = None
following = None
if current_index > 0:
previous_heading = same_or_higher[current_index - 1]
previous = _section_for_line(lines, headings, int(previous_heading["line"]))
if previous_heading["level"] < current_heading["level"]:
previous = {
"heading": previous_heading,
"start_line": int(previous_heading["line"]),
"end_line": int(current_heading["line"]) - 1,
"text": "\n".join(
lines[
int(previous_heading["line"]) - 1:
int(current_heading["line"]) - 1
]
),
}
if current_index + 1 < len(same_or_higher):
following = _section_for_line(
lines,
headings,
int(same_or_higher[current_index + 1]["line"]),
)
return previous, following
def _context_anchor_line(lines: list[str], headings: list[dict],
context: dict) -> int | None:
anchor = context.get("anchor") or {}
kind = anchor.get("kind")
value = anchor.get("value")
if kind is None:
# 초기 context snapshot에는 anchor가 없었다. 그 형식도 current heading이
# 유일하면 같은 구조로 재구성할 수 있어야 historical drift를 계속 잡는다.
saved_current = context.get("current_section") or {}
saved_heading = (
saved_current.get("heading")
if isinstance(saved_current, dict) else None
)
title = (
saved_heading.get("text")
if isinstance(saved_heading, dict) else None
)
if isinstance(title, str):
return _find_heading_line(headings, title)
return None
if kind == "heading" and isinstance(value, str):
return _find_heading_line(headings, value)
if kind == "marker" and isinstance(value, str):
marker = re.compile(
rf"<!--\s*techviz:generate\s+id={re.escape(value)}(?:\s+[^>]*)?-->"
)
for index, line in enumerate(lines, start=1):
if marker.search(line):
return index
return None
if kind == "line":
saved_current = context.get("current_section") or {}
saved_heading = (
saved_current.get("heading")
if isinstance(saved_current, dict) else None
)
title = (
saved_heading.get("text")
if isinstance(saved_heading, dict) else None
)
if isinstance(title, str):
found = _find_heading_line(headings, title)
if found is not None:
return found
try:
line_number = int(value)
except (TypeError, ValueError):
return None
return (
line_number
if 1 <= line_number <= max(1, len(lines))
else None
)
return None
def _same_section_snapshot(saved: object, current: object) -> bool:
if saved is None or current is None:
return saved is None and current is None
if not isinstance(saved, dict) or not isinstance(current, dict):
return False
if not isinstance(saved.get("text"), str) or not isinstance(current.get("text"), str):
return False
saved_heading = saved.get("heading")
current_heading = current.get("heading")
if saved_heading is None or current_heading is None:
if saved_heading is not None or current_heading is not None:
return False
elif not isinstance(saved_heading, dict) or not isinstance(current_heading, dict):
return False
else:
if ("level" in saved_heading and
saved_heading.get("level") != current_heading.get("level")):
return False
if ("text" in saved_heading and
saved_heading.get("text") != current_heading.get("text")):
return False
return saved["text"].rstrip() == current["text"].rstrip()
def _context_snapshot_matches(document_path: str, context_path: str) -> bool | None:
"""외부 TechViz 없이도 build_context의 neighboring-section 의미로 snapshot을 대조한다."""
try:
with open(document_path, encoding="utf-8") as handle:
document = handle.read()
with open(context_path, encoding="utf-8") as handle:
context = json.load(handle)
except (OSError, ValueError):
return None
lines = _collapse_techviz_blocks(document).splitlines()
headings = _parse_canonical_headings(lines)
anchor_line = _context_anchor_line(lines, headings, context)
if anchor_line is None:
return None
current = _section_for_line(lines, headings, anchor_line)
if current is None:
return None
previous, following = _sibling_sections(lines, headings, current)
rebuilt = {
"previous_section": previous,
"current_section": current,
"next_section": following,
}
compared = 0
for key in ("previous_section", "current_section", "next_section"):
if key not in context:
continue
compared += 1
if not _same_section_snapshot(context.get(key), rebuilt.get(key)):
return False
return True if compared else None
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))
durable_snapshot = False
index_path = os.path.join(studio, "tech-log-tree.json")
try:
with open(index_path, encoding="utf-8") as handle:
index = json.load(handle)
policy = index.get("sourcePolicy") or {}
durable_snapshot = (
isinstance(policy, dict)
and policy.get("mode") == "DURABLE_IMPORT_SNAPSHOT"
)
except (OSError, ValueError):
durable_snapshot = False
if durable_snapshot:
rep.facts["source"] = (
f"durable import snapshot · source/ {n}개 — exact commit 없는 반입 바이트 보존"
)
else:
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 이 없다")
# ── 그림 ───────────────────────────────────────────────────────
ssot_sha = _context_sha(os.path.join(final, "document.md"))
assets = os.path.join(final, "assets")
techviz = os.path.join(final, ".techviz")
# 정본은 그림 이름 폴더다. .techviz 에 놓인 파일은 정본이 아니다
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()
if os.path.isdir(assets):
sources = techviz_sources
svgs = _svg_stems(assets)
rep.facts["diagrams"] = {"svg": len(svgs), "techviz": len(sources)}
overlap = _load_overlap()
for stem, rel in svgs:
if stem not in sources:
rep.warn("techviz 정본이 없는 그림", f"final/assets/{rel}")
# lint 는 좌표를 안 본다. 상자와 라벨이 서로를 덮는 것은 여기서만 걸린다
if overlap is not None:
for hit in overlap(os.path.join(assets, rel)):
rep.error("그림 안에서 상자와 라벨이 겹친다", f"final/assets/{rel}{hit}")
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}")
# 관계선이 없고 항목마다 같은 수의 details 를 늘어놓았으면 그것은 표다.
# 표는 값을 비교하고 그림은 포함·순서·경계처럼 자리로만 보이는 것을 맡는다
for name in sorted(sources):
spec_path = os.path.join(techviz, name, "spec.json")
if not os.path.exists(spec_path):
continue
try:
spec = json.load(open(spec_path, encoding="utf-8"))
except (ValueError, OSError):
continue
# 그림의 근거는 SSOT 다. 기록은 SSOT 의 인용이라 줄 번호가 근거가 되지 못하는데,
# techviz prepare 는 기록 .md 를 받아도 에러 없이 돈다. 여기서 잡는다
ctx = spec.get("source_context") or {}
doc = os.path.basename(str(ctx.get("document") or ""))
if doc and doc != "document.md":
rep.error("그림의 근거가 SSOT 가 아니다",
f"final/.techviz/{name} — source_context.document = {doc}")
elif ssot_sha and ctx.get("document_sha256") and \
ctx["document_sha256"] != ssot_sha:
rep.warn("SSOT 가 바뀐 뒤 그림을 다시 보지 않았다",
f"final/.techviz/{name}")
elif ssot_sha is None and ctx.get("document_sha256"):
context_path = os.path.join(techviz, name, "context.json")
snapshot_match = _context_snapshot_matches(
os.path.join(final, "document.md"), context_path)
if snapshot_match is False:
rep.warn("SSOT 문맥이 바뀐 뒤 그림을 다시 보지 않았다",
f"final/.techviz/{name} — techviz 도구 없이 context snapshot으로 확인")
elif snapshot_match is True:
rep.warn("그림 전체 SSOT hash를 대조하지 못했다",
f"final/.techviz/{name} — techviz 도구가 없다; context snapshot은 일치")
else:
rep.warn("그림이 어느 SSOT 를 보고 만들어졌는지 대조하지 못했다",
f"final/.techviz/{name} — techviz 도구가 없고 context snapshot도 없다")
nodes = spec.get("nodes") or []
if spec.get("edges") or len(nodes) < 2:
continue
counts = [len(n.get("details") or []) for n in nodes]
if all(counts) and len(set(counts)) == 1:
rep.warn("표로 되는 그림", f"final/.techviz/{name} — 관계선이 없고 "
f"{len(nodes)}항목이 같은 {counts[0]}줄을 늘어놓는다")
# ── 기록이 가리키는 그림 ───────────────────────────────────────
if os.path.isdir(studio):
wrong = 0
broken = 0
records = 0
cited_figures: set[str] = set()
cited_evidence: set[str] = set()
for path in sorted(glob.glob(os.path.join(studio, "*", "*", "*.md"))):
if os.path.basename(os.path.dirname(os.path.dirname(path))).startswith("_"):
continue
records += 1
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)))
stem = (os.path.basename(target)[:-4] if target.endswith(".svg")
else os.path.basename(target))
cited_figures.add(stem)
if not os.path.exists(target):
broken += 1
if broken <= 5:
rep.error("기록이 가리키는 그림이 없다",
f"{os.path.relpath(path, base)}{m.group(1)}")
continue
# 기록이 가리키는 그림도 다시 만들 수 있어야 한다. 사본을 따로 두면 정본이 둘이 된다
if stem not in techviz_sources:
wrong += 1
rep.warn("기록이 가리키는 그림에 techviz 정본이 없다",
f"{os.path.relpath(path, base)}{os.path.basename(target)}")
for m in re.finditer(r"^ - (\.\./\S*final/evidence/\S+)$", text, re.M):
cited_evidence.add(
os.path.normpath(os.path.join(os.path.dirname(path), m.group(1))))
# ── SSOT 가 만들어 둔 것을 기록이 쓰고 있나 ────────────────────
# 기록이 하나도 없는 프로젝트는 아직 안 쓴 것이지 안 쓰기로 한 것이 아니다
if records:
unused_figures = [rel for stem, rel in _svg_stems(assets)
if stem not in cited_figures]
for rel in unused_figures:
rep.warn("기록이 쓰지 않는 SSOT 그림", f"final/assets/{rel}")
unused_evidence = [
p for p in sorted(glob.glob(os.path.join(evidence, "raw", "**", "*"),
recursive=True))
if os.path.isfile(p)
and os.path.basename(p) != "README.txt"
and p not in cited_evidence]
for p_ev in unused_evidence:
rep.warn("기록이 인용하지 않는 raw 증거", os.path.relpath(p_ev, base))
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()
if args.projects:
bad = techlog.check_targets(args.projects, ROOT, "final/document.md")
if bad is not None:
return bad
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())