feat: initial commit of WMOC CEO portfolio with cruise ship parallax and seafarer document compliance platform
This commit is contained in:
95
.agents/scripts/README.md
Normal file
95
.agents/scripts/README.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# AG Kit Runtime Scripts
|
||||
|
||||
## Entry points
|
||||
|
||||
### `validate_kit.py`
|
||||
|
||||
Self-validates the `.agents/` package. It checks JSON, strict SemVer frontmatter, workflow/agent/skill references, manifest and lock synchronization, generated dependency docs, memory contracts, local Markdown links, Python syntax, referenced script paths, and documented inventory counts.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/validate_kit.py
|
||||
python .agents/scripts/validate_kit.py --json
|
||||
```
|
||||
|
||||
|
||||
### `generate_manifest.py`
|
||||
|
||||
Builds deterministic `manifest.json` and `manifest.lock.json` files from component frontmatter. Use `--check` in CI to fail on registry drift.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/generate_manifest.py
|
||||
python .agents/scripts/generate_manifest.py --check
|
||||
```
|
||||
|
||||
### `dependency_graph.py`
|
||||
|
||||
Builds `DEPENDENCY_GRAPH.md` from workflow and agent dependencies. Use `--check` to verify that the generated graph is current.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/dependency_graph.py
|
||||
python .agents/scripts/dependency_graph.py --check
|
||||
```
|
||||
|
||||
### `checklist.py`
|
||||
|
||||
Runs the fast project validation path. URL checks are automatically skipped when `--url` is not supplied.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/checklist.py .
|
||||
python .agents/scripts/checklist.py . --url http://localhost:3000
|
||||
python .agents/scripts/checklist.py . --report .agents/reports/checklist.json
|
||||
```
|
||||
|
||||
### `verify_all.py`
|
||||
|
||||
Runs the broad release suite. `--no-runtime` excludes Lighthouse and Playwright; `--no-e2e` excludes Playwright only.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/verify_all.py . --no-runtime
|
||||
python .agents/scripts/verify_all.py . --url http://localhost:3000 --report verification.json
|
||||
```
|
||||
|
||||
### `session_manager.py`
|
||||
|
||||
Prints project type, package metadata, feature hints, and file counts.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/session_manager.py status .
|
||||
```
|
||||
|
||||
### `auto_preview.py`
|
||||
|
||||
Starts, stops, or inspects a detected local preview server.
|
||||
|
||||
```bash
|
||||
python .agents/scripts/auto_preview.py start 3000
|
||||
python .agents/scripts/auto_preview.py status
|
||||
python .agents/scripts/auto_preview.py stop
|
||||
```
|
||||
|
||||
## Runtime prerequisites
|
||||
|
||||
Most scripts use only the Python standard library. Optional checks require the corresponding project tools:
|
||||
|
||||
- Lighthouse: `npm install -g lighthouse`
|
||||
- Playwright: `pip install playwright && playwright install chromium`
|
||||
- Node lint/test commands: project package manager and configured scripts
|
||||
- Python lint/test commands: project-configured tools such as Ruff, MyPy, or pytest
|
||||
|
||||
Missing URL-based tools produce a failed runtime check rather than a false pass. Missing non-applicable build outputs are reported as skipped/pass with an explanatory message.
|
||||
|
||||
## Exit-code contract
|
||||
|
||||
- `0`: check passed or was not applicable
|
||||
- `1`: findings met the configured failure threshold
|
||||
- `2`: invalid command usage or missing input path
|
||||
|
||||
The master runners use subprocess exit codes as the source of truth and can emit a full JSON report with commands, durations, stdout, stderr, and status.
|
||||
|
||||
## Regression tests
|
||||
|
||||
Toolkit scripts include regression tests for self-validation, component SemVer, manifest/lock integrity, dependency graph synchronization, memory contracts, security scanning, dependency and bundle analysis, and toolkit-root discovery.
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s .agents/scripts/tests -v
|
||||
```
|
||||
149
.agents/scripts/auto_preview.py
Normal file
149
.agents/scripts/auto_preview.py
Normal file
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Auto Preview - AG Kit
|
||||
==============================
|
||||
Manages (start/stop/status) the local development server for previewing the application.
|
||||
|
||||
Usage:
|
||||
python .agents/scripts/auto_preview.py start [port]
|
||||
python .agents/scripts/auto_preview.py stop
|
||||
python .agents/scripts/auto_preview.py status
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import signal
|
||||
import argparse
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
# Detect agent directory name dynamically
|
||||
AGENT_DIR = Path(".agents") if Path(".agents").exists() else Path(".agents")
|
||||
PID_FILE = AGENT_DIR / "preview.pid"
|
||||
LOG_FILE = AGENT_DIR / "preview.log"
|
||||
|
||||
def get_project_root():
|
||||
return Path(".").resolve()
|
||||
|
||||
def is_running(pid):
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def get_start_command(root):
|
||||
pkg_file = root / "package.json"
|
||||
if not pkg_file.exists():
|
||||
return None
|
||||
|
||||
with open(pkg_file, 'r') as f:
|
||||
data = json.load(f)
|
||||
|
||||
scripts = data.get("scripts", {})
|
||||
if "dev" in scripts:
|
||||
return ["npm", "run", "dev"]
|
||||
elif "start" in scripts:
|
||||
return ["npm", "start"]
|
||||
return None
|
||||
|
||||
def start_server(port=3000):
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
pid = int(PID_FILE.read_text().strip())
|
||||
if is_running(pid):
|
||||
print(f"⚠️ Preview already running (PID: {pid})")
|
||||
return
|
||||
except:
|
||||
pass # Invalid PID file
|
||||
|
||||
root = get_project_root()
|
||||
cmd = get_start_command(root)
|
||||
|
||||
if not cmd:
|
||||
print("❌ No 'dev' or 'start' script found in package.json")
|
||||
sys.exit(1)
|
||||
|
||||
# Add port env var if needed (simple heuristic)
|
||||
env = os.environ.copy()
|
||||
env["PORT"] = str(port)
|
||||
|
||||
print(f"🚀 Starting preview on port {port}...")
|
||||
|
||||
with open(LOG_FILE, "w") as log:
|
||||
process = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root),
|
||||
stdout=log,
|
||||
stderr=log,
|
||||
env=env,
|
||||
shell=True # Required for npm on windows often, or consistent path handling
|
||||
)
|
||||
|
||||
PID_FILE.write_text(str(process.pid))
|
||||
print(f"✅ Preview started! (PID: {process.pid})")
|
||||
print(f" Logs: {LOG_FILE}")
|
||||
print(f" URL: http://localhost:{port}")
|
||||
|
||||
def stop_server():
|
||||
if not PID_FILE.exists():
|
||||
print("ℹ️ No preview server found.")
|
||||
return
|
||||
|
||||
try:
|
||||
pid = int(PID_FILE.read_text().strip())
|
||||
if is_running(pid):
|
||||
# Try gentle kill first
|
||||
os.kill(pid, signal.SIGTERM) if sys.platform != 'win32' else subprocess.call(['taskkill', '/F', '/T', '/PID', str(pid)])
|
||||
print(f"🛑 Preview stopped (PID: {pid})")
|
||||
else:
|
||||
print("ℹ️ Process was not running.")
|
||||
except Exception as e:
|
||||
print(f"❌ Error stopping server: {e}")
|
||||
finally:
|
||||
if PID_FILE.exists():
|
||||
PID_FILE.unlink()
|
||||
|
||||
def status_server():
|
||||
running = False
|
||||
pid = None
|
||||
url = "Unknown"
|
||||
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
pid = int(PID_FILE.read_text().strip())
|
||||
if is_running(pid):
|
||||
running = True
|
||||
# Heuristic for URL, strictly we should save it
|
||||
url = "http://localhost:3000"
|
||||
except:
|
||||
pass
|
||||
|
||||
print("\n=== Preview Status ===")
|
||||
if running:
|
||||
print(f"✅ Status: Running")
|
||||
print(f"🔢 PID: {pid}")
|
||||
print(f"🌐 URL: {url} (Likely)")
|
||||
print(f"📝 Logs: {LOG_FILE}")
|
||||
else:
|
||||
print("⚪ Status: Stopped")
|
||||
print("===================\n")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["start", "stop", "status"])
|
||||
parser.add_argument("port", nargs="?", default="3000")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.action == "start":
|
||||
start_server(int(args.port))
|
||||
elif args.action == "stop":
|
||||
stop_server()
|
||||
elif args.action == "status":
|
||||
status_server()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
75
.agents/scripts/checklist.py
Executable file
75
.agents/scripts/checklist.py
Executable file
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the fast AG Kit validation checklist."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from validation_runner import (
|
||||
CONSOLE,
|
||||
CheckSpec,
|
||||
execute_suite,
|
||||
locate_toolkit_root,
|
||||
print_summary,
|
||||
write_report,
|
||||
)
|
||||
|
||||
CORE_CHECKS = (
|
||||
CheckSpec(
|
||||
"Security Scan",
|
||||
"skills/vulnerability-scanner/scripts/security_scan.py",
|
||||
"P0 Security",
|
||||
required=True,
|
||||
args=("--output", "summary", "--fail-on", "high"),
|
||||
),
|
||||
CheckSpec("Lint Check", "skills/lint-and-validate/scripts/lint_runner.py", "P1 Code Quality", required=True),
|
||||
CheckSpec("Type Coverage", "skills/lint-and-validate/scripts/type_coverage.py", "P1 Code Quality"),
|
||||
CheckSpec("Schema Validation", "skills/database-design/scripts/schema_validator.py", "P2 Data Layer"),
|
||||
CheckSpec("Test Runner", "skills/testing-patterns/scripts/test_runner.py", "P3 Testing"),
|
||||
CheckSpec("UX Audit", "skills/frontend-design/scripts/ux_audit.py", "P4 UX & Accessibility"),
|
||||
CheckSpec("Accessibility Check", "skills/frontend-design/scripts/accessibility_checker.py", "P4 UX & Accessibility"),
|
||||
CheckSpec("SEO Check", "skills/seo-fundamentals/scripts/seo_checker.py", "P5 SEO"),
|
||||
)
|
||||
|
||||
URL_CHECKS = (
|
||||
CheckSpec("Lighthouse Audit", "skills/performance-profiling/scripts/lighthouse_audit.py", "P6 Runtime Checks", target="url", required=True, timeout=180),
|
||||
CheckSpec("Playwright Smoke Test", "skills/webapp-testing/scripts/playwright_runner.py", "P6 Runtime Checks", target="url", timeout=120),
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Run the fast AG Kit validation checklist")
|
||||
parser.add_argument("project", nargs="?", default=".", help="Project path to validate")
|
||||
parser.add_argument("--url", help="Running application URL for Lighthouse and Playwright")
|
||||
parser.add_argument("--skip-runtime", action="store_true", help="Skip URL-based runtime checks")
|
||||
parser.add_argument("--stop-on-fail", action="store_true", help="Stop after the first failed check")
|
||||
parser.add_argument("--report", type=Path, help="Write a machine-readable JSON report")
|
||||
args = parser.parse_args()
|
||||
|
||||
project = Path(args.project).resolve()
|
||||
if not project.is_dir():
|
||||
parser.error(f"Project directory does not exist: {project}")
|
||||
|
||||
try:
|
||||
toolkit_root = locate_toolkit_root(project, __file__)
|
||||
except FileNotFoundError as exc:
|
||||
parser.error(str(exc))
|
||||
|
||||
started = datetime.now(timezone.utc)
|
||||
CONSOLE.header("AG KIT - FAST CHECKLIST")
|
||||
print(f"Project: {project}\nToolkit: {toolkit_root}\nURL: {args.url or 'not provided'}")
|
||||
|
||||
specs = list(CORE_CHECKS)
|
||||
if not args.skip_runtime:
|
||||
specs.extend(URL_CHECKS)
|
||||
results = execute_suite(specs, toolkit_root, project, args.url, args.stop_on_fail)
|
||||
success = print_summary("CHECKLIST SUMMARY", results, started)
|
||||
if args.report:
|
||||
write_report(args.report.resolve(), project, toolkit_root, results, started)
|
||||
print(f"Report: {args.report.resolve()}")
|
||||
return 0 if success else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
238
.agents/scripts/component_registry.py
Normal file
238
.agents/scripts/component_registry.py
Normal file
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build deterministic AG Kit component and runtime metadata."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError: # pragma: no cover
|
||||
yaml = None
|
||||
|
||||
SEMVER_RE = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$")
|
||||
|
||||
|
||||
def extract_frontmatter(path: Path) -> str:
|
||||
text = path.read_text("utf-8", errors="replace")
|
||||
if not text.startswith("---\n"):
|
||||
raise ValueError(f"Missing YAML frontmatter: {path}")
|
||||
end = text.find("\n---\n", 4)
|
||||
if end < 0:
|
||||
raise ValueError(f"Unterminated YAML frontmatter: {path}")
|
||||
return text[4:end]
|
||||
|
||||
|
||||
def _fallback_frontmatter(raw: str) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {}
|
||||
for line in raw.splitlines():
|
||||
if not line or line[0].isspace() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line)
|
||||
if match:
|
||||
key, value = match.groups()
|
||||
data[key] = value.strip().strip('"\'')
|
||||
return data
|
||||
|
||||
|
||||
def load_frontmatter(path: Path) -> dict[str, Any]:
|
||||
raw = extract_frontmatter(path)
|
||||
if yaml is not None:
|
||||
loaded = yaml.safe_load(raw)
|
||||
if not isinstance(loaded, dict):
|
||||
raise ValueError(f"Frontmatter must be a mapping: {path}")
|
||||
return dict(loaded)
|
||||
return _fallback_frontmatter(raw)
|
||||
|
||||
|
||||
def normalize_list(value: object) -> list[str]:
|
||||
if isinstance(value, list):
|
||||
return [str(item).strip() for item in value if str(item).strip()]
|
||||
if isinstance(value, str):
|
||||
return [item.strip() for item in value.split(",") if item.strip()]
|
||||
return []
|
||||
|
||||
|
||||
def is_semver(value: object) -> bool:
|
||||
return isinstance(value, str) and SEMVER_RE.fullmatch(value) is not None
|
||||
|
||||
|
||||
def compatible_range(version: str) -> str:
|
||||
match = SEMVER_RE.fullmatch(version)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid SemVer: {version}")
|
||||
return version if int(match.group(1)) == 0 else f"^{version}"
|
||||
|
||||
|
||||
def version_satisfies(version: str, constraint: str) -> bool:
|
||||
match = SEMVER_RE.fullmatch(version)
|
||||
if not match:
|
||||
return False
|
||||
current = tuple(int(match.group(i)) for i in range(1, 4))
|
||||
if constraint.startswith("^"):
|
||||
base_match = SEMVER_RE.fullmatch(constraint[1:])
|
||||
if not base_match:
|
||||
return False
|
||||
base = tuple(int(base_match.group(i)) for i in range(1, 4))
|
||||
if base[0] > 0:
|
||||
return current >= base and current[0] == base[0]
|
||||
if base[1] > 0:
|
||||
return current >= base and current[:2] == base[:2]
|
||||
return current == base
|
||||
return constraint == version
|
||||
|
||||
|
||||
def _relative(root: Path, path: Path) -> str:
|
||||
return path.relative_to(root).as_posix()
|
||||
|
||||
|
||||
def _runtime_manifest(root: Path) -> dict[str, Any]:
|
||||
path = root / "antigravity.json"
|
||||
if not path.is_file():
|
||||
raise ValueError("Missing Antigravity runtime contract: antigravity.json")
|
||||
data = json.loads(path.read_text("utf-8"))
|
||||
if data.get("runtime") != "antigravity":
|
||||
raise ValueError("antigravity.json runtime must be 'antigravity'")
|
||||
return {
|
||||
"path": "antigravity.json",
|
||||
"schemaVersion": data.get("schemaVersion"),
|
||||
"requiredCliCommands": data.get("requiredCliCommands", []),
|
||||
"phases": data.get("phases", {}),
|
||||
}
|
||||
|
||||
|
||||
def build_manifest(root: Path) -> dict[str, Any]:
|
||||
root = root.resolve()
|
||||
kit_version = (root / "VERSION").read_text("utf-8").strip()
|
||||
|
||||
skills: dict[str, dict[str, Any]] = {}
|
||||
for path in sorted((root / "skills").glob("*/SKILL.md")):
|
||||
data = load_frontmatter(path)
|
||||
name = path.parent.name
|
||||
version = str(data.get("version", ""))
|
||||
skills[name] = {
|
||||
"path": _relative(root, path),
|
||||
"version": version,
|
||||
"allowedTools": normalize_list(data.get("allowed-tools")),
|
||||
"scripts": sorted(_relative(root, item) for item in path.parent.glob("scripts/*.py")),
|
||||
}
|
||||
|
||||
agents: dict[str, dict[str, Any]] = {}
|
||||
for path in sorted((root / "agent").glob("*.md")):
|
||||
data = load_frontmatter(path)
|
||||
dependencies: dict[str, str] = {}
|
||||
for skill_name in normalize_list(data.get("skills")):
|
||||
skill_version = str(skills.get(skill_name, {}).get("version", "0.0.0"))
|
||||
dependencies[skill_name] = compatible_range(skill_version) if is_semver(skill_version) else skill_version
|
||||
agents[path.stem] = {
|
||||
"path": _relative(root, path),
|
||||
"version": str(data.get("version", "")),
|
||||
"model": str(data.get("model", "inherit")),
|
||||
"tools": normalize_list(data.get("tools")),
|
||||
"requires": {"skills": dependencies},
|
||||
}
|
||||
|
||||
workflows: dict[str, dict[str, Any]] = {}
|
||||
for path in sorted((root / "workflows").glob("*.md")):
|
||||
data = load_frontmatter(path)
|
||||
workflows[path.stem] = {
|
||||
"path": _relative(root, path),
|
||||
"version": str(data.get("version", "")),
|
||||
"requires": {
|
||||
"agents": normalize_list(data.get("requires_agents")),
|
||||
"skills": normalize_list(data.get("requires_skills")),
|
||||
},
|
||||
"artifactOutputs": normalize_list(data.get("artifact_outputs")),
|
||||
}
|
||||
|
||||
rules: dict[str, dict[str, Any]] = {}
|
||||
for path in sorted((root / "rules").glob("*.md")):
|
||||
data = load_frontmatter(path)
|
||||
rules[path.stem] = {
|
||||
"path": _relative(root, path),
|
||||
"version": str(data.get("version", "")),
|
||||
"priority": str(data.get("priority", "")),
|
||||
"trigger": str(data.get("trigger", "")),
|
||||
}
|
||||
|
||||
return {
|
||||
"$schema": "schemas/manifest.schema.json",
|
||||
"schemaVersion": "1.0.0",
|
||||
"kitVersion": kit_version,
|
||||
"contracts": {
|
||||
"antigravityRuntime": "1.0.0",
|
||||
"componentApi": "1.0.0",
|
||||
"memorySchema": "1.0.0",
|
||||
"rulesApi": "1.0.0",
|
||||
"workflowApi": "1.0.0",
|
||||
},
|
||||
"support": {
|
||||
"primary": "Google Antigravity",
|
||||
"official": ["Google Antigravity"],
|
||||
"bestEffort": ["Gemini CLI", "other Markdown-compatible agent tools"],
|
||||
"portableFormat": True,
|
||||
},
|
||||
"runtimes": {"antigravity": _runtime_manifest(root)},
|
||||
"agents": agents,
|
||||
"skills": skills,
|
||||
"workflows": workflows,
|
||||
"rules": rules,
|
||||
}
|
||||
|
||||
|
||||
def canonical_json(data: object) -> str:
|
||||
return json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def component_files(root: Path) -> list[Path]:
|
||||
"""Return every managed source file covered by the integrity lock."""
|
||||
root = root.resolve()
|
||||
files: list[Path] = []
|
||||
for name in (
|
||||
"VERSION",
|
||||
"README.md",
|
||||
"ARCHITECTURE.md",
|
||||
"CHANGELOG.md",
|
||||
"antigravity.json",
|
||||
"hooks.json",
|
||||
"mcp_config.json",
|
||||
):
|
||||
path = root / name
|
||||
if path.is_file():
|
||||
files.append(path)
|
||||
for directory in ("agent", "skills", "workflows", "rules", "memory", "hooks", "schemas", "scripts"):
|
||||
base = root / directory
|
||||
if not base.is_dir():
|
||||
continue
|
||||
for path in base.rglob("*"):
|
||||
if not path.is_file() or "__pycache__" in path.parts or path.suffix == ".pyc":
|
||||
continue
|
||||
files.append(path)
|
||||
return sorted({path.resolve() for path in files})
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(65536), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def build_lock(root: Path, manifest: dict[str, Any]) -> dict[str, Any]:
|
||||
root = root.resolve()
|
||||
hashes = {
|
||||
path.relative_to(root).as_posix(): sha256_file(path)
|
||||
for path in component_files(root)
|
||||
if path.name != "manifest.lock.json"
|
||||
}
|
||||
return {
|
||||
"$schema": "schemas/manifest-lock.schema.json",
|
||||
"schemaVersion": "1.0.0",
|
||||
"kitVersion": manifest["kitVersion"],
|
||||
"manifestSha256": hashlib.sha256(canonical_json(manifest).encode("utf-8")).hexdigest(),
|
||||
"components": hashes,
|
||||
}
|
||||
73
.agents/scripts/dependency_graph.py
Executable file
73
.agents/scripts/dependency_graph.py
Executable file
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a maintainable Mermaid dependency graph from manifest.json."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from component_registry import build_manifest
|
||||
|
||||
|
||||
def node_id(prefix: str, name: str) -> str:
|
||||
return prefix + "_" + name.replace("-", "_")
|
||||
|
||||
|
||||
def render(root: Path) -> str:
|
||||
manifest = build_manifest(root)
|
||||
lines = [
|
||||
"# AG Kit Dependency Graph",
|
||||
"",
|
||||
"> Generated by `.agents/scripts/dependency_graph.py`. Do not edit manually.",
|
||||
"",
|
||||
f"Kit version: `{manifest['kitVersion']}` · {len(manifest['agents'])} agents · {len(manifest['skills'])} skills · {len(manifest['workflows'])} workflows",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" subgraph Workflows",
|
||||
]
|
||||
for name in manifest["workflows"]:
|
||||
lines.append(f' {node_id("W", name)}["/{name}"]')
|
||||
lines.extend([" end", " subgraph Agents"])
|
||||
for name in manifest["agents"]:
|
||||
lines.append(f' {node_id("A", name)}["{name}"]')
|
||||
lines.extend([" end", " subgraph Skills"])
|
||||
for name in manifest["skills"]:
|
||||
lines.append(f' {node_id("S", name)}["{name}"]')
|
||||
lines.append(" end")
|
||||
|
||||
for workflow, data in manifest["workflows"].items():
|
||||
for agent in data["requires"]["agents"]:
|
||||
lines.append(f" {node_id('W', workflow)} --> {node_id('A', agent)}")
|
||||
for skill in data["requires"]["skills"]:
|
||||
lines.append(f" {node_id('W', workflow)} -.-> {node_id('S', skill)}")
|
||||
for agent, data in manifest["agents"].items():
|
||||
for skill in data["requires"]["skills"]:
|
||||
lines.append(f" {node_id('A', agent)} --> {node_id('S', skill)}")
|
||||
lines.extend(["```", "", "## Contracts", ""])
|
||||
for key, value in manifest["contracts"].items():
|
||||
lines.append(f"- `{key}`: `{value}`")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Generate AG Kit dependency graph")
|
||||
parser.add_argument("path", nargs="?", default=None, help="Path to .agents")
|
||||
parser.add_argument("--check", action="store_true", help="Fail when DEPENDENCY_GRAPH.md is stale")
|
||||
args = parser.parse_args()
|
||||
root = Path(args.path).resolve() if args.path else Path(__file__).resolve().parents[1]
|
||||
output = root / "DEPENDENCY_GRAPH.md"
|
||||
expected = render(root)
|
||||
if args.check:
|
||||
if not output.is_file() or output.read_text("utf-8") != expected:
|
||||
print("DEPENDENCY_GRAPH.md is stale")
|
||||
return 1
|
||||
print("Dependency graph is synchronized.")
|
||||
return 0
|
||||
output.write_text(expected, "utf-8")
|
||||
print(f"Wrote {output}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
44
.agents/scripts/generate_manifest.py
Executable file
44
.agents/scripts/generate_manifest.py
Executable file
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate or verify the AG Kit component registry and lock file."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from component_registry import build_lock, build_manifest, canonical_json
|
||||
|
||||
|
||||
def check_file(path: Path, expected: str) -> bool:
|
||||
return path.is_file() and path.read_text("utf-8") == expected
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Generate AG Kit manifest.json and manifest.lock.json")
|
||||
parser.add_argument("path", nargs="?", default=None, help="Path to .agents")
|
||||
parser.add_argument("--check", action="store_true", help="Fail when generated files are stale")
|
||||
args = parser.parse_args()
|
||||
|
||||
root = Path(args.path).resolve() if args.path else Path(__file__).resolve().parents[1]
|
||||
manifest = build_manifest(root)
|
||||
manifest_text = canonical_json(manifest)
|
||||
lock = build_lock(root, manifest)
|
||||
lock_text = canonical_json(lock)
|
||||
outputs = [(root / "manifest.json", manifest_text), (root / "manifest.lock.json", lock_text)]
|
||||
|
||||
if args.check:
|
||||
stale = [path.name for path, expected in outputs if not check_file(path, expected)]
|
||||
if stale:
|
||||
print("Stale generated registry files: " + ", ".join(stale))
|
||||
return 1
|
||||
print("Component registry is synchronized.")
|
||||
return 0
|
||||
|
||||
for path, content in outputs:
|
||||
path.write_text(content, "utf-8")
|
||||
print(f"Wrote {path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
120
.agents/scripts/session_manager.py
Normal file
120
.agents/scripts/session_manager.py
Normal file
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Session Manager - AG Kit
|
||||
=================================
|
||||
Analyzes project state, detects tech stack, tracks file statistics, and provides
|
||||
a summary of the current session.
|
||||
|
||||
Usage:
|
||||
python .agents/scripts/session_manager.py status [path]
|
||||
python .agents/scripts/session_manager.py info [path]
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List
|
||||
|
||||
def get_project_root(path: str) -> Path:
|
||||
return Path(path).resolve()
|
||||
|
||||
def analyze_package_json(root: Path) -> Dict[str, Any]:
|
||||
pkg_file = root / "package.json"
|
||||
if not pkg_file.exists():
|
||||
return {"type": "unknown", "dependencies": {}}
|
||||
|
||||
try:
|
||||
with open(pkg_file, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
deps = data.get("dependencies", {})
|
||||
dev_deps = data.get("devDependencies", {})
|
||||
all_deps = {**deps, **dev_deps}
|
||||
|
||||
stack = []
|
||||
if "next" in all_deps: stack.append("Next.js")
|
||||
elif "react" in all_deps: stack.append("React")
|
||||
elif "vue" in all_deps: stack.append("Vue")
|
||||
elif "svelte" in all_deps: stack.append("Svelte")
|
||||
elif "express" in all_deps: stack.append("Express")
|
||||
elif "nestjs" in all_deps or "@nestjs/core" in all_deps: stack.append("NestJS")
|
||||
|
||||
if "tailwindcss" in all_deps: stack.append("Tailwind CSS")
|
||||
if "prisma" in all_deps: stack.append("Prisma")
|
||||
if "typescript" in all_deps: stack.append("TypeScript")
|
||||
|
||||
return {
|
||||
"name": data.get("name", "unnamed"),
|
||||
"version": data.get("version", "0.0.0"),
|
||||
"stack": stack,
|
||||
"scripts": list(data.get("scripts", {}).keys())
|
||||
}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
def count_files(root: Path) -> Dict[str, int]:
|
||||
stats = {"created": 0, "modified": 0, "total": 0}
|
||||
# Simple count for now, comprehensive tracking would require git diff or extensive history
|
||||
exclude = {".git", "node_modules", ".next", "dist", "build", ".agents", ".agents", ".gemini", "__pycache__"}
|
||||
|
||||
for root_dir, dirs, files in os.walk(root):
|
||||
dirs[:] = [d for d in dirs if d not in exclude]
|
||||
stats["total"] += len(files)
|
||||
|
||||
return stats
|
||||
|
||||
def detect_features(root: Path) -> List[str]:
|
||||
# Heuristic: look at folder names in src/
|
||||
features = []
|
||||
src = root / "src"
|
||||
if src.exists():
|
||||
possible_dirs = ["components", "modules", "features", "app", "pages", "services"]
|
||||
for d in possible_dirs:
|
||||
p = src / d
|
||||
if p.exists() and p.is_dir():
|
||||
# List subdirectories as likely features
|
||||
for child in p.iterdir():
|
||||
if child.is_dir():
|
||||
features.append(child.name)
|
||||
return features[:10] # Limit to top 10
|
||||
|
||||
def print_status(root: Path):
|
||||
info = analyze_package_json(root)
|
||||
stats = count_files(root)
|
||||
features = detect_features(root)
|
||||
|
||||
print("\n=== Project Status ===")
|
||||
print(f"\n📁 Project: {info.get('name', root.name)}")
|
||||
print(f"📂 Path: {root}")
|
||||
print(f"🏷️ Type: {', '.join(info.get('stack', ['Generic']))}")
|
||||
print(f"📊 Status: Active")
|
||||
|
||||
print("\n🔧 Tech Stack:")
|
||||
for tech in info.get('stack', []):
|
||||
print(f" • {tech}")
|
||||
|
||||
print(f"\n✅ Detected Modules/Features ({len(features)}):")
|
||||
for feat in features:
|
||||
print(f" • {feat}")
|
||||
if not features:
|
||||
print(" (No distinct feature modules detected)")
|
||||
|
||||
print(f"\n📄 Files: {stats['total']} total files tracked")
|
||||
print("\n====================\n")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Session Manager")
|
||||
parser.add_argument("command", choices=["status", "info"], help="Command to run")
|
||||
parser.add_argument("path", nargs="?", default=".", help="Project path")
|
||||
|
||||
args = parser.parse_args()
|
||||
root = get_project_root(args.path)
|
||||
|
||||
if args.command == "status":
|
||||
print_status(root)
|
||||
elif args.command == "info":
|
||||
print(json.dumps(analyze_package_json(root), indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
238
.agents/scripts/tests/test_toolkit.py
Normal file
238
.agents/scripts/tests/test_toolkit.py
Normal file
@@ -0,0 +1,238 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
TOOLKIT = Path(__file__).resolve().parents[2]
|
||||
SCRIPTS = TOOLKIT / "scripts"
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
|
||||
def load_module(name: str, path: Path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
validate_kit = load_module("agkit_validate_kit", SCRIPTS / "validate_kit.py")
|
||||
component_registry = sys.modules["component_registry"]
|
||||
dependency_graph = sys.modules["dependency_graph"]
|
||||
security_scan = load_module("agkit_security_scan", TOOLKIT / "skills/vulnerability-scanner/scripts/security_scan.py")
|
||||
dependency_analyzer = load_module("agkit_dependency_analyzer", TOOLKIT / "skills/vulnerability-scanner/scripts/dependency_analyzer.py")
|
||||
bundle_analyzer = load_module("agkit_bundle_analyzer", TOOLKIT / "skills/performance-profiling/scripts/bundle_analyzer.py")
|
||||
validation_runner = load_module("agkit_validation_runner", SCRIPTS / "validation_runner.py")
|
||||
geo_checker = load_module("agkit_geo_checker", TOOLKIT / "skills/geo-fundamentals/scripts/geo_checker.py")
|
||||
react_performance = load_module(
|
||||
"agkit_react_performance",
|
||||
TOOLKIT / "skills/nextjs-react-expert/scripts/react_performance_checker.py",
|
||||
)
|
||||
|
||||
|
||||
class ToolkitRegressionTests(unittest.TestCase):
|
||||
def test_toolkit_self_validation_passes(self):
|
||||
findings = validate_kit.validate(TOOLKIT)
|
||||
errors = [item for item in findings if item.severity == "error"]
|
||||
self.assertEqual([], errors)
|
||||
|
||||
def test_mcp_config_is_valid_json(self):
|
||||
data = json.loads((TOOLKIT / "mcp_config.json").read_text("utf-8"))
|
||||
self.assertIn("mcpServers", data)
|
||||
|
||||
def test_security_scanner_ignores_patterns_inside_strings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "sample.py").write_text(
|
||||
"""PATTERN = r'eval\\s*\\('
|
||||
TOKEN = 'YOUR_API_KEY'
|
||||
""",
|
||||
"utf-8",
|
||||
)
|
||||
report = security_scan.run_full_scan(str(root), "all")
|
||||
self.assertEqual(0, report["summary"]["critical"])
|
||||
self.assertEqual(0, report["summary"]["high"])
|
||||
|
||||
def test_security_scanner_detects_executable_eval_and_secret(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "bad.py").write_text(
|
||||
"""api_key = 'sk_live_12345678901234567890'
|
||||
eval(user_input)
|
||||
""",
|
||||
"utf-8",
|
||||
) # agkit: allow-secret
|
||||
report = security_scan.run_full_scan(str(root), "all")
|
||||
self.assertGreaterEqual(report["summary"]["critical"], 1)
|
||||
self.assertGreaterEqual(report["summary"]["high"], 1)
|
||||
self.assertTrue(security_scan._should_fail(report, "high"))
|
||||
|
||||
def test_security_scanner_detects_nested_nextjs_header_configuration(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "package.json").write_text('{"private":true}', "utf-8")
|
||||
web = root / "web"
|
||||
web.mkdir()
|
||||
(web / "next.config.ts").write_text(
|
||||
'const headers = [{ key: "Content-Security-Policy", value: "frame-ancestors \'none\'" }];',
|
||||
"utf-8",
|
||||
)
|
||||
report = security_scan.run_full_scan(str(root), "config")
|
||||
config = report["scans"]["configuration"]
|
||||
self.assertTrue(config["checks"]["security_headers_config"])
|
||||
self.assertFalse(any("security-header" in item.get("issue", "") for item in config["findings"]))
|
||||
|
||||
def test_dependency_analyzer_flags_missing_lock(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "package.json").write_text('{"dependencies":{"demo":"latest"}}', "utf-8")
|
||||
report = dependency_analyzer.analyze(root)
|
||||
issues = {item["issue"] for item in report["findings"]}
|
||||
self.assertIn("Missing JavaScript lock file", issues)
|
||||
self.assertIn("Unbounded dependency version", issues)
|
||||
|
||||
def test_bundle_analyzer_flags_oversized_asset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
asset = root / "dist" / "app.js"
|
||||
asset.parent.mkdir(parents=True)
|
||||
asset.write_bytes(b"x" * 2048)
|
||||
report = bundle_analyzer.analyze(root, file_warn_kib=1, file_fail_kib=2, total_fail_kib=100)
|
||||
self.assertTrue(report["findings"])
|
||||
self.assertEqual("high", report["findings"][0]["severity"])
|
||||
|
||||
def test_geo_checker_follows_localized_mdx_and_skips_layouts(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
route = root / "web" / "src" / "app" / "docs" / "demo"
|
||||
route.mkdir(parents=True)
|
||||
(route / "page.tsx").write_text(
|
||||
'import En from "./content.en.mdx";\n'
|
||||
'import Vi from "./content.vi.mdx";\n'
|
||||
'export default function Page(){ return <En />; }\n',
|
||||
"utf-8",
|
||||
)
|
||||
(route / "content.en.mdx").write_text(
|
||||
"# Demo\n\n## Overview\nText.\n\n## Usage\nText.\n",
|
||||
"utf-8",
|
||||
)
|
||||
(route / "content.vi.mdx").write_text(
|
||||
"# Trình diễn\n\n## Tổng quan\nNội dung.\n\n## Sử dụng\nNội dung.\n",
|
||||
"utf-8",
|
||||
)
|
||||
(route.parent / "layout.tsx").write_text(
|
||||
"export default function Layout({children}){return <div>{children}</div>}\n",
|
||||
"utf-8",
|
||||
)
|
||||
|
||||
pages = geo_checker.find_web_pages(root)
|
||||
self.assertEqual([route / "page.tsx"], pages)
|
||||
result = geo_checker.check_page(route / "page.tsx", root)
|
||||
self.assertGreaterEqual(result["score"], 60)
|
||||
self.assertFalse(any("Multiple H1" in issue for issue in result["issues"]))
|
||||
|
||||
def test_react_checker_ignores_generated_next_output(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
web = root / "web"
|
||||
source = web / "src" / "app"
|
||||
generated = web / ".next" / "types"
|
||||
source.mkdir(parents=True)
|
||||
generated.mkdir(parents=True)
|
||||
(web / "package.json").write_text(
|
||||
'{"dependencies":{"next":"16.2.10","react":"19.2.3"}}',
|
||||
"utf-8",
|
||||
)
|
||||
(source / "page.tsx").write_text(
|
||||
"export default function Page(){return <main><h1>Safe</h1></main>}\n",
|
||||
"utf-8",
|
||||
)
|
||||
(generated / "page.ts").write_text(
|
||||
"async function generated(){await one();\nawait two();}\n",
|
||||
"utf-8",
|
||||
)
|
||||
|
||||
checker = react_performance.PerformanceChecker(str(root))
|
||||
# Resolve paths: macOS temp dirs use /var -> /private/var symlinks.
|
||||
scanned = {path.resolve() for path in checker._iter_files(["ts", "tsx"])}
|
||||
self.assertIn((source / "page.tsx").resolve(), scanned)
|
||||
self.assertNotIn((generated / "page.ts").resolve(), scanned)
|
||||
self.assertTrue(checker.run())
|
||||
self.assertEqual([], checker.issues)
|
||||
|
||||
def test_runner_finds_embedded_toolkit_for_external_project(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
project = Path(tmp)
|
||||
located = validation_runner.locate_toolkit_root(project, str(SCRIPTS / "checklist.py"))
|
||||
self.assertEqual(TOOLKIT, located)
|
||||
|
||||
def test_all_components_use_strict_semver(self):
|
||||
manifest = component_registry.build_manifest(TOOLKIT)
|
||||
for group in ("agents", "skills", "workflows", "rules"):
|
||||
with self.subTest(group=group):
|
||||
invalid = {
|
||||
name: data["version"]
|
||||
for name, data in manifest[group].items()
|
||||
if not component_registry.is_semver(data["version"])
|
||||
}
|
||||
self.assertEqual({}, invalid)
|
||||
|
||||
def test_component_registry_and_lock_are_synchronized(self):
|
||||
manifest = component_registry.build_manifest(TOOLKIT)
|
||||
lock = component_registry.build_lock(TOOLKIT, manifest)
|
||||
self.assertEqual(manifest, json.loads((TOOLKIT / "manifest.json").read_text("utf-8")))
|
||||
self.assertEqual(lock, json.loads((TOOLKIT / "manifest.lock.json").read_text("utf-8")))
|
||||
|
||||
def test_dependency_graph_is_synchronized(self):
|
||||
expected = dependency_graph.render(TOOLKIT)
|
||||
self.assertEqual(expected, (TOOLKIT / "DEPENDENCY_GRAPH.md").read_text("utf-8"))
|
||||
|
||||
def test_workflow_dependencies_resolve(self):
|
||||
manifest = component_registry.build_manifest(TOOLKIT)
|
||||
agents = set(manifest["agents"])
|
||||
skills = set(manifest["skills"])
|
||||
for name, workflow in manifest["workflows"].items():
|
||||
with self.subTest(workflow=name):
|
||||
self.assertLessEqual(set(workflow["requires"]["agents"]), agents)
|
||||
self.assertLessEqual(set(workflow["requires"]["skills"]), skills)
|
||||
self.assertTrue(workflow["artifactOutputs"])
|
||||
|
||||
def test_orchestration_guidance_is_antigravity_first_and_bounded(self):
|
||||
orchestrator = (TOOLKIT / "agent/orchestrator.md").read_text("utf-8")
|
||||
parallel = (TOOLKIT / "skills/parallel-agents/SKILL.md").read_text("utf-8")
|
||||
combined = orchestrator + "\n" + parallel
|
||||
|
||||
self.assertNotIn("Claude Code's native Agent Tool", combined)
|
||||
self.assertNotIn("Claude orchestrates autonomously", combined)
|
||||
self.assertNotIn("**Explore** | Haiku", combined)
|
||||
self.assertNotIn("**Plan** | Sonnet", combined)
|
||||
self.assertIn("Google Antigravity is the primary production runtime", combined)
|
||||
self.assertIn("max_delegation_depth", combined)
|
||||
self.assertIn("Never allow an open-ended ReAct", combined)
|
||||
self.assertIn("isolated worktree", combined)
|
||||
self.assertIn("untrusted data", combined)
|
||||
|
||||
def test_caret_semver_resolution(self):
|
||||
self.assertTrue(component_registry.version_satisfies("1.4.2", "^1.2.0"))
|
||||
self.assertFalse(component_registry.version_satisfies("2.0.0", "^1.2.0"))
|
||||
self.assertTrue(component_registry.version_satisfies("0.3.5", "^0.3.1"))
|
||||
self.assertFalse(component_registry.version_satisfies("0.4.0", "^0.3.1"))
|
||||
|
||||
def test_memory_topics_are_present(self):
|
||||
topics = {
|
||||
"project-conventions.md",
|
||||
"user-preferences.md",
|
||||
"tech-decisions.md",
|
||||
"feedback-history.md",
|
||||
}
|
||||
self.assertLessEqual(topics, {path.name for path in (TOOLKIT / "memory").glob("*.md")})
|
||||
self.assertLessEqual(len((TOOLKIT / "memory/MEMORY.md").read_text("utf-8").splitlines()), 200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
397
.agents/scripts/validate_kit.py
Executable file
397
.agents/scripts/validate_kit.py
Executable file
@@ -0,0 +1,397 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Self-validate an AG Kit installation.
|
||||
|
||||
Checks machine-readable configuration, versioned frontmatter contracts,
|
||||
cross references, generated registries, local Markdown links, memory schema,
|
||||
Python syntax, and architecture inventory counts.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError: # pragma: no cover - optional enhancement
|
||||
yaml = None
|
||||
|
||||
from component_registry import (
|
||||
build_lock,
|
||||
build_manifest,
|
||||
canonical_json,
|
||||
is_semver,
|
||||
normalize_list,
|
||||
version_satisfies,
|
||||
)
|
||||
from dependency_graph import render as render_dependency_graph
|
||||
|
||||
|
||||
@dataclass
|
||||
class Finding:
|
||||
severity: str
|
||||
code: str
|
||||
file: str
|
||||
line: int
|
||||
message: str
|
||||
|
||||
|
||||
REQUIRED_FIELDS = {
|
||||
"agent": {"name", "description", "tools", "model", "skills", "version"},
|
||||
"skill": {"name", "description", "when_to_use", "allowed-tools", "version"},
|
||||
"workflow": {
|
||||
"name",
|
||||
"description",
|
||||
"version",
|
||||
"requires_agents",
|
||||
"requires_skills",
|
||||
"artifact_outputs",
|
||||
},
|
||||
"rule": {"name", "trigger", "version", "priority"},
|
||||
}
|
||||
|
||||
|
||||
def add(findings: list[Finding], severity: str, code: str, path: Path, message: str, line: int = 1) -> None:
|
||||
findings.append(Finding(severity, code, path.as_posix(), line, message))
|
||||
|
||||
|
||||
def extract_frontmatter(path: Path) -> tuple[str | None, int]:
|
||||
text = path.read_text("utf-8", errors="replace")
|
||||
if not text.startswith("---\n"):
|
||||
return None, 1
|
||||
end = text.find("\n---\n", 4)
|
||||
if end < 0:
|
||||
return None, 1
|
||||
return text[4:end], 1
|
||||
|
||||
|
||||
def fallback_frontmatter(raw: str) -> dict[str, object]:
|
||||
data: dict[str, object] = {}
|
||||
for line in raw.splitlines():
|
||||
if not line or line[0].isspace() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line)
|
||||
if not match:
|
||||
continue
|
||||
key, value = match.groups()
|
||||
data[key] = value.strip().strip('"\'')
|
||||
return data
|
||||
|
||||
|
||||
def parse_frontmatter(path: Path, findings: list[Finding]) -> dict[str, object] | None:
|
||||
raw, _ = extract_frontmatter(path)
|
||||
if raw is None:
|
||||
add(findings, "error", "frontmatter.missing", path, "Missing or unterminated YAML frontmatter")
|
||||
return None
|
||||
if yaml is None:
|
||||
return fallback_frontmatter(raw)
|
||||
try:
|
||||
data = yaml.safe_load(raw)
|
||||
except Exception as exc:
|
||||
line = int(getattr(getattr(exc, "problem_mark", None), "line", 0)) + 2
|
||||
add(findings, "error", "frontmatter.invalid_yaml", path, str(exc), line)
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
add(findings, "error", "frontmatter.not_mapping", path, "Frontmatter must be a YAML mapping")
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def validate_json(root: Path, findings: list[Finding]) -> None:
|
||||
for path in root.rglob("*.json"):
|
||||
if "__pycache__" in path.parts:
|
||||
continue
|
||||
try:
|
||||
json.loads(path.read_text("utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
line = int(getattr(exc, "lineno", 1))
|
||||
add(findings, "error", "json.invalid", path.relative_to(root), str(exc), line)
|
||||
|
||||
|
||||
def validate_kit_version(root: Path, findings: list[Finding]) -> None:
|
||||
version_path = root / "VERSION"
|
||||
if not version_path.is_file():
|
||||
add(findings, "error", "version.missing", Path("VERSION"), "VERSION is missing")
|
||||
return
|
||||
value = version_path.read_text("utf-8").strip()
|
||||
if not re.fullmatch(r"\d{4}\.\d{1,2}\.\d{1,2}", value):
|
||||
add(findings, "error", "version.invalid_calver", Path("VERSION"), f"Expected YYYY.M.D CalVer, got {value!r}")
|
||||
|
||||
|
||||
def validate_frontmatter(
|
||||
root: Path, findings: list[Finding]
|
||||
) -> tuple[
|
||||
dict[str, dict[str, object]],
|
||||
dict[str, dict[str, object]],
|
||||
dict[str, dict[str, object]],
|
||||
dict[str, dict[str, object]],
|
||||
]:
|
||||
agents: dict[str, dict[str, object]] = {}
|
||||
skills: dict[str, dict[str, object]] = {}
|
||||
workflows: dict[str, dict[str, object]] = {}
|
||||
rules: dict[str, dict[str, object]] = {}
|
||||
groups = (
|
||||
("agent", sorted((root / "agent").glob("*.md"))),
|
||||
("skill", sorted((root / "skills").glob("*/SKILL.md"))),
|
||||
("workflow", sorted((root / "workflows").glob("*.md"))),
|
||||
("rule", sorted((root / "rules").glob("*.md"))),
|
||||
)
|
||||
registries = {"agent": agents, "skill": skills, "workflow": workflows, "rule": rules}
|
||||
for kind, paths in groups:
|
||||
names_seen: set[str] = set()
|
||||
for path in paths:
|
||||
rel = path.relative_to(root)
|
||||
data = parse_frontmatter(path, findings)
|
||||
if data is None:
|
||||
continue
|
||||
missing = REQUIRED_FIELDS[kind] - set(data)
|
||||
for field in sorted(missing):
|
||||
add(findings, "error", "frontmatter.required_field", rel, f"Missing required field: {field}")
|
||||
name = str(data.get("name", ""))
|
||||
expected = path.parent.name if kind == "skill" else path.stem
|
||||
if name != expected:
|
||||
add(findings, "error", "frontmatter.name_mismatch", rel, f"name={name!r}, expected {expected!r}")
|
||||
if name:
|
||||
if name in names_seen:
|
||||
add(findings, "error", "frontmatter.duplicate_name", rel, f"Duplicate {kind} name: {name}")
|
||||
names_seen.add(name)
|
||||
version = data.get("version")
|
||||
if version is not None and not is_semver(str(version)):
|
||||
add(findings, "error", "frontmatter.invalid_semver", rel, f"Invalid SemVer: {version!r}")
|
||||
registries[kind][expected] = data
|
||||
return agents, skills, workflows, rules
|
||||
|
||||
|
||||
def validate_references(
|
||||
root: Path,
|
||||
agents: dict[str, dict[str, object]],
|
||||
skills: dict[str, dict[str, object]],
|
||||
workflows: dict[str, dict[str, object]],
|
||||
findings: list[Finding],
|
||||
) -> None:
|
||||
for agent_name, data in agents.items():
|
||||
path = Path("agent") / f"{agent_name}.md"
|
||||
for skill in normalize_list(data.get("skills")):
|
||||
if skill not in skills:
|
||||
add(findings, "error", "reference.unknown_skill", path, f"Agent references missing skill: {skill}")
|
||||
|
||||
for workflow_name, data in workflows.items():
|
||||
path = Path("workflows") / f"{workflow_name}.md"
|
||||
for agent in normalize_list(data.get("requires_agents")):
|
||||
if agent not in agents:
|
||||
add(findings, "error", "reference.unknown_agent", path, f"Workflow references missing agent: {agent}")
|
||||
for skill in normalize_list(data.get("requires_skills")):
|
||||
if skill not in skills:
|
||||
add(findings, "error", "reference.unknown_skill", path, f"Workflow references missing skill: {skill}")
|
||||
if not normalize_list(data.get("artifact_outputs")):
|
||||
add(findings, "warning", "workflow.no_outputs", path, "Workflow declares no artifact outputs")
|
||||
|
||||
script_pattern = re.compile(r'["\']((?:skills|scripts)/[^"\']+?\.py)["\']')
|
||||
for path in (root / "scripts").glob("*.py"):
|
||||
text = path.read_text("utf-8", errors="replace")
|
||||
for match in script_pattern.finditer(text):
|
||||
if any(char in match.group(1) for char in "*?["):
|
||||
continue
|
||||
target = root / match.group(1)
|
||||
if not target.is_file():
|
||||
line = text.count("\n", 0, match.start()) + 1
|
||||
add(findings, "error", "reference.missing_script", path.relative_to(root), f"Referenced script does not exist: {match.group(1)}", line)
|
||||
|
||||
|
||||
def validate_manifest(root: Path, findings: list[Finding]) -> None:
|
||||
manifest_path = root / "manifest.json"
|
||||
lock_path = root / "manifest.lock.json"
|
||||
if not manifest_path.is_file():
|
||||
add(findings, "error", "manifest.missing", Path("manifest.json"), "Run scripts/generate_manifest.py")
|
||||
return
|
||||
if not lock_path.is_file():
|
||||
add(findings, "error", "manifest.lock_missing", Path("manifest.lock.json"), "Run scripts/generate_manifest.py")
|
||||
return
|
||||
try:
|
||||
actual_manifest = json.loads(manifest_path.read_text("utf-8"))
|
||||
actual_lock = json.loads(lock_path.read_text("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
try:
|
||||
expected_manifest = build_manifest(root)
|
||||
expected_lock = build_lock(root, expected_manifest)
|
||||
except Exception as exc:
|
||||
add(findings, "error", "manifest.generation_failed", Path("manifest.json"), str(exc))
|
||||
return
|
||||
if actual_manifest != expected_manifest:
|
||||
add(findings, "error", "manifest.stale", Path("manifest.json"), "Registry differs from component frontmatter; regenerate it")
|
||||
if actual_lock != expected_lock:
|
||||
add(findings, "error", "manifest.lock_stale", Path("manifest.lock.json"), "Lock differs from current component files; regenerate it")
|
||||
|
||||
skill_versions = {name: data["version"] for name, data in expected_manifest["skills"].items()}
|
||||
for agent_name, agent in expected_manifest["agents"].items():
|
||||
for skill_name, constraint in agent["requires"]["skills"].items():
|
||||
version = skill_versions.get(skill_name)
|
||||
if version and not version_satisfies(version, constraint):
|
||||
add(
|
||||
findings,
|
||||
"error",
|
||||
"manifest.incompatible_dependency",
|
||||
Path(agent["path"]),
|
||||
f"{skill_name} {version} does not satisfy {constraint}",
|
||||
)
|
||||
|
||||
|
||||
def validate_generated_docs(root: Path, findings: list[Finding]) -> None:
|
||||
path = root / "DEPENDENCY_GRAPH.md"
|
||||
if not path.is_file():
|
||||
add(findings, "error", "graph.missing", Path("DEPENDENCY_GRAPH.md"), "Run scripts/dependency_graph.py")
|
||||
return
|
||||
expected = render_dependency_graph(root)
|
||||
if path.read_text("utf-8") != expected:
|
||||
add(findings, "error", "graph.stale", Path("DEPENDENCY_GRAPH.md"), "Dependency graph is stale")
|
||||
|
||||
|
||||
def validate_markdown_links(root: Path, findings: list[Finding]) -> None:
|
||||
pattern = re.compile(r"!?\[[^\]]*\]\(([^)]+)\)")
|
||||
for path in root.rglob("*.md"):
|
||||
text = path.read_text("utf-8", errors="replace")
|
||||
for match in pattern.finditer(text):
|
||||
raw = match.group(1).strip()
|
||||
if not raw:
|
||||
continue
|
||||
target_text = raw.split()[0].strip("<>")
|
||||
if target_text.startswith(("#", "http://", "https://", "mailto:", "tel:", "data:")):
|
||||
continue
|
||||
target_text = unquote(target_text.split("#", 1)[0])
|
||||
if not target_text:
|
||||
continue
|
||||
target = (path.parent / target_text).resolve()
|
||||
try:
|
||||
target.relative_to(root.resolve())
|
||||
except ValueError:
|
||||
continue
|
||||
if path.relative_to(root).as_posix() == "skills/documentation-templates/SKILL.md" and target_text.startswith("./docs/"):
|
||||
continue
|
||||
if not target.exists():
|
||||
line = text.count("\n", 0, match.start()) + 1
|
||||
add(findings, "error", "markdown.missing_link", path.relative_to(root), f"Missing local target: {target_text}", line)
|
||||
|
||||
|
||||
def validate_memory(root: Path, findings: list[Finding]) -> None:
|
||||
memory_root = root / "memory"
|
||||
index = memory_root / "MEMORY.md"
|
||||
required_topics = {"project-conventions.md", "user-preferences.md", "tech-decisions.md", "feedback-history.md"}
|
||||
if not index.is_file():
|
||||
add(findings, "error", "memory.index_missing", Path("memory/MEMORY.md"), "Memory index is missing")
|
||||
return
|
||||
lines = index.read_text("utf-8").splitlines()
|
||||
if len(lines) > 200:
|
||||
add(findings, "error", "memory.index_too_large", Path("memory/MEMORY.md"), f"Memory index has {len(lines)} lines; maximum is 200")
|
||||
entry_pattern = re.compile(r"^- \[(user|feedback|project|reference)\] .+ → ([A-Za-z0-9._-]+\.md)$")
|
||||
for line_no, line in enumerate(lines, 1):
|
||||
if not line.startswith("- ["):
|
||||
continue
|
||||
match = entry_pattern.fullmatch(line)
|
||||
if not match:
|
||||
add(findings, "error", "memory.invalid_entry", Path("memory/MEMORY.md"), "Invalid memory index entry", line_no)
|
||||
continue
|
||||
target = memory_root / match.group(2)
|
||||
if not target.is_file():
|
||||
add(findings, "error", "memory.missing_topic", Path("memory/MEMORY.md"), f"Missing topic file: {match.group(2)}", line_no)
|
||||
for topic in sorted(required_topics):
|
||||
path = memory_root / topic
|
||||
if not path.is_file():
|
||||
add(findings, "error", "memory.required_topic", Path("memory") / topic, "Required memory topic is missing")
|
||||
continue
|
||||
data = parse_frontmatter(path, findings)
|
||||
if data is None:
|
||||
continue
|
||||
missing = {"type", "created", "updated"} - set(data)
|
||||
for field in sorted(missing):
|
||||
add(findings, "error", "memory.required_field", path.relative_to(root), f"Missing required field: {field}")
|
||||
if str(data.get("type", "")) not in {"user", "feedback", "project", "reference"}:
|
||||
add(findings, "error", "memory.invalid_type", path.relative_to(root), f"Invalid memory type: {data.get('type')!r}")
|
||||
|
||||
|
||||
def validate_python(root: Path, findings: list[Finding]) -> None:
|
||||
for path in root.rglob("*.py"):
|
||||
if "__pycache__" in path.parts:
|
||||
continue
|
||||
try:
|
||||
ast.parse(path.read_text("utf-8"), filename=str(path))
|
||||
except (OSError, SyntaxError) as exc:
|
||||
add(findings, "error", "python.syntax", path.relative_to(root), str(exc), int(getattr(exc, "lineno", 1) or 1))
|
||||
|
||||
|
||||
def validate_architecture_counts(root: Path, findings: list[Finding]) -> None:
|
||||
path = root / "ARCHITECTURE.md"
|
||||
if not path.is_file():
|
||||
add(findings, "error", "architecture.missing", Path("ARCHITECTURE.md"), "ARCHITECTURE.md is missing")
|
||||
return
|
||||
text = path.read_text("utf-8", errors="replace")
|
||||
actual = {
|
||||
"agents": len(list((root / "agent").glob("*.md"))),
|
||||
"skills": len(list((root / "skills").glob("*/SKILL.md"))),
|
||||
"workflows": len(list((root / "workflows").glob("*.md"))),
|
||||
"skill_scripts": len(list((root / "skills").glob("*/scripts/*.py"))),
|
||||
}
|
||||
patterns = {
|
||||
"agents": r"\*\*Total Agents\*\*\s*\|\s*(\d+)",
|
||||
"skills": r"\*\*Total Skills\*\*\s*\|\s*(\d+)",
|
||||
"workflows": r"\*\*Total Workflows\*\*\s*\|\s*(\d+)",
|
||||
"skill_scripts": r"\*\*Total Skill Scripts\*\*\s*\|\s*(\d+)",
|
||||
}
|
||||
for key, pattern in patterns.items():
|
||||
match = re.search(pattern, text)
|
||||
if not match:
|
||||
add(findings, "error", "architecture.count_missing", Path("ARCHITECTURE.md"), f"Missing inventory field for {key}")
|
||||
elif int(match.group(1)) != actual[key]:
|
||||
add(findings, "error", "architecture.count_mismatch", Path("ARCHITECTURE.md"), f"{key}: documented {match.group(1)}, actual {actual[key]}")
|
||||
|
||||
|
||||
def validate(root: Path) -> list[Finding]:
|
||||
findings: list[Finding] = []
|
||||
validate_json(root, findings)
|
||||
validate_kit_version(root, findings)
|
||||
agents, skills, workflows, _rules = validate_frontmatter(root, findings)
|
||||
validate_references(root, agents, skills, workflows, findings)
|
||||
validate_manifest(root, findings)
|
||||
validate_generated_docs(root, findings)
|
||||
validate_markdown_links(root, findings)
|
||||
validate_memory(root, findings)
|
||||
validate_python(root, findings)
|
||||
validate_architecture_counts(root, findings)
|
||||
return findings
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Validate AG Kit structure and cross references")
|
||||
parser.add_argument("path", nargs="?", default=None, help="Path to .agents (defaults to this toolkit)")
|
||||
parser.add_argument("--json", action="store_true", dest="as_json")
|
||||
args = parser.parse_args()
|
||||
root = Path(args.path).resolve() if args.path else Path(__file__).resolve().parents[1]
|
||||
if not root.is_dir():
|
||||
parser.error(f"Toolkit directory does not exist: {root}")
|
||||
findings = validate(root)
|
||||
errors = [item for item in findings if item.severity == "error"]
|
||||
warnings = [item for item in findings if item.severity == "warning"]
|
||||
payload = {
|
||||
"toolkit": str(root),
|
||||
"passed": not errors,
|
||||
"summary": {"errors": len(errors), "warnings": len(warnings)},
|
||||
"findings": [item.__dict__ for item in findings],
|
||||
}
|
||||
if args.as_json:
|
||||
print(json.dumps(payload, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
print(f"AG Kit self-validation: {root}")
|
||||
for item in findings:
|
||||
print(f"[{item.severity.upper()}] {item.file}:{item.line} {item.code} - {item.message}")
|
||||
print(f"Summary: {len(errors)} error(s), {len(warnings)} warning(s)")
|
||||
print("[PASS] Toolkit is structurally valid." if not errors else "[FAIL] Toolkit validation failed.")
|
||||
return 0 if not errors else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
216
.agents/scripts/validation_runner.py
Normal file
216
.agents/scripts/validation_runner.py
Normal file
@@ -0,0 +1,216 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Shared process runner for AG Kit validation entry points."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Iterable, Literal
|
||||
|
||||
Target = Literal["project", "url", "none"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CheckSpec:
|
||||
name: str
|
||||
script: str
|
||||
category: str
|
||||
target: Target = "project"
|
||||
required: bool = False
|
||||
args: tuple[str, ...] = ()
|
||||
timeout: int = 300
|
||||
|
||||
|
||||
@dataclass
|
||||
class CheckResult:
|
||||
name: str
|
||||
category: str
|
||||
status: Literal["passed", "failed", "skipped", "error"]
|
||||
required: bool
|
||||
duration_seconds: float = 0.0
|
||||
command: list[str] = field(default_factory=list)
|
||||
stdout: str = ""
|
||||
stderr: str = ""
|
||||
reason: str = ""
|
||||
|
||||
@property
|
||||
def passed(self) -> bool:
|
||||
return self.status in {"passed", "skipped"}
|
||||
|
||||
|
||||
class Console:
|
||||
def __init__(self) -> None:
|
||||
enabled = sys.stdout.isatty() and "NO_COLOR" not in os.environ
|
||||
self.bold = "\033[1m" if enabled else ""
|
||||
self.cyan = "\033[96m" if enabled else ""
|
||||
self.green = "\033[92m" if enabled else ""
|
||||
self.yellow = "\033[93m" if enabled else ""
|
||||
self.red = "\033[91m" if enabled else ""
|
||||
self.end = "\033[0m" if enabled else ""
|
||||
|
||||
def header(self, text: str) -> None:
|
||||
line = "=" * 70
|
||||
print(f"\n{self.bold}{self.cyan}{line}\n{text.center(70)}\n{line}{self.end}\n")
|
||||
|
||||
def passed(self, text: str) -> None:
|
||||
print(f"{self.green}[PASS] {text}{self.end}")
|
||||
|
||||
def skipped(self, text: str) -> None:
|
||||
print(f"{self.yellow}[SKIP] {text}{self.end}")
|
||||
|
||||
def failed(self, text: str) -> None:
|
||||
print(f"{self.red}[FAIL] {text}{self.end}")
|
||||
|
||||
def info(self, text: str) -> None:
|
||||
print(text)
|
||||
|
||||
|
||||
CONSOLE = Console()
|
||||
|
||||
|
||||
def locate_toolkit_root(project: Path, caller_file: str) -> Path:
|
||||
"""Find the toolkit independently from the project being audited."""
|
||||
for candidate in (project / ".agents", project / ".agent"):
|
||||
if (candidate / "skills").is_dir() and (candidate / "scripts").is_dir():
|
||||
return candidate
|
||||
embedded = Path(caller_file).resolve().parents[1]
|
||||
if (embedded / "skills").is_dir() and (embedded / "scripts").is_dir():
|
||||
return embedded
|
||||
raise FileNotFoundError(
|
||||
"AG Kit root was not found. Expected <project>/.agents, <project>/.agent, "
|
||||
"or a runner located inside the toolkit."
|
||||
)
|
||||
|
||||
|
||||
def _command_for(spec: CheckSpec, script: Path, project: Path, url: str | None) -> list[str] | None:
|
||||
command = [sys.executable, str(script)]
|
||||
if spec.target == "project":
|
||||
command.append(str(project))
|
||||
elif spec.target == "url":
|
||||
if not url:
|
||||
return None
|
||||
command.append(url)
|
||||
command.extend(spec.args)
|
||||
return command
|
||||
|
||||
|
||||
def run_check(spec: CheckSpec, toolkit_root: Path, project: Path, url: str | None) -> CheckResult:
|
||||
script = toolkit_root / spec.script
|
||||
if not script.is_file():
|
||||
status = "failed" if spec.required else "skipped"
|
||||
reason = f"Script not found: {script}"
|
||||
result = CheckResult(spec.name, spec.category, status, spec.required, reason=reason)
|
||||
(CONSOLE.failed if status == "failed" else CONSOLE.skipped)(f"{spec.name}: {reason}")
|
||||
return result
|
||||
|
||||
command = _command_for(spec, script, project, url)
|
||||
if command is None:
|
||||
reason = "URL not provided"
|
||||
CONSOLE.skipped(f"{spec.name}: {reason}")
|
||||
return CheckResult(spec.name, spec.category, "skipped", spec.required, reason=reason)
|
||||
|
||||
started = datetime.now(timezone.utc)
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
command,
|
||||
cwd=project,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=spec.timeout,
|
||||
check=False,
|
||||
)
|
||||
duration = (datetime.now(timezone.utc) - started).total_seconds()
|
||||
status = "passed" if proc.returncode == 0 else "failed"
|
||||
result = CheckResult(
|
||||
spec.name, spec.category, status, spec.required, duration,
|
||||
command, proc.stdout, proc.stderr,
|
||||
reason="" if status == "passed" else f"Exit code {proc.returncode}",
|
||||
)
|
||||
if status == "passed":
|
||||
CONSOLE.passed(f"{spec.name} ({duration:.1f}s)")
|
||||
else:
|
||||
CONSOLE.failed(f"{spec.name} ({duration:.1f}s, exit {proc.returncode})")
|
||||
_print_failure_output(result)
|
||||
return result
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
duration = (datetime.now(timezone.utc) - started).total_seconds()
|
||||
result = CheckResult(
|
||||
spec.name, spec.category, "error", spec.required, duration, command,
|
||||
_decode_timeout(exc.stdout), _decode_timeout(exc.stderr),
|
||||
f"Timed out after {spec.timeout}s",
|
||||
)
|
||||
CONSOLE.failed(f"{spec.name}: {result.reason}")
|
||||
return result
|
||||
except OSError as exc:
|
||||
duration = (datetime.now(timezone.utc) - started).total_seconds()
|
||||
result = CheckResult(spec.name, spec.category, "error", spec.required, duration, command, reason=str(exc))
|
||||
CONSOLE.failed(f"{spec.name}: {exc}")
|
||||
return result
|
||||
|
||||
|
||||
def _decode_timeout(value: str | bytes | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return value.decode(errors="replace") if isinstance(value, bytes) else value
|
||||
|
||||
|
||||
def _print_failure_output(result: CheckResult, limit: int = 1600) -> None:
|
||||
combined = "\n".join(part.strip() for part in (result.stdout, result.stderr) if part.strip())
|
||||
if combined:
|
||||
print(combined[-limit:])
|
||||
|
||||
|
||||
def execute_suite(
|
||||
specs: Iterable[CheckSpec],
|
||||
toolkit_root: Path,
|
||||
project: Path,
|
||||
url: str | None,
|
||||
stop_on_fail: bool = False,
|
||||
) -> list[CheckResult]:
|
||||
results: list[CheckResult] = []
|
||||
current_category = ""
|
||||
for spec in specs:
|
||||
if spec.category != current_category:
|
||||
current_category = spec.category
|
||||
CONSOLE.header(current_category)
|
||||
result = run_check(spec, toolkit_root, project, url)
|
||||
results.append(result)
|
||||
if stop_on_fail and result.status in {"failed", "error"}:
|
||||
break
|
||||
return results
|
||||
|
||||
|
||||
def suite_success(results: Iterable[CheckResult]) -> bool:
|
||||
return all(result.status not in {"failed", "error"} for result in results)
|
||||
|
||||
|
||||
def print_summary(title: str, results: list[CheckResult], started: datetime) -> bool:
|
||||
CONSOLE.header(title)
|
||||
counts = {status: sum(r.status == status for r in results) for status in ("passed", "failed", "error", "skipped")}
|
||||
duration = (datetime.now(timezone.utc) - started).total_seconds()
|
||||
print(f"Duration: {duration:.1f}s")
|
||||
print(f"Checks: {len(results)} | Passed: {counts['passed']} | Failed: {counts['failed']} | Errors: {counts['error']} | Skipped: {counts['skipped']}")
|
||||
for result in results:
|
||||
marker = {"passed": "PASS", "failed": "FAIL", "error": "ERROR", "skipped": "SKIP"}[result.status]
|
||||
detail = f" - {result.reason}" if result.reason else ""
|
||||
print(f"[{marker}] {result.category} / {result.name}{detail}")
|
||||
ok = suite_success(results)
|
||||
(CONSOLE.passed if ok else CONSOLE.failed)("Validation completed successfully" if ok else "Validation found blocking failures")
|
||||
return ok
|
||||
|
||||
|
||||
def write_report(path: Path, project: Path, toolkit_root: Path, results: list[CheckResult], started: datetime) -> None:
|
||||
payload = {
|
||||
"project": str(project),
|
||||
"toolkit_root": str(toolkit_root),
|
||||
"started_at": started.isoformat(),
|
||||
"finished_at": datetime.now(timezone.utc).isoformat(),
|
||||
"success": suite_success(results),
|
||||
"results": [asdict(result) for result in results],
|
||||
}
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
85
.agents/scripts/verify_all.py
Executable file
85
.agents/scripts/verify_all.py
Executable file
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the complete AG Kit verification suite."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from validation_runner import (
|
||||
CONSOLE,
|
||||
CheckSpec,
|
||||
execute_suite,
|
||||
locate_toolkit_root,
|
||||
print_summary,
|
||||
write_report,
|
||||
)
|
||||
|
||||
VERIFICATION_SUITE = (
|
||||
CheckSpec(
|
||||
"Security Scan",
|
||||
"skills/vulnerability-scanner/scripts/security_scan.py",
|
||||
"P0 Security",
|
||||
required=True,
|
||||
args=("--output", "summary", "--fail-on", "high"),
|
||||
),
|
||||
CheckSpec("Dependency Analysis", "skills/vulnerability-scanner/scripts/dependency_analyzer.py", "P0 Security"),
|
||||
CheckSpec("Lint Check", "skills/lint-and-validate/scripts/lint_runner.py", "P1 Code Quality", required=True),
|
||||
CheckSpec("Type Coverage", "skills/lint-and-validate/scripts/type_coverage.py", "P1 Code Quality"),
|
||||
CheckSpec("Schema Validation", "skills/database-design/scripts/schema_validator.py", "P2 Data Layer"),
|
||||
CheckSpec("Test Suite", "skills/testing-patterns/scripts/test_runner.py", "P3 Testing"),
|
||||
CheckSpec("UX Audit", "skills/frontend-design/scripts/ux_audit.py", "P4 UX & Accessibility"),
|
||||
CheckSpec("Accessibility Check", "skills/frontend-design/scripts/accessibility_checker.py", "P4 UX & Accessibility"),
|
||||
CheckSpec("SEO Check", "skills/seo-fundamentals/scripts/seo_checker.py", "P5 SEO & Content"),
|
||||
CheckSpec("GEO Check", "skills/geo-fundamentals/scripts/geo_checker.py", "P5 SEO & Content"),
|
||||
CheckSpec("Bundle Analysis", "skills/performance-profiling/scripts/bundle_analyzer.py", "P6 Build Performance"),
|
||||
CheckSpec("React Performance", "skills/nextjs-react-expert/scripts/react_performance_checker.py", "P6 Build Performance"),
|
||||
CheckSpec("Mobile Audit", "skills/mobile-design/scripts/mobile_audit.py", "P7 Platform Quality"),
|
||||
CheckSpec("i18n Check", "skills/i18n-localization/scripts/i18n_checker.py", "P7 Platform Quality"),
|
||||
CheckSpec("API Validation", "skills/api-patterns/scripts/api_validator.py", "P7 Platform Quality"),
|
||||
CheckSpec("Lighthouse Audit", "skills/performance-profiling/scripts/lighthouse_audit.py", "P8 Runtime", target="url", required=True, timeout=180),
|
||||
CheckSpec("Playwright E2E", "skills/webapp-testing/scripts/playwright_runner.py", "P8 Runtime", target="url", timeout=120),
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Run the complete AG Kit verification suite")
|
||||
parser.add_argument("project", nargs="?", default=".", help="Project path to validate")
|
||||
parser.add_argument("--url", help="Running application URL for Lighthouse and Playwright")
|
||||
parser.add_argument("--no-e2e", action="store_true", help="Skip Playwright")
|
||||
parser.add_argument("--no-runtime", action="store_true", help="Skip all URL-based runtime checks")
|
||||
parser.add_argument("--stop-on-fail", action="store_true", help="Stop after the first failed check")
|
||||
parser.add_argument("--report", type=Path, help="Write a machine-readable JSON report")
|
||||
args = parser.parse_args()
|
||||
|
||||
project = Path(args.project).resolve()
|
||||
if not project.is_dir():
|
||||
parser.error(f"Project directory does not exist: {project}")
|
||||
|
||||
try:
|
||||
toolkit_root = locate_toolkit_root(project, __file__)
|
||||
except FileNotFoundError as exc:
|
||||
parser.error(str(exc))
|
||||
|
||||
specs = []
|
||||
for spec in VERIFICATION_SUITE:
|
||||
if args.no_runtime and spec.target == "url":
|
||||
continue
|
||||
if args.no_e2e and spec.name == "Playwright E2E":
|
||||
continue
|
||||
specs.append(spec)
|
||||
|
||||
started = datetime.now(timezone.utc)
|
||||
CONSOLE.header("AG KIT - FULL VERIFICATION")
|
||||
print(f"Project: {project}\nToolkit: {toolkit_root}\nURL: {args.url or 'not provided'}")
|
||||
|
||||
results = execute_suite(specs, toolkit_root, project, args.url, args.stop_on_fail)
|
||||
success = print_summary("FULL VERIFICATION REPORT", results, started)
|
||||
if args.report:
|
||||
write_report(args.report.resolve(), project, toolkit_root, results, started)
|
||||
print(f"Report: {args.report.resolve()}")
|
||||
return 0 if success else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user