|
|
|
|
| """
|
| structure-sentinel.py -- minimal structure sentinel for a nomad-skeleton team workspace.
|
|
|
| WHAT THIS IS
|
| A single, dependency-free script that runs four checks over this team's
|
| folder and prints a plain-language report. It is a GUARDRAIL, not a gate:
|
| it never blocks or edits anything, it only tells you what drifted.
|
|
|
| FOUR CHECKS
|
| 1. Existence -- every file a persona names as "must-read" (the agent-home
|
| six-piece set + the core governance files) really exists.
|
| 2. Orphan -- files that exist on disk under a memory/ folder but are
|
| not mentioned in that folder's README.md index.
|
| 3. Frontmatter -- .md files under the three mandatory zones (00-index/,
|
| 02-shared-knowledge/, 01-agents/*/memory/) carry the
|
| required 4-field YAML header (type/owner/created/status)
|
| with controlled values.
|
| 4. Broken link -- relative markdown links (`[text](path)`) inside .md
|
| files resolve to a real file on disk.
|
|
|
| USAGE
|
| python3 structure-sentinel.py [team_root] # macOS / Linux
|
| py -3 structure-sentinel.py [team_root] # Windows
|
| python3 structure-sentinel.py [team_root] --json report.json
|
|
|
| macOS 12.3 removed /usr/bin/python, so `python` alone is not portable;
|
| `python3` is the portable name on macOS/Linux and `py -3` on Windows.
|
|
|
| team_root defaults to the current working directory. Exit code is 0 when
|
| everything is clean, 1 when any violation was found -- so it is safe to
|
| wire into a CI-style check without parsing stdout.
|
|
|
| DESIGN NOTE
|
| This is a deliberately minimal port of a design pattern used in the
|
| author's own production team workspace (structure sentinel + metadata
|
| schema), generalized and stripped of any private names/paths for this
|
| starter kit. It reads the team's own governance doc
|
| (`00-index/metadata-conventions.md`) for the controlled value tables --
|
| see TYPE_VALUES / STATUS_VALUES below, which mirror that doc's word list.
|
| If you rename files or fold in new agents, this script needs no changes:
|
| everything it scans is discovered by walking the disk, not hard-coded
|
| per-agent (only the six-piece file list and the three mandatory-zone
|
| directory names are fixed, because those are the team-skeleton contract
|
| itself, not per-deployment content).
|
| """
|
| from __future__ import annotations
|
|
|
| import argparse
|
| import json
|
| import re
|
| import sys
|
| from datetime import datetime, timezone
|
| from pathlib import Path
|
|
|
|
|
|
|
|
|
|
|
| if sys.version_info < (3, 8):
|
| sys.stderr.write(
|
| "[sentinel] Python %d.%d detected; 3.8+ recommended. Older versions may hit "
|
| "obscure syntax errors; please upgrade (Windows: use 'py -3').\n"
|
| % (sys.version_info.major, sys.version_info.minor)
|
| )
|
|
|
| try:
|
| sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
| except Exception:
|
| pass
|
|
|
|
|
|
|
|
|
|
|
| TYPE_VALUES = {"index", "rule", "state", "log", "knowledge", "calibration", "archive"}
|
| STATUS_VALUES = {"active", "draft", "to-fix", "expired", "archived"}
|
| REQUIRED_FIELDS = ["type", "owner", "created", "status"]
|
|
|
| MANDATORY_ZONE_DIRS = ["00-index", "02-shared-knowledge"]
|
|
|
|
|
|
|
|
|
|
|
| EXEMPT_DIR_NAMES = {
|
| "templates", "workspace", "98-archive", "99-recycle-bin", "97-inbox-misc",
|
| ".agent-modpack", ".git", "__pycache__", "skills",
|
| }
|
| EMPLOYEE_TEMPLATE_DIRNAME_MARKER = "fill-in, not loaded"
|
|
|
| AGENT_HOME_SIX_PIECE = [
|
| "AGENTS.md", "CLAUDE.md", "workspace",
|
| "memory/README.md", "memory/inbox.md", "memory/worklog.md",
|
| ]
|
|
|
|
|
|
|
|
|
|
|
|
|
| NUWA_AGENT_NAMES = {"nuwa", "女娲"}
|
| NUWA_HOME_REQUIRED = [
|
| "AGENTS.md", "CLAUDE.md",
|
| "memory/judgment-calibration-log.md", "memory/forging-ledger.md",
|
| ]
|
|
|
| FRONTMATTER_RE = re.compile(r"\A?---[ \t]*\r?\n(.*?)\r?\n---[ \t]*\r?\n", re.DOTALL)
|
| FIELD_LINE_RE = re.compile(r"^([A-Za-z_]+):[ \t]*(.*)$")
|
| ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
|
|
|
|
|
| MD_LINK_RE = re.compile(r"\[[^\]]*\]\(([^)]+)\)")
|
|
|
|
|
| def is_exempt_path(path: Path, root: Path) -> bool:
|
| rel_parts = path.relative_to(root).parts
|
| for part in rel_parts:
|
| if part in EXEMPT_DIR_NAMES:
|
| return True
|
| if EMPLOYEE_TEMPLATE_DIRNAME_MARKER in part:
|
| return True
|
| return False
|
|
|
|
|
| def read_text(path: Path) -> str | None:
|
| try:
|
| text = path.read_text(encoding="utf-8")
|
| except Exception:
|
| return None
|
| if text.startswith(""):
|
| text = text[1:]
|
| return text
|
|
|
|
|
|
|
|
|
|
|
|
|
| def check_existence(root: Path) -> list[dict]:
|
| violations: list[dict] = []
|
| if not (root / "team-config.json").exists():
|
| violations.append({
|
| "check": "existence", "severity": "high", "path": "team-config.json",
|
| "message": "team-config.json is missing -- the team's parameterized spine is gone.",
|
| })
|
|
|
| agents_root = root / "01-agents"
|
| if not agents_root.is_dir():
|
| violations.append({
|
| "check": "existence", "severity": "high", "path": "01-agents",
|
| "message": "01-agents/ directory is missing.",
|
| })
|
| return violations
|
|
|
| for agent_dir in sorted(p for p in agents_root.iterdir() if p.is_dir()):
|
| if EMPLOYEE_TEMPLATE_DIRNAME_MARKER in agent_dir.name:
|
| continue
|
| required = NUWA_HOME_REQUIRED if agent_dir.name in NUWA_AGENT_NAMES else AGENT_HOME_SIX_PIECE
|
| for rel in required:
|
| if not (agent_dir / rel).exists():
|
| violations.append({
|
| "check": "existence", "severity": "high",
|
| "path": str((agent_dir / rel).relative_to(root)),
|
| "message": f"agent home required file missing for '{agent_dir.name}'.",
|
| })
|
| return violations
|
|
|
|
|
|
|
|
|
|
|
|
|
| def check_orphans(root: Path) -> list[dict]:
|
| violations: list[dict] = []
|
| agents_root = root / "01-agents"
|
| if not agents_root.is_dir():
|
| return violations
|
| for agent_dir in sorted(p for p in agents_root.iterdir() if p.is_dir()):
|
| if agent_dir.name in NUWA_AGENT_NAMES:
|
| continue
|
| mem_dir = agent_dir / "memory"
|
| if not mem_dir.is_dir():
|
| continue
|
| readme_path = mem_dir / "README.md"
|
| readme_text = read_text(readme_path)
|
| if readme_text is None:
|
| violations.append({
|
| "check": "orphan", "severity": "high",
|
| "path": str(readme_path.relative_to(root)),
|
| "message": "memory/README.md missing or unreadable -- orphan check skipped for this agent.",
|
| })
|
| continue
|
| for entry in sorted(mem_dir.iterdir()):
|
| if entry.is_dir():
|
| continue
|
| if entry.name == "README.md":
|
| continue
|
| if entry.name.startswith(".") or entry.name.endswith(".bak"):
|
| continue
|
| if entry.name not in readme_text:
|
| violations.append({
|
| "check": "orphan", "severity": "medium",
|
| "path": str(entry.relative_to(root)),
|
| "message": f"'{entry.name}' exists on disk but is not mentioned in "
|
| f"{readme_path.relative_to(root)} -- register it or delete it.",
|
| })
|
| return violations
|
|
|
|
|
|
|
|
|
|
|
|
|
| def parse_frontmatter(text: str) -> dict | None:
|
| m = FRONTMATTER_RE.match(text)
|
| if not m:
|
| return None
|
| fields: dict[str, str] = {}
|
| for line in m.group(1).splitlines():
|
| fm = FIELD_LINE_RE.match(line)
|
| if fm:
|
| fields[fm.group(1)] = fm.group(2).strip()
|
| return fields
|
|
|
|
|
| def mandatory_zone_dirs(root: Path) -> list[Path]:
|
| dirs = [root / d for d in MANDATORY_ZONE_DIRS if (root / d).is_dir()]
|
| agents_root = root / "01-agents"
|
| if agents_root.is_dir():
|
| for agent_dir in sorted(p for p in agents_root.iterdir() if p.is_dir()):
|
| if EMPLOYEE_TEMPLATE_DIRNAME_MARKER in agent_dir.name:
|
| continue
|
| mem = agent_dir / "memory"
|
| if mem.is_dir():
|
| dirs.append(mem)
|
| return dirs
|
|
|
|
|
| def check_frontmatter(root: Path) -> list[dict]:
|
| violations: list[dict] = []
|
| for zone in mandatory_zone_dirs(root):
|
| for md_path in sorted(zone.rglob("*.md")):
|
| if is_exempt_path(md_path, root):
|
| continue
|
| rel = md_path.relative_to(root)
|
| text = read_text(md_path)
|
| if text is None:
|
| violations.append({
|
| "check": "frontmatter", "severity": "high", "path": str(rel),
|
| "message": "file could not be read.",
|
| })
|
| continue
|
| fields = parse_frontmatter(text)
|
| if fields is None:
|
| violations.append({
|
| "check": "frontmatter", "severity": "high", "path": str(rel),
|
| "message": "missing YAML frontmatter (mandatory zone requires "
|
| "type/owner/created/status).",
|
| })
|
| continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| if (not fields.get("type") and not fields.get("owner") and not fields.get("status")
|
| and any(fields.get(k) for k in ("name", "description", "version", "title"))):
|
| violations.append({
|
| "check": "frontmatter", "severity": "medium", "path": str(rel),
|
| "message": "file carries another system's frontmatter schema "
|
| "(name/description/version/title) inside a mandatory zone — "
|
| "needs a human call: move it to where its system lives "
|
| "(e.g. 90-methodology/skills/), or convert it to the team schema.",
|
| })
|
| continue
|
| for f in REQUIRED_FIELDS:
|
| if not fields.get(f):
|
| violations.append({
|
| "check": "frontmatter", "severity": "high", "path": str(rel),
|
| "message": f"required field missing: {f}",
|
| })
|
| if fields.get("type") and fields["type"] not in TYPE_VALUES:
|
| violations.append({
|
| "check": "frontmatter", "severity": "high", "path": str(rel),
|
| "message": f"type value '{fields['type']}' is not in the controlled "
|
| f"7-value table: {sorted(TYPE_VALUES)}",
|
| })
|
| if fields.get("status") and fields["status"] not in STATUS_VALUES:
|
| violations.append({
|
| "check": "frontmatter", "severity": "high", "path": str(rel),
|
| "message": f"status value '{fields['status']}' is not in the controlled "
|
| f"5-value table: {sorted(STATUS_VALUES)}",
|
| })
|
| created = fields.get("created")
|
| if created and not (ISO_DATE_RE.match(created) and _is_real_date(created)):
|
| violations.append({
|
| "check": "frontmatter", "severity": "medium", "path": str(rel),
|
| "message": f"created value '{created}' is not a valid YYYY-MM-DD date.",
|
| })
|
|
|
|
|
|
|
|
|
|
|
| if fields.get("status") in ("archived", "expired"):
|
| violations.append({
|
| "check": "frontmatter", "severity": "low", "path": str(rel),
|
| "message": f"status is '{fields['status']}' but the file still lives in a "
|
| "live mandatory zone — consider moving it to 98-archive/ "
|
| "(or re-activate it if it is actually still in service).",
|
| })
|
| return violations
|
|
|
|
|
| def _is_real_date(value: str) -> bool:
|
| try:
|
| datetime.strptime(value, "%Y-%m-%d")
|
| return True
|
| except ValueError:
|
| return False
|
|
|
|
|
|
|
|
|
|
|
|
|
| def check_broken_links(root: Path) -> list[dict]:
|
| violations: list[dict] = []
|
| for md_path in sorted(root.rglob("*.md")):
|
| if is_exempt_path(md_path, root):
|
| continue
|
| text = read_text(md_path)
|
| if text is None:
|
| continue
|
| for m in MD_LINK_RE.finditer(text):
|
| target = m.group(1).strip()
|
| if not target:
|
| continue
|
|
|
| if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", target):
|
| continue
|
| if target.startswith("#"):
|
| continue
|
| if target.startswith("{{") and target.endswith("}}"):
|
| continue
|
|
|
| file_part = target.split("#", 1)[0].strip()
|
| if not file_part:
|
| continue
|
| if file_part.startswith("/"):
|
| candidate = root / file_part.lstrip("/")
|
| else:
|
| candidate = (md_path.parent / file_part).resolve()
|
| if not candidate.exists():
|
| violations.append({
|
| "check": "broken-link", "severity": "medium",
|
| "path": str(md_path.relative_to(root)),
|
| "message": f"link target does not resolve to a file on disk: {target}",
|
| })
|
| return violations
|
|
|
|
|
|
|
|
|
|
|
|
|
| def run_all(root: Path) -> dict:
|
| checks = {
|
| "existence": check_existence(root),
|
| "orphan": check_orphans(root),
|
| "frontmatter": check_frontmatter(root),
|
| "broken-link": check_broken_links(root),
|
| }
|
| all_violations = [v for vs in checks.values() for v in vs]
|
| return {
|
| "sentinelVersion": "0.1.0-min",
|
| "teamRoot": str(root),
|
| "ranAt": datetime.now(timezone.utc).isoformat(),
|
| "checkCounts": {name: len(vs) for name, vs in checks.items()},
|
| "totalViolations": len(all_violations),
|
| "overall": "CLEAN" if not all_violations else "DRIFT FOUND",
|
| "violations": all_violations,
|
| }
|
|
|
|
|
| def render_report_text(report: dict) -> str:
|
| lines: list[str] = []
|
| lines.append(f"=== structure sentinel · {report['teamRoot']} ===")
|
| lines.append(f"ran at : {report['ranAt']}")
|
| lines.append(f"overall : {report['overall']}")
|
| lines.append(
|
| "checks : existence={existence} orphan={orphan} frontmatter={frontmatter} "
|
| "broken-link={broken-link}".format(**report["checkCounts"])
|
| )
|
| lines.append("")
|
| if not report["violations"]:
|
| lines.append("Nothing to report -- structure looks clean.")
|
| return "\n".join(lines)
|
| by_check: dict[str, list[dict]] = {}
|
| for v in report["violations"]:
|
| by_check.setdefault(v["check"], []).append(v)
|
| for check_name, items in by_check.items():
|
| lines.append(f"-- {check_name} ({len(items)}) --")
|
| for v in items:
|
| lines.append(f" [{v['severity']}] {v['path']}")
|
| lines.append(f" {v['message']}")
|
| lines.append("")
|
| lines.append(
|
| f"TOTAL: {report['totalViolations']} issue(s). This is a guardrail, not a gate -- "
|
| f"nothing was changed. Fix what matters, re-run to confirm."
|
| )
|
| return "\n".join(lines)
|
|
|
|
|
| def main() -> int:
|
| parser = argparse.ArgumentParser(description="Minimal structure sentinel for a nomad-skeleton team workspace.")
|
| parser.add_argument("team_root", nargs="?", default=".", help="Team root directory (default: cwd)")
|
| parser.add_argument("--json", dest="json_out", default=None, help="Also write a machine-readable JSON report to this path")
|
| args = parser.parse_args()
|
|
|
| root = Path(args.team_root).resolve()
|
| if not root.is_dir():
|
| print(f"ERROR: team_root does not exist or is not a directory: {root}")
|
| return 2
|
|
|
| report = run_all(root)
|
| print(render_report_text(report))
|
|
|
| if args.json_out:
|
| Path(args.json_out).write_text(
|
| json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n",
|
| )
|
| print(f"\nJSON report written: {args.json_out}")
|
|
|
| return 0 if report["overall"] == "CLEAN" else 1
|
|
|
|
|
| if __name__ == "__main__":
|
| sys.exit(main())
|
|
|