Skip to content

matt-bat/got-skills / skills/skill-governance

skill-governance

Verified

Govern release-affecting, policy-changing, externally mutating, destructive, or otherwise high-risk work through typed effects, mandatory evidence, independent safety gates, and an explicit go/no-go decision. Do not use for ordinary answers, read-only inspection, tiny reversible edits, or a task made "multi-skill" only by optional process helpers.

FileKindSize
SKILL.mdskill md9.7 KB
fixtures/passed-artifact-evidence.jsonconfig104 B
fixtures/routing-scenarios.jsonconfig44.2 KB
references/governance-artifacts.mdmarkdown5.1 KB
references/risk-and-gates.mdmarkdown4.6 KB
requirements.txtmanifest89 B
schemas/governance-artifact.schema.jsonconfig13.6 KB
schemas/remote-configuration-policy.schema.jsonconfig4.3 KB
schemas/routing-result.schema.jsonconfig7.7 KB
schemas/task-descriptor.schema.jsonconfig13.3 KB
scripts/enforce_governance_ci.pyscript24.4 KB
scripts/generate_governance_artifact.pyscript43.4 KB
scripts/generate_routing_views.pyscript27.6 KB
scripts/governance_common.pyscript14.5 KB
scripts/record_routing_observation.pyscript9.3 KB
scripts/resolve_task_route.pyscript69.4 KB
scripts/validate_governance_artifact.pyscript39.9 KB
scripts/validate_skill_order_sync.pyscript4.0 KB
scripts/validate_skill_policy.pyscript32.3 KB
scripts/verify_remote_configuration.pyscript12.3 KB
tests/test_advanced_svg_render.pyscript5.1 KB
tests/test_conflict_matrix_integrity.pyscript2.1 KB
tests/test_default_skill_quality_gates.pyscript2.9 KB
tests/test_docs_website_navigation.pyscript2.7 KB
tests/test_enforce_governance_scope.pyscript1.7 KB
tests/test_generate_governance_startup.pyscript9.0 KB
tests/test_generate_routing_views.pyscript12.8 KB
tests/test_governance_history_and_pair_integrity.pyscript10.6 KB
tests/test_governance_integrity.pyscript55.7 KB
tests/test_new_skill_integration.pyscript8.3 KB
tests/test_project_index_integrity.pyscript6.4 KB
tests/test_remote_configuration.pyscript5.6 KB
tests/test_routing_observation.pyscript4.3 KB
tests/test_runtime_adapter.pyscript9.2 KB
tests/test_task_routing.pyscript47.5 KB
tests/test_validate_skill_order_sync.pyscript2.4 KB
tests/test_validate_skill_policy_smoke.pyscript869 B

scripts/generate_routing_views.py

