264 lines
9.5 KiB
Python
264 lines
9.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Validate the implemented AI-ready repository template without dependencies."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
from urllib.parse import unquote
|
|
|
|
|
|
REQUIRED_PATHS = (
|
|
".gitea/ISSUE_TEMPLATE/bug-report.md",
|
|
".gitea/ISSUE_TEMPLATE/documentation-correction.md",
|
|
".gitea/ISSUE_TEMPLATE/feature-request.md",
|
|
".gitea/PULL_REQUEST_TEMPLATE.md",
|
|
"AGENTS.md",
|
|
"AUTHOR.md",
|
|
"CHANGELOG.md",
|
|
"CITATION.cff",
|
|
"CONTRIBUTING.md",
|
|
"LICENSE",
|
|
"README.md",
|
|
"SECURITY.md",
|
|
"UPDATES.md",
|
|
"VERSION",
|
|
"assets/README.md",
|
|
"data/README.md",
|
|
"docs/README.md",
|
|
"examples/README.md",
|
|
"receipts/README.md",
|
|
"repository.json",
|
|
"schemas/README.md",
|
|
"schemas/repository.schema.json",
|
|
"scripts/README.md",
|
|
"skills.md",
|
|
"skills/README.md",
|
|
"skills/structure-ai-ready-repository/SKILL.md",
|
|
"tasks/README.md",
|
|
"templates/README.md",
|
|
"tests/README.md",
|
|
)
|
|
|
|
MANIFEST_REQUIRED_KEYS = (
|
|
"schema_version",
|
|
"repository_id",
|
|
"name",
|
|
"title",
|
|
"description",
|
|
"authors",
|
|
"publisher",
|
|
"repository_status",
|
|
"visibility",
|
|
"maturity",
|
|
"version",
|
|
"resource_types",
|
|
"entrypoints",
|
|
"rights",
|
|
"maintenance",
|
|
"ai_retrieval",
|
|
)
|
|
|
|
MARKDOWN_LINK = re.compile(r"(?<!!)\[[^\]]+\]\(([^)]+)\)")
|
|
CITATION_VERSION = re.compile(r"(?m)^version:\s*[\"']?([^\"'\s#]+)")
|
|
CITATION_LICENSE = re.compile(r"(?m)^license:\s*[\"']?([^\"'\s#]+)")
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("repository", nargs="?", default=".", type=Path)
|
|
parser.add_argument("--json", action="store_true", help="Emit JSON")
|
|
return parser.parse_args()
|
|
|
|
|
|
def read_text(path: Path) -> str:
|
|
return path.read_text(encoding="utf-8-sig")
|
|
|
|
|
|
def add(findings: list[dict[str, str]], level: str, message: str) -> None:
|
|
findings.append({"level": level, "message": message})
|
|
|
|
|
|
def validate_manifest(root: Path, findings: list[dict[str, str]]) -> dict | None:
|
|
path = root / "repository.json"
|
|
try:
|
|
manifest = json.loads(read_text(path))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
add(findings, "error", f"repository.json is invalid: {exc}")
|
|
return None
|
|
|
|
for key in MANIFEST_REQUIRED_KEYS:
|
|
if key not in manifest:
|
|
add(findings, "error", f"repository.json lacks required key: {key}")
|
|
|
|
entrypoints = manifest.get("entrypoints")
|
|
if not isinstance(entrypoints, dict):
|
|
add(findings, "error", "repository.json entrypoints must be an object")
|
|
else:
|
|
for name in ("human", "ai"):
|
|
value = entrypoints.get(name)
|
|
if not isinstance(value, str) or not value:
|
|
add(findings, "error", f"Missing {name} entrypoint")
|
|
elif not (root / value).exists():
|
|
add(findings, "error", f"Declared {name} entrypoint does not exist: {value}")
|
|
for name, value in entrypoints.items():
|
|
if name in ("human", "ai") or value is None:
|
|
continue
|
|
if not isinstance(value, str) or not (root / value).exists():
|
|
add(findings, "error", f"Declared entrypoint does not exist: {name}={value}")
|
|
|
|
contents = manifest.get("contents", [])
|
|
if not isinstance(contents, list):
|
|
add(findings, "error", "repository.json contents must be an array")
|
|
else:
|
|
for item in contents:
|
|
declared = item.get("path") if isinstance(item, dict) else None
|
|
if not declared or not (root / declared).exists():
|
|
add(findings, "error", f"Declared contents path does not exist: {declared}")
|
|
|
|
retrieval = manifest.get("ai_retrieval", {})
|
|
if isinstance(retrieval, dict):
|
|
for field in ("read_first", "retrieve_as_needed"):
|
|
for declared in retrieval.get(field, []):
|
|
normalized = declared.rstrip("/")
|
|
if normalized and not (root / normalized).exists():
|
|
add(findings, "error", f"AI retrieval path does not exist: {declared}")
|
|
|
|
author_text = read_text(root / "AUTHOR.md") if (root / "AUTHOR.md").is_file() else ""
|
|
citation_text = read_text(root / "CITATION.cff") if (root / "CITATION.cff").is_file() else ""
|
|
license_text = read_text(root / "LICENSE") if (root / "LICENSE").is_file() else ""
|
|
authors = manifest.get("authors", [])
|
|
if not isinstance(authors, list) or not authors:
|
|
add(findings, "error", "repository.json authors must be a non-empty array")
|
|
else:
|
|
for author in authors:
|
|
name = author.get("name") if isinstance(author, dict) else None
|
|
if not name:
|
|
add(findings, "error", "Every repository.json author must have a name")
|
|
continue
|
|
if name not in author_text:
|
|
add(findings, "error", f"Author is absent from AUTHOR.md: {name}")
|
|
parts = name.split()
|
|
if not all(part in citation_text for part in parts):
|
|
add(findings, "error", f"Author is not aligned with CITATION.cff: {name}")
|
|
if name not in license_text:
|
|
add(findings, "error", f"Author is absent from LICENSE copyright: {name}")
|
|
|
|
publisher = manifest.get("publisher")
|
|
publisher_name = publisher.get("name") if isinstance(publisher, dict) else None
|
|
if not publisher_name:
|
|
add(findings, "error", "repository.json publisher must have a name")
|
|
elif publisher_name not in author_text:
|
|
add(findings, "error", f"Publisher is absent from AUTHOR.md: {publisher_name}")
|
|
|
|
maintainer = manifest.get("maintenance", {}).get("maintainer")
|
|
if maintainer and maintainer not in author_text:
|
|
add(findings, "error", f"Maintainer is absent from AUTHOR.md: {maintainer}")
|
|
return manifest
|
|
|
|
|
|
def validate_versions(root: Path, manifest: dict | None, findings: list[dict[str, str]]) -> None:
|
|
version = read_text(root / "VERSION").strip()
|
|
if not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?", version):
|
|
add(findings, "error", f"VERSION is not semantic: {version!r}")
|
|
|
|
if manifest and manifest.get("version") != version:
|
|
add(findings, "error", "VERSION differs from repository.json")
|
|
|
|
citation = read_text(root / "CITATION.cff")
|
|
match = CITATION_VERSION.search(citation)
|
|
if not match or match.group(1) != version:
|
|
add(findings, "error", "VERSION differs from or is absent in CITATION.cff")
|
|
|
|
changelog = read_text(root / "CHANGELOG.md")
|
|
if f"## [{version}]" not in changelog:
|
|
add(findings, "error", f"CHANGELOG.md lacks release heading for {version}")
|
|
|
|
if manifest:
|
|
manifest_license = manifest.get("rights", {}).get("license")
|
|
citation_match = CITATION_LICENSE.search(citation)
|
|
if citation_match and manifest_license != citation_match.group(1):
|
|
add(findings, "error", "License differs between repository.json and CITATION.cff")
|
|
|
|
|
|
def validate_markdown_links(root: Path, findings: list[dict[str, str]]) -> None:
|
|
for path in root.rglob("*.md"):
|
|
if ".git" in path.parts:
|
|
continue
|
|
text = read_text(path)
|
|
for raw_target in MARKDOWN_LINK.findall(text):
|
|
target = raw_target.strip().split(maxsplit=1)[0].strip("<>")
|
|
if (
|
|
not target
|
|
or target.startswith(("#", "http://", "https://", "mailto:"))
|
|
or "{{" in target
|
|
):
|
|
continue
|
|
local = unquote(target.split("#", 1)[0])
|
|
if local and not (path.parent / local).resolve().exists():
|
|
add(
|
|
findings,
|
|
"error",
|
|
f"Broken relative Markdown link in {path.relative_to(root)}: {target}",
|
|
)
|
|
|
|
|
|
def validate(root: Path) -> dict:
|
|
findings: list[dict[str, str]] = []
|
|
root = root.resolve()
|
|
if not root.is_dir():
|
|
add(findings, "error", "Repository path is not a directory")
|
|
return {"repository": str(root), "passed": False, "findings": findings}
|
|
|
|
for relative in REQUIRED_PATHS:
|
|
if not (root / relative).exists():
|
|
add(findings, "error", f"Missing required path: {relative}")
|
|
|
|
if findings:
|
|
missing_core = any(
|
|
item["message"].endswith(("repository.json", "VERSION", "CITATION.cff", "CHANGELOG.md"))
|
|
for item in findings
|
|
)
|
|
else:
|
|
missing_core = False
|
|
|
|
manifest = None if not (root / "repository.json").is_file() else validate_manifest(root, findings)
|
|
if not missing_core:
|
|
validate_versions(root, manifest, findings)
|
|
validate_markdown_links(root, findings)
|
|
|
|
return {
|
|
"repository": str(root),
|
|
"passed": not any(item["level"] == "error" for item in findings),
|
|
"findings": findings,
|
|
}
|
|
|
|
|
|
def emit_markdown(result: dict) -> None:
|
|
print("# Repository Validation")
|
|
print(f"\n- Repository: `{result['repository']}`")
|
|
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
|
|
print("\n## Findings")
|
|
if not result["findings"]:
|
|
print("\n- No validation errors found.")
|
|
else:
|
|
for finding in result["findings"]:
|
|
print(f"\n- {finding['level'].upper()}: {finding['message']}")
|
|
|
|
|
|
def main() -> int:
|
|
args = parse_args()
|
|
result = validate(args.repository)
|
|
if args.json:
|
|
print(json.dumps(result, indent=2))
|
|
else:
|
|
emit_markdown(result)
|
|
return 0 if result["passed"] else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|