#!/usr/bin/env python3
"""agents-audit.py <agents-dir>: our script, NOT Claude Code. It encodes the rules in
code.claude.com/docs/en/sub-agents (checked 2026-11-23): which subagent files load, which
frontmatter fields are ignored, and whether the resulting tool set can change files."""
import os, re, sys
KNOWN = {"name", "description", "tools", "disallowedTools", "model", "permissionMode", "maxTurns",
         "autoCompactWindow", "skills", "mcpServers", "hooks", "memory", "background", "omitClaudeMd",
         "effort", "isolation", "color", "initialPrompt", "experimental"}
def front(path):
    lines = open(path).read().splitlines()
    if not lines or lines[0].strip() != "---": return None
    fm = {}
    for ln in lines[1:]:
        if ln.strip() == "---": break
        m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", ln)
        if m: fm[m.group(1)] = m.group(2).strip()
    return fm
def tool_list(v): return [t.strip() for t in v.strip("[]").split(",") if t.strip()]
args = [a for a in sys.argv[1:] if a != "--compact"]; compact = "--compact" in sys.argv  # --compact: portrait-card width
d = args[0] if args else ".claude/agents"
def out(f, status, edits, why, short):
    if compact: print(f"{f:<19} {edits:<4} {short}")
    else: print(f"{f:<20} {status:<8} {edits:<7} {why}")
print(f"{'file':<19} {'edit':<4} why" if compact else f"{'file':<20} {'status':<8} {'edits?':<7} why")
for f in sorted(os.listdir(d)):
    if not f.endswith(".md"): continue
    fm = front(os.path.join(d, f))
    if fm is None or "name" not in fm:
        out(f, "doc", "-", "no name: read as docs", "docs (no name)"); continue
    if "description" not in fm:
        out(f, "SKIPPED", "-", "no description", "SKIPPED"); continue
    unknown = [k for k in fm if k not in KNOWN]
    tools = set(tool_list(fm["tools"])) if "tools" in fm else {"*"}
    dropped = {re.sub(r"\(.*\)$", "", t) for t in tool_list(fm.get("disallowedTools", ""))}
    tools -= dropped
    why = []
    if unknown: why.append('unknown key ' + ', '.join(unknown))
    if dropped: why.append(f"drops ALL of {', '.join(sorted(dropped))}")
    if "memory" in fm: tools |= {"Read", "Write", "Edit"}; why.append("memory: adds Write, Edit")
    if "*" in tools: edits = "YES"; why.append("inherits all tools")
    else:
        via = [t for t in ("Edit", "Write", "Bash") if t in tools]
        edits = "YES" if via else "no"
        if via and "memory" not in fm: why.append("via " + ", ".join(via))
        if not via: why.append(", ".join(sorted(tools)) + " only")
    short = ("unknown key, inherits all" if unknown and "*" in tools else "memory adds Write+Edit" if "memory" in fm
             else "via Bash" if edits == "YES" and "Bash" in tools else "ALL of Bash dropped" if dropped else "Read/Grep/Glob" if edits == "no" else why[-1])
    out(f, "loads", edits, "; ".join(why), short)