View on GitHub
#!/usr/bin/env python3
"""Validate the canonical skill catalog and generate its Markdown views."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any


RELATIONS = {
    "requires",
    "gates",
    "runs_after",
    "supports",
    "conflicts_with",
    "consumes",
    "superseded_by",
}
STATUSES = {"active", "deprecated", "compatibility_alias", "removed"}
ROLES = {"owner", "safety", "execution", "support", "mode", "compatibility"}
ROUTING_MODES = {"automatic", "explicit_only", "safety_only", "nonselectable"}
ROUTING_CLAUSES = {
    "actions_any": "actions",
    "operations_any": "operations",
    "operations_all": "operations",
    "effects_any": "effects",
    "effects_all": "effects",
    "surfaces_any": "surfaces",
    "surfaces_all": "surfaces",
    "domains_any": "domains",
    "domains_all": "domains",
    "flags_any": "flags",
    "flags_all": "flags",
    "flags_none": "flags",
}
DURABILITY = {
    "none",
    "conversation_local",
    "conversation_local_unless_record",
    "authorized_only",
    "required_when_governed",
}
GENERATED_NOTICE = "<!-- Generated by generate_routing_views.py; edit skill-catalog.json instead. -->"


class CatalogError(ValueError):
    """Catalog validation error with a user-actionable message."""


def parse_args() -> argparse.Namespace:
    repo_default = Path(__file__).resolve().parents[3]
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo-root", type=Path, default=repo_default)
    parser.add_argument("--catalog", type=Path)
    parser.add_argument("--check", action="store_true")
    return parser.parse_args()


def load_catalog(path: Path) -> dict[str, Any]:
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError as exc:
        raise CatalogError(f"catalog not found: {path}") from exc
    except json.JSONDecodeError as exc:
        raise CatalogError(f"invalid JSON in {path}: {exc}") from exc
    if not isinstance(payload, dict):
        raise CatalogError("catalog root must be an object")
    return payload


def frontmatter(path: Path) -> dict[str, str]:
    text = path.read_text(encoding="utf-8")
    if not text.startswith("---\n"):
        raise CatalogError(f"missing YAML frontmatter: {path}")
    try:
        raw = text.split("---\n", 2)[1]
    except IndexError as exc:
        raise CatalogError(f"unterminated YAML frontmatter: {path}") from exc
    values: dict[str, str] = {}
    for line in raw.splitlines():
        if not line or line[0].isspace() or ":" not in line:
            continue
        key, value = line.split(":", 1)
        values[key.strip()] = value.strip().strip("'\"")
    return values


def require_string_list(value: Any, location: str, *, nonempty: bool = False) -> list[str]:
    if not isinstance(value, list) or any(not isinstance(item, str) or not item for item in value):
        raise CatalogError(f"{location} must be a list of non-empty strings")
    if nonempty and not value:
        raise CatalogError(f"{location} must not be empty")
    return value


def validate_catalog(catalog: dict[str, Any], repo_root: Path) -> list[dict[str, Any]]:
    if catalog.get("$schema") != "./skill-catalog.schema.json":
        raise CatalogError("$schema must reference ./skill-catalog.schema.json")
    if catalog.get("schema_version") != 2:
        raise CatalogError("schema_version must be 2")
    if not isinstance(catalog.get("catalog_version"), str):
        raise CatalogError("catalog_version must be a semantic-version string")
    if catalog.get("router_contract") != "2.1":
        raise CatalogError("router_contract must be '2.1'")

    schema_path = repo_root / "skills" / "skill-catalog.schema.json"
    if schema_path.exists():
        try:
            from jsonschema import Draft202012Validator
        except ImportError:
            pass
        else:
            schema = json.loads(schema_path.read_text(encoding="utf-8"))
            errors = sorted(
                Draft202012Validator(schema).iter_errors(catalog),
                key=lambda error: list(error.absolute_path),
            )
            if errors:
                error = errors[0]
                location = ".".join(str(part) for part in error.absolute_path) or "$"
                raise CatalogError(f"schema violation at {location}: {error.message}")

    components = set(require_string_list(catalog.get("components"), "components", nonempty=True))
    if len(components) != len(catalog["components"]):
        raise CatalogError("components must not contain duplicates")
    generated_views = require_string_list(
        catalog.get("generated_views"), "generated_views", nonempty=True
    )
    expected_views = {
        "skills/SKILL-MAP.md",
        "skills/docs/skill-index.md",
        "skills/docs/skill-decision-tree.md",
    }
    if set(generated_views) != expected_views:
        raise CatalogError(f"generated_views must be exactly {sorted(expected_views)}")

    policy = catalog.get("router_policy", catalog.get("core_policy"))
    if not isinstance(policy, dict):
        raise CatalogError("router_policy must be an object")
    if policy.get("zero_skill_valid") is not True:
        raise CatalogError("router_policy.zero_skill_valid must be true")
    budget = policy.get("skill_budget")
    if not isinstance(budget, dict):
        raise CatalogError("router_policy.skill_budget must be an object")
    if budget.get("routine_target_median") != 2 or budget.get("routine_maximum") != 5:
        raise CatalogError("routine skill budget must target median 2 and maximum 5")
    if budget.get("mandatory_safety_exempt") is not True:
        raise CatalogError("mandatory safety gates must be exempt from the optional skill budget")

    vocabulary = catalog.get("routing_vocabulary")
    expected_vocabulary = {"actions", "operations", "effects", "surfaces", "domains", "flags"}
    if not isinstance(vocabulary, dict) or set(vocabulary) != expected_vocabulary:
        raise CatalogError(f"routing_vocabulary must define exactly {sorted(expected_vocabulary)}")
    for dimension in sorted(expected_vocabulary):
        values = require_string_list(
            vocabulary[dimension], f"routing_vocabulary.{dimension}", nonempty=True
        )
        if len(values) != len(set(values)):
            raise CatalogError(f"routing_vocabulary.{dimension} contains duplicates")
        if values != sorted(values):
            raise CatalogError(f"routing_vocabulary.{dimension} must be sorted")

    descriptor_schema_path = (
        repo_root / "skills" / "skill-governance" / "schemas" / "task-descriptor.schema.json"
    )
    if descriptor_schema_path.exists():
        try:
            descriptor_schema = json.loads(descriptor_schema_path.read_text(encoding="utf-8"))
            descriptor_properties = descriptor_schema["properties"]
            schema_vocabulary = {
                "actions": descriptor_properties["action"]["properties"]["primary"]["enum"],
                "operations": descriptor_properties["action"]["properties"]["operations"]["items"]["enum"],
                "effects": descriptor_properties["effects"]["items"]["enum"],
                "surfaces": descriptor_properties["surfaces"]["items"]["enum"],
                "domains": descriptor_properties["domains"]["items"]["enum"],
            }
        except (OSError, json.JSONDecodeError, KeyError, TypeError) as exc:
            raise CatalogError(f"cannot read task descriptor vocabulary: {exc}") from exc
        for dimension, schema_values in schema_vocabulary.items():
            if set(schema_values) != set(vocabulary[dimension]):
                raise CatalogError(
                    f"routing_vocabulary.{dimension} differs from task descriptor schema; "
                    f"catalog_only={sorted(set(vocabulary[dimension]) - set(schema_values))}, "
                    f"schema_only={sorted(set(schema_values) - set(vocabulary[dimension]))}"
                )

    relation_types = catalog.get("relation_types")
    if not isinstance(relation_types, dict) or set(relation_types) != RELATIONS:
        raise CatalogError(f"relation_types must define exactly {sorted(RELATIONS)}")
    gate_ids = set(require_string_list(catalog.get("gate_ids"), "gate_ids", nonempty=True))
    if len(gate_ids) != len(catalog["gate_ids"]):
        raise CatalogError("gate_ids must not contain duplicates")
    if catalog["gate_ids"] != sorted(catalog["gate_ids"]):
        raise CatalogError("gate_ids must be sorted")
    artifact_types = set(
        require_string_list(catalog.get("artifact_types"), "artifact_types", nonempty=True)
    )
    if len(artifact_types) != len(catalog["artifact_types"]):
        raise CatalogError("artifact_types must not contain duplicates")
    if catalog["artifact_types"] != sorted(catalog["artifact_types"]):
        raise CatalogError("artifact_types must be sorted")

    raw_skills = catalog.get("skills")
    if not isinstance(raw_skills, list) or not raw_skills:
        raise CatalogError("skills must be a non-empty list")
    if any(not isinstance(skill, dict) for skill in raw_skills):
        raise CatalogError("each skill entry must be an object")
    skills = list(raw_skills)
    names = [skill.get("name") for skill in skills]
    if any(not isinstance(name, str) or not name for name in names):
        raise CatalogError("each skill requires a non-empty name")
    if len(names) != len(set(names)):
        raise CatalogError("skill names must be unique")
    if names != sorted(names):
        raise CatalogError("skills must be sorted by name")
    known_skills = set(names)
    selection_order = require_string_list(
        policy.get("selection_order"), "router_policy.selection_order", nonempty=True
    )
    if len(selection_order) != len(set(selection_order)):
        raise CatalogError("router_policy.selection_order must not contain duplicates")
    unknown_order = sorted(set(selection_order) - known_skills)
    if unknown_order:
        raise CatalogError(f"router_policy.selection_order has unknown skills: {unknown_order}")

    skill_dirs = {
        path.parent.name
        for path in (repo_root / "skills").glob("*/SKILL.md")
        if path.is_file()
    }
    if known_skills != skill_dirs:
        missing = sorted(skill_dirs - known_skills)
        extra = sorted(known_skills - skill_dirs)
        raise CatalogError(f"catalog/package mismatch; missing={missing}, extra={extra}")

    decision_domains_value = catalog.get("decision_domains")
    known_domains = (
        set(require_string_list(decision_domains_value, "decision_domains", nonempty=True))
        if decision_domains_value is not None
        else {domain for skill in skills for domain in skill.get("decision_domains", [])}
    )
    if decision_domains_value is not None:
        if len(known_domains) != len(decision_domains_value):
            raise CatalogError("decision_domains must not contain duplicates")
        if decision_domains_value != sorted(decision_domains_value):
            raise CatalogError("decision_domains must be sorted")

    for skill in skills:
        name = skill["name"]
        if skill.get("status") not in STATUSES:
            raise CatalogError(f"{name}.status must be one of {sorted(STATUSES)}")
        role = skill.get("role")
        if role not in ROLES:
            raise CatalogError(f"{name}.role must be one of {sorted(ROLES)}")
        routing_mode = skill.get("routing_mode")
        if routing_mode not in ROUTING_MODES:
            raise CatalogError(f"{name}.routing_mode must be one of {sorted(ROUTING_MODES)}")
        description = skill.get("description")
        if not isinstance(description, str) or not description:
            raise CatalogError(f"{name}.description must be a non-empty string")
        skill_path = repo_root / "skills" / name / "SKILL.md"
        metadata = frontmatter(skill_path)
        if metadata.get("name") != name:
            raise CatalogError(f"frontmatter name mismatch for {name}")
        if metadata.get("description") != description:
            raise CatalogError(f"frontmatter description differs from catalog for {name}")

        triggers = skill.get("triggers", skill.get("include_when"))
        exclusions = skill.get("exclusions", skill.get("exclude_when"))
        require_string_list(triggers, f"{name}.triggers", nonempty=True)
        require_string_list(exclusions, f"{name}.exclusions", nonempty=True)
        if len(triggers) != len(set(triggers)) or len(exclusions) != len(set(exclusions)):
            raise CatalogError(f"{name} triggers and exclusions must not contain duplicates")

        routing = skill.get("routing")
        if not isinstance(routing, dict) or set(routing) != {
            "selection_strength", "triggers", "exclusions"
        }:
            raise CatalogError(f"{name}.routing has an invalid shape")
        if routing["selection_strength"] not in {"required", "optional"}:
            raise CatalogError(f"{name}.routing.selection_strength is invalid")
        for clause_kind in ("triggers", "exclusions"):
            clauses = routing[clause_kind]
            if not isinstance(clauses, list):
                raise CatalogError(f"{name}.routing.{clause_kind} must be a list")
            for index, clause in enumerate(clauses):
                location = f"{name}.routing.{clause_kind}[{index}]"
                if not isinstance(clause, dict) or not clause or not set(clause) <= set(ROUTING_CLAUSES):
                    raise CatalogError(f"{location} is not a valid routing clause")
                for field, values in clause.items():
                    route_values = require_string_list(values, f"{location}.{field}", nonempty=True)
                    if len(route_values) != len(set(route_values)):
                        raise CatalogError(f"{location}.{field} contains duplicates")
                    unknown_values = sorted(set(route_values) - set(vocabulary[ROUTING_CLAUSES[field]]))
                    if unknown_values:
                        raise CatalogError(f"{location}.{field} has unknown values: {unknown_values}")
            rendered_clauses = [json.dumps(clause, sort_keys=True) for clause in clauses]
            if len(rendered_clauses) != len(set(rendered_clauses)):
                raise CatalogError(f"{name}.routing.{clause_kind} contains duplicate clauses")
        machine_triggers = routing["triggers"]
        if routing_mode in {"automatic", "safety_only"} and not machine_triggers:
            raise CatalogError(f"{name} is {routing_mode} but has no machine trigger")
        if routing_mode in {"explicit_only", "nonselectable"} and machine_triggers:
            raise CatalogError(f"{name} is {routing_mode} but has automatic triggers")
        if role == "safety" and routing_mode != "safety_only":
            raise CatalogError(f"safety-role skill {name} must use safety_only routing")
        if routing_mode == "safety_only" and routing["selection_strength"] != "required":
            raise CatalogError(f"safety-only skill {name} cannot be optional")
        domains = require_string_list(skill.get("decision_domains"), f"{name}.decision_domains")
        unknown_domains = sorted(set(domains) - known_domains)
        if unknown_domains:
            raise CatalogError(f"{name} references unknown decision domains: {unknown_domains}")

        artifact_policy = skill.get("artifact_policy")
        if not isinstance(artifact_policy, dict):
            raise CatalogError(f"{name}.artifact_policy must be an object")
        if artifact_policy.get("durability") not in DURABILITY:
            raise CatalogError(f"{name}.artifact_policy.durability is invalid")
        if artifact_policy.get("durability") == "authorized_only":
            skill_text = skill_path.read_text(encoding="utf-8")
            if "## Authority and Artifact Policy" not in skill_text:
                raise CatalogError(
                    f"{name} uses authorized_only artifacts but lacks an explicit "
                    "Authority and Artifact Policy section"
                )
        artifacts = require_string_list(
            artifact_policy.get("artifacts"), f"{name}.artifact_policy.artifacts"
        )
        unknown_artifacts = sorted(set(artifacts) - artifact_types)
        if unknown_artifacts:
            raise CatalogError(f"{name} emits unknown artifact types: {unknown_artifacts}")
        if skill.get("risk_level") not in {"low", "medium", "high", "critical"}:
            raise CatalogError(f"{name}.risk_level is invalid")

        relations = skill.get("relations")
        if not isinstance(relations, dict) or set(relations) != RELATIONS:
            raise CatalogError(f"{name}.relations must define exactly {sorted(RELATIONS)}")
        for relation in RELATIONS:
            values = require_string_list(relations[relation], f"{name}.relations.{relation}")
            if len(values) != len(set(values)):
                raise CatalogError(f"{name}.relations.{relation} contains duplicates")
            if relation in {"requires", "runs_after", "supports", "conflicts_with"}:
                unknown = sorted(set(values) - known_skills - components)
            elif relation == "superseded_by":
                unknown = sorted(set(values) - known_skills - components)
            elif relation == "gates":
                unknown = sorted(set(values) - gate_ids)
            else:
                unknown = sorted(set(values) - artifact_types)
            if unknown:
                raise CatalogError(f"{name}.relations.{relation} has unknown targets: {unknown}")

        if skill["status"] in {"deprecated", "compatibility_alias"}:
            targets = relations["superseded_by"]
            if len(targets) != 1:
                raise CatalogError(f"{name} must have exactly one superseded_by target")
        elif relations["superseded_by"]:
            raise CatalogError(f"active skill {name} cannot have superseded_by targets")
        if skill["status"] == "active" and role == "compatibility":
            raise CatalogError(f"active skill {name} cannot use compatibility role")
        if skill["status"] != "active" and role != "compatibility":
            raise CatalogError(f"non-active skill {name} must use compatibility role")
        if skill["status"] != "active" and routing_mode != "nonselectable":
            raise CatalogError(f"non-active skill {name} must be nonselectable")
        if skill["status"] == "active" and routing_mode == "nonselectable":
            raise CatalogError(f"active skill {name} cannot be nonselectable")
        if name in selection_order and skill["status"] != "active":
            raise CatalogError(f"selection_order cannot contain non-active skill {name}")

    by_name = {skill["name"]: skill for skill in skills}
    domain_owners: dict[str, str] = {}
    for skill in skills:
        if skill["status"] != "active":
            continue
        for domain in skill["decision_domains"]:
            existing = domain_owners.get(domain)
            if existing:
                raise CatalogError(
                    f"decision domain {domain!r} has multiple active owners: "
                    f"{existing} and {skill['name']}"
                )
            domain_owners[domain] = skill["name"]
    routable = {
        skill["name"]
        for skill in skills
        if skill["status"] == "active"
        and skill["routing_mode"] in {"automatic", "safety_only"}
    }
    if set(selection_order) != routable:
        raise CatalogError(
            "selection_order must contain every and only active automatic/safety skill; "
            f"missing={sorted(routable - set(selection_order))}, "
            f"extra={sorted(set(selection_order) - routable)}"
        )
    for skill in skills:
        name = skill["name"]
        for target in skill["relations"]["conflicts_with"]:
            if target in by_name and name not in by_name[target]["relations"]["conflicts_with"]:
                raise CatalogError(f"conflicts_with must be symmetric: {name} -> {target}")
        if skill["status"] in {"deprecated", "compatibility_alias"}:
            target = skill["relations"]["superseded_by"][0]
            if target in by_name and by_name[target]["status"] in {
                "deprecated",
                "compatibility_alias",
                "removed",
            }:
                raise CatalogError(f"compatibility chains are forbidden: {name} -> {target}")

    visiting: set[str] = set()
    visited: set[str] = set()

    def visit(name: str, trail: list[str]) -> None:
        if name in visiting:
            cycle = " -> ".join([*trail, name])
            raise CatalogError(f"requires graph cycle: {cycle}")
        if name in visited:
            return
        visiting.add(name)
        for target in by_name[name]["relations"]["requires"]:
            if target in by_name:
                visit(target, [*trail, name])
        visiting.remove(name)
        visited.add(name)

    for name in names:
        visit(name, [])

    ordering_visiting: set[str] = set()
    ordering_visited: set[str] = set()

    def visit_ordering(name: str, trail: list[str]) -> None:
        if name in ordering_visiting:
            cycle = " -> ".join([*trail, name])
            raise CatalogError(f"combined requires/runs_after ordering cycle: {cycle}")
        if name in ordering_visited:
            return
        ordering_visiting.add(name)
        predecessors = [
            *by_name[name]["relations"]["requires"],
            *by_name[name]["relations"]["runs_after"],
        ]
        for target in predecessors:
            if target in by_name:
                visit_ordering(target, [*trail, name])
        ordering_visiting.remove(name)
        ordering_visited.add(name)

    for name in names:
        visit_ordering(name, [])

    return skills


def md(value: str) -> str:
    return value.replace("|", "\\|").replace("\n", " ")


def relation_summary(skill: dict[str, Any]) -> str:
    parts: list[str] = []
    for relation in sorted(RELATIONS):
        values = skill["relations"][relation]
        if values:
            parts.append(f"{relation}: {', '.join(f'`{value}`' for value in values)}")
    return "; ".join(parts) or "None"


def render_map(catalog: dict[str, Any], skills: list[dict[str, Any]]) -> str:
    policy = catalog.get("router_policy", catalog.get("core_policy"))
    rows = []
    for skill in skills:
        role = skill.get("role", "owner" if skill["decision_domains"] else "compatibility")
        rows.append(
            "| `{}` | {} | {} / {} | {} | {} | {} |\n".format(
                skill["name"],
                skill["status"],
                skill["routing_mode"],
                skill["routing"]["selection_strength"],
                role,
                md(", ".join(skill["decision_domains"]) or "None"),
                md(relation_summary(skill)),
            )
        )
    relations = "\n".join(
        f"- `{name}`: {description}" for name, description in catalog["relation_types"].items()
    )
    return (
        f"{GENERATED_NOTICE}\n# Skill Map\n\n"
        "`skill-catalog.json` is the canonical source for this generated view.\n\n"
        "## Routing Invariants\n\n"
        f"- Zero-skill route: **{'valid' if policy['zero_skill_valid'] else 'invalid'}**.\n"
        f"- Routine target median: **{policy['skill_budget']['routine_target_median']}**.\n"
        f"- Routine maximum: **{policy['skill_budget']['routine_maximum']}**.\n"
        "- Mandatory safety gates are outside the optional-skill budget.\n"
        "- Skill activation never grants write or external-action authority.\n\n"
        "## Typed Relations\n\n"
        f"{relations}\n\n"
        "## Decision Ownership\n\n"
        "| Skill | Status | Routing | Role | Decision domains | Relations |\n"
        "|---|---|---|---|---|---|\n"
        + "".join(rows)
    )


def render_index(catalog: dict[str, Any], skills: list[dict[str, Any]]) -> str:
    rows = []
    for skill in skills:
        policy = skill["artifact_policy"]
        artifacts = ", ".join(policy["artifacts"]) or "none"
        rows.append(
            "| [`{0}`](../{0}/SKILL.md) | {1} | {2} / {3} | {4} | {5} | {6} |\n".format(
                skill["name"],
                skill["status"],
                skill["routing_mode"],
                skill["routing"]["selection_strength"],
                skill["risk_level"],
                md(policy["durability"] + ": " + artifacts),
                md(skill["description"]),
            )
        )
    return (
        f"{GENERATED_NOTICE}\n# Skill Index\n\n"
        f"Catalog version: `{catalog['catalog_version']}`. Packages: **{len(skills)}**.\n\n"
        "| Skill | Status | Routing | Risk | Artifact policy | Description |\n"
        "|---|---|---|---|---|---|\n"
        + "".join(rows)
    )


def render_tree(catalog: dict[str, Any], skills: list[dict[str, Any]]) -> str:
    blocks = []
    for skill in skills:
        triggers = skill.get("triggers", skill.get("include_when"))
        exclusions = skill.get("exclusions", skill.get("exclude_when"))
        trigger_lines = "\n".join(f"  - Include: {item}" for item in triggers)
        exclusion_lines = "\n".join(f"  - Exclude: {item}" for item in exclusions)
        requires = ", ".join(f"`{item}`" for item in skill["relations"]["requires"]) or "none"
        conflicts = (
            ", ".join(f"`{item}`" for item in skill["relations"]["conflicts_with"])
            or "none"
        )
        blocks.append(
            f"- `{skill['name']}` ({skill['status']}; {skill['routing_mode']}; "
            f"{skill['routing']['selection_strength']})\n"
            f"  - Requires: {requires}\n"
            f"  - Conflicts: {conflicts}\n"
            f"{trigger_lines}\n{exclusion_lines}\n"
        )
    return (
        f"{GENERATED_NOTICE}\n# Skill Decision Tree\n\n"
        "1. Apply instruction precedence and derive the task contract.\n"
        "2. Run the safety kernel for read-only, authority, external-state, destructive, and release boundaries.\n"
        "3. Select one owner for each material decision domain. Zero selected skills is valid.\n"
        "4. Add hard prerequisites and mandatory gates; advisory relations never activate a skill.\n"
        "5. Enforce the optional-skill budget, then reclassify at each checkpoint.\n\n"
        "## Route Conditions\n\n"
        + "\n".join(blocks)
    )


def expected_outputs(catalog: dict[str, Any], skills: list[dict[str, Any]]) -> dict[str, str]:
    return {
        "skills/SKILL-MAP.md": render_map(catalog, skills),
        "skills/docs/skill-index.md": render_index(catalog, skills),
        "skills/docs/skill-decision-tree.md": render_tree(catalog, skills),
    }


def run(repo_root: Path, catalog_path: Path, check: bool) -> int:
    repo_root = repo_root.resolve()
    catalog = load_catalog(catalog_path.resolve())
    skills = validate_catalog(catalog, repo_root)
    outputs = expected_outputs(catalog, skills)
    drift: list[str] = []
    for relative, expected in outputs.items():
        path = repo_root / relative
        if check:
            actual = path.read_text(encoding="utf-8") if path.exists() else None
            if actual != expected:
                drift.append(relative)
        else:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(expected, encoding="utf-8")
    if drift:
        print("generated routing views are stale: " + ", ".join(drift), file=sys.stderr)
        return 1
    if check:
        print(f"routing catalog and {len(outputs)} generated views are valid")
    else:
        print(f"generated {len(outputs)} routing views from {len(skills)} skills")
    return 0


def main() -> int:
    args = parse_args()
    catalog_path = args.catalog or args.repo_root / "skills" / "skill-catalog.json"
    try:
        return run(args.repo_root, catalog_path, args.check)
    except CatalogError as exc:
        print(f"catalog validation failed: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall