check-docs.py

tools/check-docs.py

check-docs.py161 lines← SDK documentation
1#!/usr/bin/env python32"""Check current Newstack guides and research navigation with the SDK link engine."""3import argparse4import importlib.util5from pathlib import Path6import re7import subprocess8import sys9from urllib.parse import unquote, urlsplit1011ROOT = Path(__file__).resolve().parents[1]12HISTORICAL_SDK_REPOSITORY = "https://github.com/Neutrinomic/cdk-rsx"13# Published counterparts for the cited paths verified during the history rewrite.14HISTORICAL_SDK_PUBLICATION_REVISIONS = {15    "409a7176096c06c2dd9b7e491e8dc630951e83b4": "66cf55e42ea23810546c5361c10dd5168f833728",16    "16bbcc1f2f4a312631cad3ce74c6b2f044d09cd3": "c94343e76305ec64d93a3d9c9466ebf0c48d6994",17}18RESEARCH_ENTRIES = (19    "research/README.md",20    "research/experiments/README.md",21    "research/experiments/ashroot/README.md",22    "research/benchmarks/README.md",23    "research/benchmarks/minima/README.md",24    "research/benchmarks/minima/collections-2026-10-22.md",25    "research/benchmarks/heavy16/README.md",26    "research/archive/README.md",27    "research/archive/benchmarks/README.md",28    "research/archive/benchmarks/reports/README.md",29    "research/experiments/worktree-recovery/README.md",30    "research/experiments/2026-10-25-factory-harness-cleanup/README.md",31    "research/archive/tools/2026-10-25-encoded-collection-api/README.md",32    "research/archive/docs/2026-10-25-obsolete-authoring-fixtures/README.md",33)34def maintained_markdown(directory):35    """Check authored guides, preserving frozen vendored documentation as source."""36    return (path for path in directory.rglob("*.md")37            if not {"vendor", "tmp", "target", "node_modules", ".rustup"} & set(path.relative_to(ROOT).parts)38            and not path.name.startswith("UPSTREAM-")39            and not path.is_relative_to(ROOT / "benches/rrt/controls/motoko/takt-fourcans"))404142def current_paths():43    paths = [ROOT / name for name in (44        "README.md", "AGENTS.md", "benches/README.md", "tests/README.md",45        "tests/authoring/README.md", "tests/pocketic/README.md",46        "tests/fuzz/README.md", "tests/fuzz/AGENTS.md", "tests/verification/README.md",47    )]48    paths.extend(maintained_markdown(ROOT / "docs"))49    sdk = ROOT / "cdk-rsx"50    paths.extend(sdk / name for name in ("README.md", "AGENTS.md"))51    for directory in ("crates", "tools"):52        paths.extend(maintained_markdown(sdk / directory))53    paths.extend(ROOT / "verification" / name for name in ("README.md", "AGENTS.md"))54    paths.extend(maintained_markdown(ROOT / "verification/docs"))55    paths.extend(maintained_markdown(ROOT / "verification/proofs"))56    paths.extend(maintained_markdown(ROOT / "benches"))57    paths.extend((ROOT / "tests/canisters").glob("*/README.md"))58    paths.extend((ROOT / "tests/authoring/fixtures").glob("*/README.md"))59    paths.extend(ROOT / name for name in RESEARCH_ENTRIES)60    paths.extend(ROOT / name for name in (61        "research/crypto/README.md", "research/crypto/experiments/README.md",62        "research/crypto/benchmarks/README.md",63        "research/verification/README.md", "research/verification/experiments/README.md",64        "research/verification/reviews/README.md",65        "research/verification/qualifications/README.md", "tests/rrt-chat/README.md",66    ))67    return paths686970def historical(path):71    """Qualification citations retain the exact source they originally checked."""72    return (path.is_relative_to(ROOT / 'research/verification/reviews')73        or path.is_relative_to(ROOT / 'verification/docs/workstreams')74        or path.is_relative_to(ROOT / 'research/verification/experiments')75        or (path.is_relative_to(ROOT / 'research') and path.name != 'README.md'))767778def check_sdk_citations(paths, engine):79    """Current SDK links are local; historical SDK citations are immutable."""80    prefixes = tuple(f"{HISTORICAL_SDK_REPOSITORY}/{kind}/" for kind in ("blob", "tree"))81    failures = []82    for path in sorted({Path(path).resolve() for path in paths}):83        if not path.is_file() or not path.is_relative_to(ROOT):84            continue85        text = path.read_text()86        for offset, target, undefined in engine.links(text):87            if undefined is not None:88                continue89            line = text.count("\n", 0, offset) + 190            label = f"{path.relative_to(ROOT)}:{line}"91            if target.startswith(prefixes):92                parts = urlsplit(target).path.split("/", 5)93                if historical(path) and len(parts) == 6 and re.fullmatch(r'[0-9a-f]{40}', parts[4]):94                    original = parts[4]95                    source_path = unquote(parts[5])96                    published = HISTORICAL_SDK_PUBLICATION_REVISIONS.get(original)97                    revisions = (original, published) if published else (original,)98                    found = any(subprocess.run(99                        ['git', '-C', str(ROOT), 'cat-file', '-e', f'{revision}:{source_path}'],100                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,101                    ).returncode == 0 for revision in revisions)102                    if not found:103                        failures.append(f"{label}: missing historical SDK source {target}")104                elif historical(path):105                    failures.append(f"{label}: historical SDK target must use an exact commit: {target}")106                else:107                    failures.append(f"{label}: current SDK target must use a local repository link: {target}")108    for failure in failures:109        print(failure, file=sys.stderr)110    return bool(failures)111112113def check_authored_targets(paths, engine):114    """Local caches and empty leftover directories must not hide clone failures."""115    names = subprocess.check_output([116        "git", "ls-files", "--cached", "--others", "--exclude-standard", "-z",117    ], cwd=ROOT).decode().split("\0")118    files = {(ROOT / name).resolve() for name in names119             if name and (ROOT / name).is_file()}120    directories = {ROOT.resolve()}121    for path in files:122        if path.is_relative_to(ROOT):123            directories.update(parent for parent in path.parents if parent.is_relative_to(ROOT))124    failures = []125    for path in sorted({Path(path).resolve() for path in paths}):126        if not path.is_file() or not path.is_relative_to(ROOT):127            continue128        source = path.read_text()129        for offset, target, undefined in engine.links(source):130            local = engine.local_target(target) if undefined is None else None131            if local is None:132                continue133            destination = (path.parent / local).resolve()134            if destination.exists() and destination not in files and destination not in directories:135                line = source.count("\n", 0, offset) + 1136                failures.append(f"{path.relative_to(ROOT)}:{line}: local target has no authored source: {target}")137    for failure in failures:138        print(failure, file=sys.stderr)139    return bool(failures)140141142def main():143    parser = argparse.ArgumentParser(description=__doc__)144    parser.add_argument("files", nargs="*", type=Path, help="check these Markdown files instead of current guides and navigation")145    args = parser.parse_args()146    engine_path = ROOT / "cdk-rsx/tools/check-docs.py"147    if not engine_path.is_file():148        parser.error("Missing tracked SDK documentation checker: cdk-rsx/tools/check-docs.py")149    spec = importlib.util.spec_from_file_location("sdk_doc_links", engine_path)150    engine = importlib.util.module_from_spec(spec)151    spec.loader.exec_module(engine)152    paths = args.files or current_paths()153    failed = check_sdk_citations(paths, engine)154    failed |= check_authored_targets(paths, engine)155    if failed:156        return 1157    return engine.check_paths(paths, root=ROOT)158159160if __name__ == "__main__":161    raise SystemExit(main())