371 lines
12 KiB
Python
371 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only structural audit for an AI-ready repository."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
|
|
|
|
PROFILES = {
|
|
"documentation-guide": {
|
|
"README.md",
|
|
"AUTHOR.md",
|
|
"repository-variables.json",
|
|
"repository.json",
|
|
"LICENSE",
|
|
"CHANGELOG.md",
|
|
"UPDATES.md",
|
|
"VERSION",
|
|
"CITATION.cff",
|
|
"docs",
|
|
},
|
|
"skill-workflow": {
|
|
"README.md",
|
|
"AUTHOR.md",
|
|
"repository-variables.json",
|
|
"repository.json",
|
|
"LICENSE",
|
|
"CHANGELOG.md",
|
|
"UPDATES.md",
|
|
"VERSION",
|
|
"AGENTS.md",
|
|
"skills.md",
|
|
"skills",
|
|
"templates",
|
|
"examples",
|
|
},
|
|
"software-automation": {
|
|
"README.md",
|
|
"AUTHOR.md",
|
|
"repository-variables.json",
|
|
"repository.json",
|
|
"LICENSE",
|
|
"CHANGELOG.md",
|
|
"UPDATES.md",
|
|
"VERSION",
|
|
"CONTRIBUTING.md",
|
|
"SECURITY.md",
|
|
"AGENTS.md",
|
|
"docs",
|
|
"scripts",
|
|
"tests",
|
|
},
|
|
"dataset": {
|
|
"README.md",
|
|
"AUTHOR.md",
|
|
"repository-variables.json",
|
|
"repository.json",
|
|
"LICENSE",
|
|
"CHANGELOG.md",
|
|
"UPDATES.md",
|
|
"VERSION",
|
|
"CITATION.cff",
|
|
"data",
|
|
"schemas",
|
|
"docs",
|
|
},
|
|
}
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("repository", type=Path, help="Repository root to inspect")
|
|
parser.add_argument(
|
|
"--profile",
|
|
choices=sorted(PROFILES),
|
|
required=True,
|
|
help="Approved repository profile",
|
|
)
|
|
parser.add_argument("--json", action="store_true", help="Emit JSON")
|
|
return parser.parse_args()
|
|
|
|
|
|
def read_version_from_citation(path: Path) -> str | None:
|
|
if not path.is_file():
|
|
return None
|
|
match = re.search(
|
|
r"(?m)^version:\s*[\"']?([^\"'\s#]+)",
|
|
path.read_text(encoding="utf-8-sig"),
|
|
)
|
|
return match.group(1) if match else None
|
|
|
|
|
|
def audit_content_index(root: Path, findings: list[dict[str, str]]) -> None:
|
|
path = root / "content-index.json"
|
|
if not path.is_file():
|
|
return
|
|
try:
|
|
index = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
findings.append({"level": "error", "message": f"content-index.json is invalid: {exc}"})
|
|
return
|
|
|
|
items = index.get("items")
|
|
if not isinstance(items, list):
|
|
findings.append(
|
|
{"level": "error", "message": "content-index.json items must be an array"}
|
|
)
|
|
return
|
|
|
|
content_ids: set[str] = set()
|
|
paths: set[str] = set()
|
|
for position, item in enumerate(items):
|
|
if not isinstance(item, dict):
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"content-index.json item {position + 1} must be an object",
|
|
}
|
|
)
|
|
continue
|
|
content_id = item.get("content_id")
|
|
declared = item.get("path")
|
|
if not content_id:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"content-index.json item {position + 1} lacks content_id",
|
|
}
|
|
)
|
|
elif content_id in content_ids:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"Duplicate content_id in content-index.json: {content_id}",
|
|
}
|
|
)
|
|
else:
|
|
content_ids.add(content_id)
|
|
if not declared:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"content-index.json item {position + 1} lacks path",
|
|
}
|
|
)
|
|
elif declared in paths:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"Duplicate path in content-index.json: {declared}",
|
|
}
|
|
)
|
|
else:
|
|
paths.add(declared)
|
|
declared_path = Path(declared)
|
|
if (
|
|
declared_path.is_absolute()
|
|
or ".." in declared_path.parts
|
|
or not (root / declared_path).is_file()
|
|
):
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"Indexed content path does not exist or is unsafe: {declared}",
|
|
}
|
|
)
|
|
|
|
|
|
def audit(root: Path, profile: str) -> dict:
|
|
findings: list[dict[str, str]] = []
|
|
if not root.is_dir():
|
|
return {
|
|
"repository": str(root),
|
|
"profile": profile,
|
|
"passed": False,
|
|
"findings": [{"level": "error", "message": "Repository path is not a directory"}],
|
|
}
|
|
|
|
for relative in sorted(PROFILES[profile]):
|
|
if not (root / relative).exists():
|
|
findings.append({"level": "error", "message": f"Missing required path: {relative}"})
|
|
|
|
manifest_path = root / "repository.json"
|
|
manifest = None
|
|
if manifest_path.is_file():
|
|
try:
|
|
manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
findings.append({"level": "error", "message": f"repository.json is invalid: {exc}"})
|
|
else:
|
|
for key in ("schema_version", "repository_id", "title", "description", "version", "entrypoints"):
|
|
if key not in manifest:
|
|
findings.append({"level": "error", "message": f"repository.json lacks key: {key}"})
|
|
entrypoints = manifest.get("entrypoints", {})
|
|
if isinstance(entrypoints, dict):
|
|
for audience in ("human", "ai"):
|
|
declared = entrypoints.get(audience)
|
|
if not declared:
|
|
findings.append(
|
|
{"level": "error", "message": f"Missing {audience} entrypoint declaration"}
|
|
)
|
|
elif not (root / declared).exists():
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"Declared {audience} entrypoint does not exist: {declared}",
|
|
}
|
|
)
|
|
else:
|
|
findings.append({"level": "error", "message": "entrypoints must be an object"})
|
|
|
|
variables_path = root / "repository-variables.json"
|
|
variables = None
|
|
if variables_path.is_file():
|
|
try:
|
|
variables = json.loads(variables_path.read_text(encoding="utf-8-sig"))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
findings.append(
|
|
{"level": "error", "message": f"repository-variables.json is invalid: {exc}"}
|
|
)
|
|
else:
|
|
for key in (
|
|
"schema_version",
|
|
"repository_profile",
|
|
"identity",
|
|
"repository",
|
|
"rights",
|
|
"skill_defaults",
|
|
"verified_by",
|
|
"verified_at",
|
|
):
|
|
if key not in variables:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"repository-variables.json lacks key: {key}",
|
|
}
|
|
)
|
|
|
|
if manifest and 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)
|
|
]
|
|
comparisons = (
|
|
("authors", variable_authors, manifest_authors),
|
|
(
|
|
"publisher",
|
|
identity.get("publisher", {}).get("name"),
|
|
manifest.get("publisher", {}).get("name"),
|
|
),
|
|
(
|
|
"maintainer",
|
|
identity.get("maintainer", {}).get("name"),
|
|
manifest.get("maintenance", {}).get("maintainer"),
|
|
),
|
|
(
|
|
"repository",
|
|
variables.get("repository"),
|
|
{
|
|
key: manifest.get(key)
|
|
for key in (
|
|
"repository_id",
|
|
"name",
|
|
"title",
|
|
"canonical_url",
|
|
"organization",
|
|
)
|
|
},
|
|
),
|
|
(
|
|
"rights",
|
|
variables.get("rights"),
|
|
{
|
|
key: manifest.get("rights", {}).get(key)
|
|
for key in ("license", "license_file")
|
|
},
|
|
),
|
|
)
|
|
for label, variable_value, manifest_value in comparisons:
|
|
if variable_value != manifest_value:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": (
|
|
f"{label} differs between repository-variables.json "
|
|
"and repository.json"
|
|
),
|
|
}
|
|
)
|
|
|
|
if variables and variables.get("repository_profile") != profile:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": (
|
|
"repository_profile differs between repository-variables.json "
|
|
f"({variables.get('repository_profile')}) and requested audit ({profile})"
|
|
),
|
|
}
|
|
)
|
|
|
|
audit_content_index(root, findings)
|
|
|
|
version_path = root / "VERSION"
|
|
version = version_path.read_text(encoding="utf-8-sig").strip() if version_path.is_file() else None
|
|
if version and manifest and manifest.get("version") != version:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"VERSION ({version}) differs from repository.json ({manifest.get('version')})",
|
|
}
|
|
)
|
|
|
|
citation_version = read_version_from_citation(root / "CITATION.cff")
|
|
if version and citation_version and citation_version != version:
|
|
findings.append(
|
|
{
|
|
"level": "error",
|
|
"message": f"VERSION ({version}) differs from CITATION.cff ({citation_version})",
|
|
}
|
|
)
|
|
|
|
readme = root / "README.md"
|
|
if readme.is_file() and not readme.read_text(encoding="utf-8-sig").strip():
|
|
findings.append({"level": "error", "message": "README.md is empty"})
|
|
|
|
return {
|
|
"repository": str(root.resolve()),
|
|
"profile": profile,
|
|
"passed": not any(item["level"] == "error" for item in findings),
|
|
"findings": findings,
|
|
}
|
|
|
|
|
|
def emit_markdown(result: dict) -> None:
|
|
print(f"# Repository Audit\n\n- Repository: `{result['repository']}`")
|
|
print(f"- Profile: `{result['profile']}`")
|
|
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
|
|
print("\n## Findings")
|
|
if not result["findings"]:
|
|
print("\n- No structural errors found.")
|
|
else:
|
|
for finding in result["findings"]:
|
|
print(f"\n- {finding['level'].upper()}: {finding['message']}")
|
|
|
|
|
|
def main() -> int:
|
|
args = parse_args()
|
|
result = audit(args.repository, args.profile)
|
|
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())
|