#!/usr/bin/env python3
|
"""Deterministically validate a repository Agent Team."""
|
|
from __future__ import annotations
|
|
import argparse
|
import hashlib
|
import json
|
import re
|
import sys
|
from datetime import datetime
|
from pathlib import Path, PurePosixPath
|
from typing import Iterable
|
|
|
START = "<!-- AI-AGENT-SYSTEM:START -->"
|
END = "<!-- AI-AGENT-SYSTEM:END -->"
|
LEGACY_START = "<!-- AI-AGENT-ROUTING:START -->"
|
LEGACY_END = "<!-- AI-AGENT-ROUTING:END -->"
|
NAME = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
RUN_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
ISO_UTC = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$")
|
PATH_REF = re.compile(
|
r"(?<![A-Za-z0-9_])\.ai/(?:agents|skills|workflows|orchestration)/[A-Za-z0-9._/-]+"
|
)
|
EXECUTION_MODES = {"inline", "subagent-readonly", "subagent-shared", "subagent-worktree"}
|
AGENT_HEADINGS = ["## role", "## input", "## output", "## decision", "## execution", "## return_contract"]
|
SKILL_HEADINGS = ["## Steps", "## Output"]
|
WORKFLOW_HEADINGS = [
|
"## goal",
|
"## flow",
|
"## execution_graph",
|
"## steps",
|
"## synchronization_gates",
|
"## routing_rules",
|
"## output_format",
|
]
|
WORKFLOW_STEP_FIELDS = {
|
"agent",
|
"skill",
|
"execution",
|
"depends_on",
|
"parallel_group",
|
"requires",
|
"read_scope",
|
"write_scope",
|
"input",
|
"output",
|
"verification",
|
"next",
|
}
|
ORCHESTRATION_FILES = {
|
"execution-policy.md",
|
"subagent-contract.md",
|
"context-policy.md",
|
"merge-policy.md",
|
}
|
MANIFEST_FIELDS = {
|
"schema_version",
|
"generator",
|
"suite_version",
|
"run_id",
|
"blueprint_id",
|
"generation_mode",
|
"generated_at",
|
"managed_paths",
|
"agents_md_managed_block",
|
"generated_files",
|
}
|
|
|
def configure_stdio() -> None:
|
for stream in (sys.stdout, sys.stderr):
|
if hasattr(stream, "reconfigure"):
|
stream.reconfigure(encoding="utf-8", errors="strict")
|
|
|
def parse_args() -> argparse.Namespace:
|
parser = argparse.ArgumentParser()
|
source = parser.add_mutually_exclusive_group(required=True)
|
source.add_argument("--root")
|
source.add_argument("--manifest-only")
|
parser.add_argument("--json", action="store_true")
|
return parser.parse_args()
|
|
|
def finding(path: str, message: str, code: str) -> dict:
|
return {"code": code, "path": path, "message": message}
|
|
|
def is_reparse(path: Path) -> bool:
|
return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())
|
|
|
def under(path: Path, root: Path) -> bool:
|
try:
|
path.relative_to(root)
|
return True
|
except ValueError:
|
return False
|
|
|
def safe_repo_path(raw: str, *, allow_tree_glob: bool = False) -> str | None:
|
"""Return a canonical repository-relative POSIX path, or None when unsafe."""
|
if not isinstance(raw, str) or not raw or raw != raw.strip():
|
return None
|
if "\\" in raw or ":" in raw or raw.startswith(("/", "./")) or "//" in raw:
|
return None
|
core = raw
|
if allow_tree_glob and core.endswith("/**"):
|
core = core[:-3]
|
if not core or core == "." or any(character in core for character in "*?[]"):
|
return None
|
path = PurePosixPath(core)
|
if any(part in {"", ".", ".."} for part in path.parts):
|
return None
|
if path.is_absolute() or path.as_posix() != core:
|
return None
|
return raw
|
|
|
def repository_path(root: Path, relative: str) -> Path:
|
return root.joinpath(*PurePosixPath(relative).parts)
|
|
|
def check_path_chain(root: Path, relative: str, errors: list[dict]) -> Path | None:
|
if safe_repo_path(relative) is None:
|
errors.append(finding(relative, "path is not a safe repository-relative POSIX path", "unsafe-path"))
|
return None
|
resolved_root = root.resolve(strict=True)
|
current = root
|
for part in PurePosixPath(relative).parts:
|
current /= part
|
if (current.exists() or current.is_symlink()) and is_reparse(current):
|
errors.append(finding(relative, f"path chain contains a symlink or junction: {current.name}", "reparse-point"))
|
return None
|
if not under(current.resolve(strict=False), resolved_root):
|
errors.append(finding(relative, "resolved path escapes the repository", "unsafe-path"))
|
return None
|
return current
|
|
|
def walk_managed(root: Path, relative: str, errors: list[dict]) -> list[Path]:
|
start = check_path_chain(root, relative, errors)
|
if start is None or not start.exists():
|
return []
|
files: list[Path] = []
|
pending = [start]
|
while pending:
|
current = pending.pop()
|
if is_reparse(current):
|
errors.append(finding(current.relative_to(root).as_posix(), "managed output contains a symlink or junction", "reparse-point"))
|
continue
|
if current.is_dir():
|
pending.extend(current.iterdir())
|
elif current.is_file():
|
files.append(current)
|
return files
|
|
|
def read_utf8(path: Path, root: Path, errors: list[dict], warnings: list[dict]) -> str | None:
|
relative = path.relative_to(root).as_posix()
|
try:
|
data = path.read_bytes()
|
except OSError as exc:
|
errors.append(finding(relative, f"cannot read regular UTF-8 file: {exc}", "unreadable-file"))
|
return None
|
if data.startswith(b"\xef\xbb\xbf"):
|
warnings.append(finding(relative, "UTF-8 BOM is unnecessary", "utf8-bom"))
|
try:
|
return data.decode("utf-8-sig")
|
except UnicodeDecodeError as exc:
|
errors.append(finding(relative, f"not valid UTF-8: {exc}", "invalid-utf8"))
|
return None
|
|
|
def check_fences(text: str) -> bool:
|
opened: tuple[str, int] | None = None
|
for line in text.splitlines():
|
match = re.match(r"^\s*(`{3,}|~{3,})", line)
|
if not match:
|
continue
|
token = match.group(1)
|
current = (token[0], len(token))
|
if opened is None:
|
opened = current
|
elif current[0] == opened[0] and current[1] >= opened[1]:
|
opened = None
|
return opened is None
|
|
|
def require_headings(text: str, headings: Iterable[str], relative: str, errors: list[dict]) -> None:
|
lines = set(text.splitlines())
|
for heading in headings:
|
if heading not in lines:
|
errors.append(finding(relative, f"missing heading: {heading}", "missing-heading"))
|
|
|
def parse_frontmatter(text: str) -> dict[str, str] | None:
|
lines = text.splitlines()
|
if not lines or lines[0] != "---":
|
return None
|
try:
|
end = lines.index("---", 1)
|
except ValueError:
|
return None
|
values: dict[str, str] = {}
|
for line in lines[1:end]:
|
if not line.strip() or line.lstrip().startswith("#"):
|
continue
|
if line != line.lstrip() or ":" not in line:
|
return None
|
key, raw = line.split(":", 1)
|
key, raw = key.strip(), raw.strip()
|
if not re.fullmatch(r"[a-z][a-z0-9_-]*", key) or key in values or not raw or raw in {"|", ">"}:
|
return None
|
if raw.startswith('"'):
|
try:
|
value = json.loads(raw)
|
except json.JSONDecodeError:
|
return None
|
if not isinstance(value, str):
|
return None
|
elif raw.startswith("'"):
|
if len(raw) < 2 or not raw.endswith("'"):
|
return None
|
value = raw[1:-1].replace("''", "'")
|
else:
|
if raw.endswith(('"', "'")) or raw.startswith(("[", "{", "&", "*", "!")):
|
return None
|
lowered = raw.casefold()
|
typed_scalar = (
|
lowered in {"null", "~", "true", "false", "yes", "no", "on", "off", ".nan", ".inf", "+.inf", "-.inf"}
|
or re.fullmatch(r"[-+]?(?:0|[1-9][0-9_]*)(?:\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?", raw) is not None
|
or re.fullmatch(r"0[xX][0-9a-fA-F_]+|0[oO][0-7_]+", raw) is not None
|
or re.fullmatch(r"\d{4}-\d{2}-\d{2}(?:[Tt ].*)?", raw) is not None
|
)
|
if typed_scalar:
|
return None
|
value = raw
|
values[key] = value
|
return values
|
|
|
def load_manifest(path: Path, errors: list[dict], display_path: str) -> dict:
|
if not path.is_file() or is_reparse(path):
|
errors.append(finding(display_path, "manifest is missing or is a reparse point", "missing-manifest"))
|
return {}
|
try:
|
data = path.read_bytes()
|
if data.startswith(b"\xef\xbb\xbf"):
|
text = data.decode("utf-8-sig")
|
else:
|
text = data.decode("utf-8")
|
value = json.loads(text)
|
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
errors.append(finding(display_path, f"manifest is not valid UTF-8 JSON: {exc}", "invalid-manifest"))
|
return {}
|
if not isinstance(value, dict):
|
errors.append(finding(display_path, "manifest root must be an object", "invalid-manifest"))
|
return {}
|
return value
|
|
|
def validate_manifest(manifest: dict, errors: list[dict], display_path: str) -> list[str]:
|
if set(manifest) != MANIFEST_FIELDS:
|
missing = sorted(MANIFEST_FIELDS - set(manifest))
|
extra = sorted(set(manifest) - MANIFEST_FIELDS)
|
errors.append(finding(display_path, f"manifest fields mismatch; missing={missing}, extra={extra}", "invalid-manifest"))
|
if type(manifest.get("schema_version")) is not int or manifest.get("schema_version") != 1:
|
errors.append(finding(display_path, "schema_version must be integer 1", "invalid-manifest"))
|
if manifest.get("generator") != "ai-agent-system-bootstrap":
|
errors.append(finding(display_path, "generator must be ai-agent-system-bootstrap", "invalid-manifest"))
|
if type(manifest.get("suite_version")) is not int or manifest.get("suite_version") != 4:
|
errors.append(finding(display_path, "suite_version must be integer 4", "invalid-manifest"))
|
run_id = manifest.get("run_id")
|
if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id):
|
errors.append(finding(display_path, "run_id is missing or invalid", "invalid-manifest"))
|
blueprint_id = manifest.get("blueprint_id")
|
if not isinstance(blueprint_id, str) or not RUN_ID.fullmatch(blueprint_id):
|
errors.append(finding(display_path, "blueprint_id is missing or invalid", "invalid-manifest"))
|
if manifest.get("generation_mode") not in {"initialize", "rebuild"}:
|
errors.append(finding(display_path, "generation_mode must be initialize or rebuild", "invalid-manifest"))
|
generated_at = manifest.get("generated_at")
|
if not isinstance(generated_at, str) or not ISO_UTC.fullmatch(generated_at):
|
errors.append(finding(display_path, "generated_at must be an ISO-8601 UTC timestamp ending in Z", "invalid-manifest"))
|
else:
|
try:
|
datetime.fromisoformat(generated_at[:-1] + "+00:00")
|
except ValueError:
|
errors.append(finding(display_path, "generated_at is not a real UTC timestamp", "invalid-manifest"))
|
if manifest.get("agents_md_managed_block") != {"start": START, "end": END}:
|
errors.append(finding(display_path, "managed block markers do not match the current schema", "invalid-manifest"))
|
|
managed = manifest.get("managed_paths")
|
if not isinstance(managed, list) or any(not isinstance(value, str) for value in managed):
|
errors.append(finding(display_path, "managed_paths must be a string array", "invalid-manifest"))
|
managed = []
|
if managed != [".ai"]:
|
errors.append(finding(display_path, "managed_paths must contain only .ai", "invalid-manifest"))
|
|
generated = manifest.get("generated_files")
|
if not isinstance(generated, list) or any(not isinstance(value, str) for value in generated):
|
errors.append(finding(display_path, "generated_files must be a string array", "invalid-manifest"))
|
generated = []
|
if len(generated) != len(set(generated)) or "AGENTS.md" not in generated or ".ai/bootstrap-manifest.json" not in generated:
|
errors.append(finding(display_path, "generated_files must be unique and include AGENTS.md plus the manifest", "invalid-manifest"))
|
for value in generated:
|
if safe_repo_path(value) is None:
|
errors.append(finding(display_path, f"unsafe generated file path: {value}", "invalid-generated-file"))
|
continue
|
owned = value == "AGENTS.md" or value.startswith(".ai/")
|
if not owned:
|
errors.append(finding(display_path, f"generated file is outside managed paths: {value}", "invalid-generated-file"))
|
return []
|
|
|
def manifest_report(path: Path) -> dict:
|
errors: list[dict] = []
|
if is_reparse(path):
|
errors.append(finding(str(path), "manifest must not be a symlink or junction", "reparse-point"))
|
manifest = {}
|
else:
|
manifest = load_manifest(path, errors, str(path))
|
skill_roots = validate_manifest(manifest, errors, str(path)) if manifest else []
|
errors.sort(key=lambda item: (item["path"].casefold(), item["code"], item["message"]))
|
return {
|
"schema_version": 1,
|
"status": "failed" if errors else "passed",
|
"errors": errors,
|
"warnings": [],
|
"manifest": manifest if not errors else None,
|
"managed_skill_paths": skill_roots if not errors else [],
|
}
|
|
|
def extract_block(text: str, errors: list[dict], relative: str) -> str:
|
if text.count(START) != 1 or text.count(END) != 1:
|
errors.append(finding(relative, "current managed markers must each appear once", "invalid-markers"))
|
return ""
|
if text.count(LEGACY_START) or text.count(LEGACY_END):
|
errors.append(finding(relative, "legacy markers remain in generated output", "legacy-markers"))
|
start = text.find(START)
|
end_start = text.find(END)
|
if end_start < start:
|
errors.append(finding(relative, "managed marker order is invalid", "invalid-markers"))
|
return ""
|
return text[start : end_start + len(END)].replace("\r\n", "\n")
|
|
|
def check_references(text: str, root: Path, relative: str, errors: list[dict]) -> None:
|
for raw in PATH_REF.findall(text):
|
reference = raw.rstrip("`'\".,;:)")
|
if safe_repo_path(reference) is None:
|
errors.append(finding(relative, f"unsafe referenced path: {reference}", "unsafe-reference"))
|
continue
|
target = check_path_chain(root, reference, errors)
|
if target is not None and not target.is_file():
|
errors.append(finding(relative, f"referenced path is missing or is not a regular file: {reference}", "missing-reference"))
|
|
|
def parse_list(block: str, key: str) -> list[str]:
|
lines = block.splitlines()
|
for index, line in enumerate(lines):
|
match = re.match(rf"^-\s+{re.escape(key)}:\s*(.*)$", line)
|
if not match:
|
continue
|
inline = match.group(1).strip().strip("`")
|
if inline and inline not in {"none", "null", "[]"}:
|
return [inline]
|
values: list[str] = []
|
for child in lines[index + 1 :]:
|
child_match = re.match(r"^\s{2,}-\s+(.+)$", child)
|
if child_match:
|
value = child_match.group(1).strip().strip("`")
|
if value not in {"none", "null"}:
|
values.append(value)
|
continue
|
if child.startswith("- ") or child.startswith("### "):
|
break
|
return values
|
return []
|
|
|
def parse_scalar(block: str, key: str) -> str | None:
|
match = re.search(rf"^-\s+{re.escape(key)}:\s*`?([^`\n]+)`?\s*$", block, re.MULTILINE)
|
return match.group(1).strip() if match else None
|
|
|
def has_field(block: str, key: str) -> bool:
|
return re.search(rf"^-\s+{re.escape(key)}:\s*", block, re.MULTILINE) is not None
|
|
|
def has_cycle(dependencies: dict[str, list[str]]) -> bool:
|
visiting: set[str] = set()
|
visited: set[str] = set()
|
|
def visit(node: str) -> bool:
|
if node in visiting:
|
return True
|
if node in visited:
|
return False
|
visiting.add(node)
|
if any(visit(dependency) for dependency in dependencies.get(node, [])):
|
return True
|
visiting.remove(node)
|
visited.add(node)
|
return False
|
|
return any(visit(node) for node in dependencies)
|
|
|
def depends_on(start: str, target: str, dependencies: dict[str, list[str]]) -> bool:
|
pending = list(dependencies.get(start, []))
|
seen: set[str] = set()
|
while pending:
|
current = pending.pop()
|
if current == target:
|
return True
|
if current not in seen:
|
seen.add(current)
|
pending.extend(dependencies.get(current, []))
|
return False
|
|
|
def scope_base(scope: str) -> str:
|
return scope[:-3].rstrip("/") if scope.endswith("/**") else scope.rstrip("/")
|
|
|
def scopes_overlap(left: str, right: str) -> bool:
|
a, b = scope_base(left).casefold(), scope_base(right).casefold()
|
return a == b or a.startswith(b + "/") or b.startswith(a + "/")
|
|
|
def check_workflow(
|
text: str,
|
relative: str,
|
agent_names: set[str],
|
skill_references: set[str],
|
errors: list[dict],
|
) -> None:
|
blocks = re.findall(r"^###\s+([a-z0-9-]+):[^\n]*\n(.*?)(?=^###\s+|\Z)", text, re.MULTILINE | re.DOTALL)
|
if not blocks:
|
errors.append(finding(relative, "workflow has no parseable step headings", "missing-workflow-steps"))
|
return
|
step_ids = {step_id for step_id, _ in blocks}
|
if len(step_ids) != len(blocks):
|
errors.append(finding(relative, "workflow step ids must be unique", "duplicate-step"))
|
dependencies: dict[str, list[str]] = {}
|
metadata: dict[str, tuple[str | None, str | None, list[str]]] = {}
|
for step_id, block in blocks:
|
for field in WORKFLOW_STEP_FIELDS:
|
if not has_field(block, field):
|
errors.append(finding(relative, f"step {step_id} is missing field {field}", "missing-workflow-field"))
|
deps = parse_list(block, "depends_on")
|
dependencies[step_id] = deps
|
for dependency in deps:
|
if dependency not in step_ids:
|
errors.append(finding(relative, f"step {step_id} depends on missing step {dependency}", "missing-dependency"))
|
agent = parse_scalar(block, "agent")
|
if not agent or agent in {"none", "null"} or agent not in agent_names:
|
errors.append(finding(relative, f"step {step_id} references missing Agent {agent}", "missing-agent"))
|
skill = parse_scalar(block, "skill")
|
if skill not in {"none", "null"} and skill not in skill_references:
|
errors.append(finding(relative, f"step {step_id} references missing or invalid project Skill {skill}", "missing-workflow-skill"))
|
execution = parse_scalar(block, "execution")
|
if execution not in EXECUTION_MODES:
|
errors.append(finding(relative, f"step {step_id} has invalid execution mode {execution}", "invalid-execution"))
|
group = parse_scalar(block, "parallel_group")
|
if group in {"none", "null"}:
|
group = None
|
scopes: list[str] = []
|
for key in ("read_scope", "write_scope"):
|
for scope in parse_list(block, key):
|
if safe_repo_path(scope, allow_tree_glob=True) is None:
|
errors.append(finding(relative, f"step {step_id} has unsafe {key} {scope}", "invalid-write-scope" if key == "write_scope" else "invalid-read-scope"))
|
elif key == "write_scope":
|
scopes.append(scope)
|
if execution == "subagent-readonly" and scopes:
|
errors.append(finding(relative, f"read-only step {step_id} has a write scope", "readonly-write"))
|
metadata[step_id] = (execution, group, scopes)
|
if has_cycle(dependencies):
|
errors.append(finding(relative, "workflow dependency graph contains a cycle", "workflow-cycle"))
|
grouped: dict[str, list[str]] = {}
|
for step_id, (_, group, _) in metadata.items():
|
if group:
|
grouped.setdefault(group, []).append(step_id)
|
for group, members in grouped.items():
|
for index, left in enumerate(members):
|
for right in members[index + 1 :]:
|
if depends_on(left, right, dependencies) or depends_on(right, left, dependencies):
|
errors.append(finding(relative, f"parallel group {group} contains dependent steps {left} and {right}", "invalid-parallel-group"))
|
for left_scope in metadata[left][2]:
|
for right_scope in metadata[right][2]:
|
if scopes_overlap(left_scope, right_scope):
|
errors.append(finding(relative, f"parallel steps {left} and {right} overlap at {left_scope} / {right_scope}", "write-scope-overlap"))
|
|
|
def candidate_digest(root: Path, skill_roots: list[str], block: str, errors: list[dict]) -> str:
|
digest = hashlib.sha256()
|
digest.update(b"AGENTS.md\0")
|
digest.update(block.encode("utf-8"))
|
paths = walk_managed(root, ".ai", errors)
|
for path in sorted(set(paths), key=lambda item: item.relative_to(root).as_posix().casefold()):
|
relative = path.relative_to(root).as_posix()
|
digest.update(relative.encode("utf-8") + b"\0" + path.read_bytes())
|
return digest.hexdigest()
|
|
|
def validate(root: Path) -> dict:
|
errors: list[dict] = []
|
warnings: list[dict] = []
|
agents_path = root / "AGENTS.md"
|
manifest_path = root / ".ai" / "bootstrap-manifest.json"
|
|
check_path_chain(root, agents_path.name, errors)
|
check_path_chain(root, ".ai/bootstrap-manifest.json", errors)
|
if not agents_path.is_file() or is_reparse(agents_path):
|
errors.append(finding(agents_path.name, "managed AGENTS artifact is missing or is a reparse point", "missing-agents-md"))
|
agents_text = ""
|
else:
|
agents_text = read_utf8(agents_path, root, errors, warnings) or ""
|
block = extract_block(agents_text, errors, agents_path.name) if agents_text else ""
|
if block:
|
check_references(block, root, agents_path.name, errors)
|
|
manifest = load_manifest(manifest_path, errors, ".ai/bootstrap-manifest.json")
|
skill_roots = validate_manifest(manifest, errors, ".ai/bootstrap-manifest.json") if manifest else []
|
for forbidden in (".agent", ".agents"):
|
if (root / forbidden).exists() or (root / forbidden).is_symlink():
|
errors.append(finding(forbidden, "generated output must not create .agent or .agents", "forbidden-agent-directory"))
|
for relative in [".ai", ".ai/skills"]:
|
check_path_chain(root, relative, errors)
|
|
skills_parent = root / ".ai" / "skills"
|
skill_dirs = sorted(skills_parent.iterdir()) if skills_parent.is_dir() and not is_reparse(skills_parent) else []
|
for path in skill_dirs:
|
if not path.is_dir() or is_reparse(path):
|
errors.append(finding(path.relative_to(root).as_posix(), "expected a regular Skill directory", "invalid-managed-entry"))
|
|
agent_root = root / ".ai" / "agents"
|
workflow_root = root / ".ai" / "workflows"
|
orchestration_root = root / ".ai" / "orchestration"
|
agent_entries = sorted(agent_root.glob("*.md")) if agent_root.is_dir() and not is_reparse(agent_root) else []
|
workflow_entries = sorted(workflow_root.glob("*.md")) if workflow_root.is_dir() and not is_reparse(workflow_root) else []
|
agent_files = [path for path in agent_entries if path.is_file() and not is_reparse(path)]
|
workflow_files = [path for path in workflow_entries if path.is_file() and not is_reparse(path)]
|
for path in [*agent_entries, *workflow_entries]:
|
if not path.is_file() or is_reparse(path):
|
errors.append(finding(path.relative_to(root).as_posix(), "expected a regular Markdown file", "invalid-managed-entry"))
|
if not agent_files:
|
errors.append(finding(".ai/agents", "at least one generated Agent is required", "missing-agent"))
|
if not workflow_files:
|
errors.append(finding(".ai/workflows", "at least one generated workflow is required", "missing-workflow"))
|
existing_orchestration = {path.name for path in orchestration_root.glob("*.md")} if orchestration_root.is_dir() and not is_reparse(orchestration_root) else set()
|
for extra in existing_orchestration - ORCHESTRATION_FILES:
|
errors.append(finding(f".ai/orchestration/{extra}", "unknown orchestration policy", "invalid-orchestration"))
|
|
agent_names: set[str] = set()
|
for path in agent_files:
|
relative = path.relative_to(root).as_posix()
|
if is_reparse(path):
|
errors.append(finding(relative, "Agent must not be a symlink or junction", "reparse-point"))
|
continue
|
if not NAME.fullmatch(path.stem):
|
errors.append(finding(relative, "Agent filename must use lowercase hyphen-case", "invalid-name"))
|
agent_names.add(path.stem)
|
text = read_utf8(path, root, errors, warnings)
|
if text is not None:
|
require_headings(text, AGENT_HEADINGS, relative, errors)
|
if not check_fences(text):
|
errors.append(finding(relative, "Markdown fence is not closed", "unclosed-fence"))
|
check_references(text, root, relative, errors)
|
|
skill_files: list[Path] = []
|
skill_references = {f".ai/skills/{path.name}/SKILL.md" for path in skill_dirs if path.is_dir() and not is_reparse(path)}
|
for skill_dir in skill_dirs:
|
if not skill_dir.is_dir() or is_reparse(skill_dir):
|
continue
|
skill_file = skill_dir / "SKILL.md"
|
skill_files.append(skill_file)
|
relative = skill_file.relative_to(root).as_posix()
|
if not skill_file.is_file() or is_reparse(skill_file):
|
errors.append(finding(relative, "managed project Skill is missing or is a reparse point", "missing-skill"))
|
continue
|
text = read_utf8(skill_file, root, errors, warnings)
|
if text is None:
|
continue
|
metadata = parse_frontmatter(text)
|
if metadata is None:
|
errors.append(finding(relative, "Skill frontmatter is missing or malformed", "invalid-frontmatter"))
|
else:
|
if set(metadata) != {"name", "description"}:
|
errors.append(finding(relative, "Skill frontmatter must contain only name and description", "invalid-frontmatter"))
|
expected = skill_file.parent.name
|
if metadata.get("name") != expected or not NAME.fullmatch(expected) or len(expected) > 64:
|
errors.append(finding(relative, "Skill name must match its lowercase hyphen-case directory", "invalid-name"))
|
if not metadata.get("description"):
|
errors.append(finding(relative, "Skill description is empty", "invalid-frontmatter"))
|
require_headings(text, SKILL_HEADINGS, relative, errors)
|
if not check_fences(text):
|
errors.append(finding(relative, "Markdown fence is not closed", "unclosed-fence"))
|
check_references(text, root, relative, errors)
|
|
used_execution_modes: set[str] = set()
|
has_parallel_group = False
|
for path in workflow_files:
|
relative = path.relative_to(root).as_posix()
|
if is_reparse(path):
|
errors.append(finding(relative, "workflow must not be a symlink or junction", "reparse-point"))
|
continue
|
if not NAME.fullmatch(path.stem):
|
errors.append(finding(relative, "Workflow filename must use lowercase hyphen-case", "invalid-name"))
|
text = read_utf8(path, root, errors, warnings)
|
if text is not None:
|
require_headings(text, WORKFLOW_HEADINGS, relative, errors)
|
if not check_fences(text):
|
errors.append(finding(relative, "Markdown fence is not closed", "unclosed-fence"))
|
check_references(text, root, relative, errors)
|
check_workflow(text, relative, agent_names, skill_references, errors)
|
used_execution_modes.update(re.findall(r"^-\s+execution:\s*`?([a-z-]+)`?\s*$", text, re.MULTILINE))
|
has_parallel_group = has_parallel_group or bool(
|
re.search(r"^-\s+parallel_group:\s*`?(?!none|null)([a-z0-9-]+)`?\s*$", text, re.MULTILINE)
|
)
|
|
required_orchestration: set[str] = set()
|
if used_execution_modes - {"inline"}:
|
required_orchestration.update({"execution-policy.md", "subagent-contract.md", "context-policy.md"})
|
if "subagent-worktree" in used_execution_modes or has_parallel_group:
|
required_orchestration.add("merge-policy.md")
|
for missing in required_orchestration - existing_orchestration:
|
errors.append(finding(f".ai/orchestration/{missing}", "workflow execution requires this orchestration policy", "missing-orchestration"))
|
if orchestration_root.exists() and not existing_orchestration:
|
errors.append(finding(".ai/orchestration", "omit an empty orchestration directory", "empty-orchestration"))
|
|
if orchestration_root.is_dir() and not is_reparse(orchestration_root):
|
for path in sorted(orchestration_root.glob("*.md")):
|
if not path.is_file() or is_reparse(path):
|
errors.append(finding(path.relative_to(root).as_posix(), "expected a regular orchestration Markdown file", "invalid-managed-entry"))
|
continue
|
text = read_utf8(path, root, errors, warnings)
|
if text is not None and not check_fences(text):
|
errors.append(finding(path.relative_to(root).as_posix(), "Markdown fence is not closed", "unclosed-fence"))
|
|
actual_files = {"AGENTS.md"}
|
actual_files.update(path.relative_to(root).as_posix() for path in walk_managed(root, ".ai", errors))
|
declared_files = set(manifest.get("generated_files", [])) if isinstance(manifest.get("generated_files"), list) else set()
|
if declared_files != actual_files:
|
missing = sorted(actual_files - declared_files, key=str.casefold)
|
extra = sorted(declared_files - actual_files, key=str.casefold)
|
errors.append(finding(".ai/bootstrap-manifest.json", f"generated_files mismatch; undeclared={missing}, absent={extra}", "file-inventory-mismatch"))
|
|
digest = candidate_digest(root, skill_roots, block, errors)
|
errors.sort(key=lambda item: ((item["path"] or "").casefold(), item["code"], item["message"]))
|
warnings.sort(key=lambda item: ((item["path"] or "").casefold(), item["code"], item["message"]))
|
return {
|
"schema_version": 1,
|
"status": "failed" if errors else ("passed-with-warnings" if warnings else "passed"),
|
"candidate_digest": digest,
|
"run_id": manifest.get("run_id") if isinstance(manifest, dict) else None,
|
"blueprint_id": manifest.get("blueprint_id") if isinstance(manifest, dict) else None,
|
"errors": errors,
|
"warnings": warnings,
|
"counts": {
|
"agents": len(agent_files),
|
"project_skills": len(skill_files),
|
"workflows": len(workflow_files),
|
"orchestration_policies": len(existing_orchestration),
|
"files": len(actual_files),
|
},
|
}
|
|
|
def emit(report: dict, as_json: bool) -> None:
|
if as_json:
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
return
|
print(f"{report['status']}: {len(report['errors'])} errors, {len(report['warnings'])} warnings")
|
for item in report["errors"] + report["warnings"]:
|
print(f"{item['code']} {item['path']}: {item['message']}")
|
|
|
def main() -> int:
|
configure_stdio()
|
args = parse_args()
|
if args.manifest_only:
|
path = Path(args.manifest_only).absolute()
|
report = manifest_report(path)
|
else:
|
raw_root = Path(args.root).absolute()
|
if is_reparse(raw_root):
|
raise ValueError("root must not be a symlink or junction")
|
root = raw_root.resolve(strict=True)
|
report = validate(root)
|
emit(report, args.json)
|
return 0 if not report["errors"] else 1
|
|
|
if __name__ == "__main__":
|
try:
|
raise SystemExit(main())
|
except Exception as exc:
|
configure_stdio()
|
print(json.dumps({"status": "failed", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
|
raise SystemExit(2)
|