436 lines
16 KiB
Python
436 lines
16 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",
|
|
"content-index.json",
|
|
"LICENSE",
|
|
"README.md",
|
|
"SECURITY.md",
|
|
"UPDATES.md",
|
|
"VERSION",
|
|
"assets/README.md",
|
|
"data/README.md",
|
|
"docs/README.md",
|
|
"examples/README.md",
|
|
"examples/example-content-index.json",
|
|
"receipts/README.md",
|
|
"repository.json",
|
|
"repository-variables.json",
|
|
"schemas/README.md",
|
|
"schemas/content-index.schema.json",
|
|
"schemas/repository.schema.json",
|
|
"schemas/repository-variables.schema.json",
|
|
"scripts/README.md",
|
|
"skills.md",
|
|
"skills/README.md",
|
|
"skills/structure-ai-ready-repository/SKILL.md",
|
|
"tasks/README.md",
|
|
"templates/content-index.json.template",
|
|
"templates/README.md",
|
|
"templates/repository-variables.json.template",
|
|
"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",
|
|
)
|
|
|
|
CONTENT_INDEX_REQUIRED_KEYS = (
|
|
"schema_version",
|
|
"collection_id",
|
|
"title",
|
|
"description",
|
|
"updated_at",
|
|
"items",
|
|
)
|
|
|
|
CONTENT_ITEM_REQUIRED_KEYS = (
|
|
"content_id",
|
|
"title",
|
|
"description",
|
|
"content_type",
|
|
"path",
|
|
"status",
|
|
)
|
|
|
|
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}")
|
|
declared_paths = {
|
|
item.get("path") for item in contents if isinstance(item, dict)
|
|
}
|
|
if (root / "content-index.json").is_file() and "content-index.json" not in declared_paths:
|
|
add(findings, "error", "repository.json contents must declare content-index.json")
|
|
|
|
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_content_index(root: Path, findings: list[dict[str, str]]) -> dict | None:
|
|
path = root / "content-index.json"
|
|
try:
|
|
index = json.loads(read_text(path))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
add(findings, "error", f"content-index.json is invalid: {exc}")
|
|
return None
|
|
|
|
for key in CONTENT_INDEX_REQUIRED_KEYS:
|
|
if key not in index:
|
|
add(findings, "error", f"content-index.json lacks required key: {key}")
|
|
|
|
items = index.get("items")
|
|
if not isinstance(items, list):
|
|
add(findings, "error", "content-index.json items must be an array")
|
|
return index
|
|
|
|
content_ids: set[str] = set()
|
|
paths: set[str] = set()
|
|
related_references: list[tuple[str, str]] = []
|
|
for position, item in enumerate(items):
|
|
label = f"content-index.json item {position + 1}"
|
|
if not isinstance(item, dict):
|
|
add(findings, "error", f"{label} must be an object")
|
|
continue
|
|
for key in CONTENT_ITEM_REQUIRED_KEYS:
|
|
if key not in item:
|
|
add(findings, "error", f"{label} lacks required key: {key}")
|
|
|
|
content_id = item.get("content_id")
|
|
if not isinstance(content_id, str) or not content_id:
|
|
add(findings, "error", f"{label} has an invalid content_id")
|
|
elif content_id in content_ids:
|
|
add(findings, "error", f"Duplicate content_id in content-index.json: {content_id}")
|
|
else:
|
|
content_ids.add(content_id)
|
|
|
|
declared = item.get("path")
|
|
if not isinstance(declared, str) or not declared:
|
|
add(findings, "error", f"{label} has an invalid path")
|
|
else:
|
|
declared_path = Path(declared)
|
|
if declared_path.is_absolute() or ".." in declared_path.parts:
|
|
add(findings, "error", f"Unsafe content-index.json path: {declared}")
|
|
elif declared in paths:
|
|
add(findings, "error", f"Duplicate path in content-index.json: {declared}")
|
|
else:
|
|
paths.add(declared)
|
|
if not (root / declared_path).is_file():
|
|
add(findings, "error", f"Indexed content path does not exist: {declared}")
|
|
|
|
related = item.get("related_content_ids", [])
|
|
if not isinstance(related, list):
|
|
add(findings, "error", f"{label} related_content_ids must be an array")
|
|
elif isinstance(content_id, str):
|
|
related_references.extend((content_id, value) for value in related)
|
|
|
|
for source_id, related_id in related_references:
|
|
if related_id not in content_ids:
|
|
add(
|
|
findings,
|
|
"error",
|
|
f"Unknown related_content_id in content-index.json: {source_id} -> {related_id}",
|
|
)
|
|
return index
|
|
|
|
|
|
def validate_variables(
|
|
root: Path, manifest: dict | None, findings: list[dict[str, str]]
|
|
) -> dict | None:
|
|
path = root / "repository-variables.json"
|
|
try:
|
|
variables = json.loads(read_text(path))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
add(findings, "error", f"repository-variables.json is invalid: {exc}")
|
|
return None
|
|
|
|
required = (
|
|
"schema_version",
|
|
"purpose",
|
|
"repository_profile",
|
|
"identity",
|
|
"repository",
|
|
"rights",
|
|
"skill_defaults",
|
|
"verified_by",
|
|
"verified_at",
|
|
)
|
|
for key in required:
|
|
if key not in variables:
|
|
add(findings, "error", f"repository-variables.json lacks required key: {key}")
|
|
|
|
if not manifest:
|
|
return variables
|
|
|
|
identity = variables.get("identity", {})
|
|
variable_authors = [
|
|
item.get("name") for item in identity.get("authors", []) if isinstance(item, dict)
|
|
]
|
|
manifest_authors = [
|
|
item.get("name")
|
|
for item in manifest.get("authors", [])
|
|
if isinstance(item, dict)
|
|
]
|
|
if variable_authors != manifest_authors:
|
|
add(findings, "error", "Authors differ between repository-variables.json and repository.json")
|
|
|
|
variable_publisher = identity.get("publisher", {}).get("name")
|
|
manifest_publisher = manifest.get("publisher", {}).get("name")
|
|
if variable_publisher != manifest_publisher:
|
|
add(findings, "error", "Publisher differs between repository-variables.json and repository.json")
|
|
|
|
variable_maintainer = identity.get("maintainer", {}).get("name")
|
|
manifest_maintainer = manifest.get("maintenance", {}).get("maintainer")
|
|
if variable_maintainer != manifest_maintainer:
|
|
add(findings, "error", "Maintainer differs between repository-variables.json and repository.json")
|
|
|
|
repository = variables.get("repository", {})
|
|
for key in ("repository_id", "name", "title", "canonical_url", "organization"):
|
|
if repository.get(key) != manifest.get(key):
|
|
add(
|
|
findings,
|
|
"error",
|
|
f"{key} differs between repository-variables.json and repository.json",
|
|
)
|
|
|
|
variable_rights = variables.get("rights", {})
|
|
manifest_rights = manifest.get("rights", {})
|
|
for key in ("license", "license_file"):
|
|
if variable_rights.get(key) != manifest_rights.get(key):
|
|
add(
|
|
findings,
|
|
"error",
|
|
f"{key} differs between repository-variables.json and repository.json",
|
|
)
|
|
return variables
|
|
|
|
|
|
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 (root / "content-index.json").is_file():
|
|
validate_content_index(root, findings)
|
|
if (root / "repository-variables.json").is_file():
|
|
validate_variables(root, manifest, 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())
|