#!/usr/bin/env python3 """Check project-owned Markdown links, language docs, routes, and imports.""" from __future__ import annotations import argparse import os import re import sys from pathlib import Path from urllib.parse import unquote, urlsplit IGNORED_DIRS = { ".git", ".next", ".pnpm-store", ".pytest_cache", ".ruff_cache", ".mypy_cache", "__pycache__", "bin", "build", "coverage", "dist", "node_modules", "site-packages", "target", "vendor", "venv", } LANGUAGE_DOCS = {"ARCHITECTURE.md", "DEPLOY.md", "DEVELOPMENT.md", "TESTING.md"} INLINE_LINK = re.compile( r"!?\[[^\]]*\]\(\s*(<[^>]+>|(?:\\.|[^\s)])+)(?:\s+[^)]*)?\)" ) REFERENCE_LINK = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)") IMPORT = re.compile(r"^\s*@([^\s]+\.md)\s*$") ROUTE_TARGET = re.compile(r"\.agents/[A-Za-z0-9_./-]+\.md") FENCE = re.compile(r"^\s{0,3}(`{3,}|~{3,})") HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$") HTML_ID = re.compile(r"\bid\s*=\s*['\"]([^'\"]+)['\"]", re.IGNORECASE) def markdown_files(root: Path) -> list[Path]: found: list[Path] = [] for current, directories, filenames in os.walk(root): directories[:] = sorted( name for name in directories if name not in IGNORED_DIRS and not name.startswith(".venv") and not (Path(current) / name).is_symlink() ) for filename in filenames: path = Path(current) / filename if path.suffix.lower() == ".md" and not path.is_symlink(): found.append(path.resolve()) return sorted(found) def visible_lines(markdown: str) -> list[tuple[int, str]]: """Return source lines outside fenced code blocks, preserving line numbers.""" result: list[tuple[int, str]] = [] fence_char: str | None = None fence_size = 0 for number, line in enumerate(markdown.splitlines(), start=1): match = FENCE.match(line) if match: marker = match.group(1) if fence_char is None: fence_char, fence_size = marker[0], len(marker) elif marker[0] == fence_char and len(marker) >= fence_size: fence_char, fence_size = None, 0 continue if fence_char is None: result.append((number, line)) return result def destination_value(raw: str) -> str: value = raw.strip() if value.startswith("<") and value.endswith(">"): value = value[1:-1] return value.replace("\\ ", " ") def without_code_spans(line: str) -> str: output: list[str] = [] index = 0 while index < len(line): if line[index] != "`": output.append(line[index]) index += 1 continue end_run = index while end_run < len(line) and line[end_run] == "`": end_run += 1 delimiter = line[index:end_run] close = line.find(delimiter, end_run) if close < 0: output.append(delimiter) index = end_run continue output.append(" ") index = close + len(delimiter) return "".join(output) def heading_anchors(markdown: str) -> set[str]: anchors: set[str] = set() occurrences: dict[str, int] = {} for _, line in visible_lines(markdown): for explicit in HTML_ID.findall(line): anchors.add(explicit) match = HEADING.match(line) if not match: continue title = re.sub(r"`([^`]*)`", r"\1", match.group(1)) title = re.sub(r"!?\[([^\]]*)\]\([^)]*\)", r"\1", title) slug = re.sub(r"[^\w -]", "", title.lower(), flags=re.UNICODE) slug = re.sub(r"\s+", "-", slug.strip()) occurrence = occurrences.get(slug, 0) occurrences[slug] = occurrence + 1 anchors.add(slug if occurrence == 0 else f"{slug}-{occurrence}") return anchors def is_external(destination: str) -> bool: parsed = urlsplit(destination) return bool(parsed.scheme or parsed.netloc) def check_link( source: Path, line_number: int, destination: str, root: Path, errors: list[str], ) -> None: destination = destination_value(destination) if not destination or is_external(destination): return parsed = urlsplit(destination) relative = unquote(parsed.path) target = (source.parent / relative).resolve() if relative else source.resolve() try: target.relative_to(root.resolve()) except ValueError: errors.append(f"{source.relative_to(root)}:{line_number}: local link escapes the repository: {destination}") return if not target.exists(): errors.append(f"{source.relative_to(root)}:{line_number}: broken local link: {destination}") return if parsed.fragment and target.is_file() and target.suffix.lower() == ".md": fragment = unquote(parsed.fragment) if fragment not in heading_anchors(target.read_text(encoding="utf-8")): errors.append( f"{source.relative_to(root)}:{line_number}: missing Markdown anchor #{fragment} in " f"{target.relative_to(root)}" ) def check_language_docs(root: Path, errors: list[str]) -> None: names: dict[str, set[str]] = {} for language in ("ru", "en"): directory = root / "docs" / language if not directory.is_dir(): errors.append(f"missing documentation directory: docs/{language}") continue actual = {path.name for path in directory.glob("*.md") if path.is_file()} names[language] = actual missing = sorted(LANGUAGE_DOCS - actual) if missing: errors.append(f"docs/{language} is missing required files: {', '.join(missing)}") if "ru" in names and "en" in names and names["ru"] != names["en"]: missing_en = sorted(names["ru"] - names["en"]) missing_ru = sorted(names["en"] - names["ru"]) details = [] if missing_en: details.append("missing in docs/en: " + ", ".join(missing_en)) if missing_ru: details.append("missing in docs/ru: " + ", ".join(missing_ru)) errors.append("docs/ru and docs/en filenames do not match: " + "; ".join(details)) def check_root_readme(files: list[Path], root: Path, errors: list[str]) -> None: expected = (root / "README.md").resolve() if not expected.is_file(): errors.append("missing root README.md") nested = [path for path in files if path.name.lower() == "readme.md" and path != expected] for path in nested: errors.append(f"nested README is not allowed: {path.relative_to(root)}") for name in ("AGENTS.md", "CLAUDE.md", "AGENTS_ROUTING.md"): if not (root / name).is_file(): errors.append(f"missing root {name}") old_architecture = root / "architecture.md" if old_architecture.exists(): errors.append("obsolete root architecture.md remains; keep architecture in docs/ru/ARCHITECTURE.md") def check_routes(root: Path, source: Path, markdown: str, errors: list[str]) -> None: for line_number, line in visible_lines(markdown): for target in ROUTE_TARGET.findall(line): if not (root / target).is_file(): errors.append(f"{source.relative_to(root)}:{line_number}: missing route target: {target}") def check_imports(root: Path, files: list[Path], errors: list[str]) -> None: graph: dict[Path, list[Path]] = {path: [] for path in files} for source in files: text = source.read_text(encoding="utf-8") for line_number, line in visible_lines(text): match = IMPORT.match(line) if not match: continue imported = (source.parent / match.group(1)).resolve() try: imported.relative_to(root.resolve()) except ValueError: errors.append(f"{source.relative_to(root)}:{line_number}: instruction import escapes repository") continue if not imported.is_file(): errors.append( f"{source.relative_to(root)}:{line_number}: missing instruction import: {match.group(1)}" ) continue graph[source].append(imported) state: dict[Path, int] = {} stack: list[Path] = [] def visit(node: Path) -> None: state[node] = 1 stack.append(node) for child in graph.get(node, []): if state.get(child) == 1: cycle = stack[stack.index(child) :] + [child] display = " -> ".join(path.relative_to(root).as_posix() for path in cycle) errors.append(f"instruction import cycle: {display}") elif state.get(child, 0) == 0: visit(child) stack.pop() state[node] = 2 for node in graph: if state.get(node, 0) == 0: visit(node) def validate_repository(root: Path) -> list[str]: root = root.resolve() errors: list[str] = [] files = markdown_files(root) check_root_readme(files, root, errors) check_language_docs(root, errors) routing = root / "AGENTS_ROUTING.md" if not routing.is_file(): errors.append("missing root AGENTS_ROUTING.md") else: check_routes(root, routing, routing.read_text(encoding="utf-8"), errors) for source in files: text = source.read_text(encoding="utf-8") for line_number, line in visible_lines(text): line_without_code = without_code_spans(line) for match in INLINE_LINK.finditer(line_without_code): check_link(source, line_number, match.group(1), root, errors) match = REFERENCE_LINK.match(line_without_code) if match: check_link(source, line_number, match.group(1), root, errors) check_imports(root, files, errors) return errors def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) args = parser.parse_args() errors = validate_repository(args.root) if errors: for error in errors: print(f"ERROR: {error}", file=sys.stderr) print(f"Documentation check failed with {len(errors)} error(s).", file=sys.stderr) return 1 print("Documentation check passed.") return 0 if __name__ == "__main__": raise SystemExit(main())