#!/usr/bin/env python3 """ BADA & Knot LLMWiki 지식 무결성 Linter 사용: python3 scripts/lint.py [wiki_path] (기본값: ./wiki) 규약 위반 시 exit 1을 반환합니다. """ import os import re import sys from pathlib import Path TYPES = {"source", "entity", "concept", "note"} REQUIRED_FIELDS = ["type", "created", "updated", "sources"] DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") LINK_RE = re.compile(r"\[\[([^\]|#\n]+?)(?:\|[^\]]*)?\]\]") errors = [] warnings = [] def parse_frontmatter(text): """YAML Frontmatter를 파싱하여 dict로 반환. 형식 오류 시 None.""" lines = text.split("\n") if not lines or lines[0].strip() != "---": return None fm = {} key = None for line in lines[1:]: if line.strip() == "---": return fm if ":" in line: k, _, v = line.partition(":") k = k.strip() v = v.split("#")[0].strip() key = k # 배열 처리 [a, b] if v.startswith("[") and v.endswith("]"): fm[k] = [x.strip().strip("'\"") for x in v[1:-1].split(",") if x.strip()] else: fm[k] = v.strip("'\"") elif key and line.strip().startswith("- "): if not isinstance(fm[key], list): fm[key] = [] fm[key].append(line.strip()[2:].strip().strip("'\"")) return None # 닫는 ---가 없음 def main(): wiki_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("./wiki") if not wiki_path.is_dir(): print(f"🚨 ERROR: wiki 디렉토리를 찾을 수 없습니다: {wiki_path}") return 1 print(f"🔍 Starting LLMWiki Lint check on: {wiki_path.resolve()}") # 1. wiki/ 내의 모든 마크다운 파일 탐색 (Flat 구조 검증) pages = sorted(wiki_path.glob("*.md")) slugs = {p.stem for p in pages} inbound_links = {s: [] for s in slugs} # 2. 개별 파일 분석 및 정합성 검사 for p in pages: if p.name.lower() in ("schema.md", "index.md", "ontology-index.md", "claude.md", "architecture.md", "readme.md"): continue filename = f"wiki/{p.name}" try: text = p.read_text(encoding="utf-8") except Exception as e: errors.append(f"{filename}: 파일 읽기 실패 - {str(e)}") continue # Frontmatter 파싱 fm = parse_frontmatter(text) if fm is None: errors.append(f"{filename}: Frontmatter가 누락되었거나 형식이 불량합니다.") continue # 필수 필드 체크 for field in REQUIRED_FIELDS: if field not in fm: errors.append(f"{filename}: 필수 필드 '{field}'가 Frontmatter에 없습니다.") # 타입 검사 if "type" in fm and fm["type"] not in TYPES: errors.append(f"{filename}: 허용되지 않은 type '{fm['type']}' (허용: {list(TYPES)})") # 날짜 포맷 검사 for date_field in ("created", "updated"): if date_field in fm and not DATE_RE.match(str(fm[date_field])): errors.append(f"{filename}: '{date_field}' 날짜 포맷이 올바르지 않습니다 (YYYY-MM-DD 권장).") # 본문 링크 검사 lines = text.split("\n") for line_num, line in enumerate(lines, 1): for match in LINK_RE.finditer(line): target_slug = match.group(1).strip() # 앵커 링크(#) 제거 후 파일명 슬러그 추출 clean_slug = target_slug.split("#")[0].strip() # notes/ 런 이력 등 외부 폴더 참조 링크 예외 통과 if "/" in clean_slug or clean_slug.startswith(".."): continue # wiki 내부 슬러그 검사 if clean_slug not in slugs: # stub 주석 처리되어 있으면 통과 if "" in line: continue errors.append(f"{filename}:{line_num}: 깨진 링크 [[{target_slug}]] 가 존재합니다 (존재하지 않는 슬러그).") else: inbound_links[clean_slug].append(p.stem) # 3. 고아 노드(Orphan Node) 탐색 (index.md 및 ontology-index.md 제외) for slug, links in inbound_links.items(): if slug in ("index", "ontology-index", "schema"): continue if not links: warnings.append(f"wiki/{slug}.md: 피링크가 없는 고아(Orphan) 지식 노드입니다.") # 4. 검사 결과 출력 print("\n=== Lint Summary ===") print(f"Total processed files: {len(pages)}") print(f"Errors found: {len(errors)}") print(f"Warnings found: {len(warnings)}") if warnings: print("\n⚠️ WARNINGS:") for w in warnings: print(f" - {w}") if errors: print("\n🚨 ERRORS (Lint Failed):") for e in errors: print(f" - {e}") return 1 print("\n✅ LLMWiki Lint PASSED successfully!") return 0 if __name__ == "__main__": sys.exit(main())