# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-s-declared-capability-set-before-the-registry-has-verified-its-provenance-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-s-declared-capability-set-before-the-registry-has-verified-its-provenance-chain.warrant.json
# Markdown SHA-256:   7e0f9c7117293238e5e1eaa84a1a4b9f5b48f51880dc8c56a1f57a36dc515aaf
# Code AST SHA-256:   204a8cd52898e062e1bf3f4d91823d49c502861a90583c10fd7ac135b2a582b7
# Verified Classes:   SkillProvenanceError, PlanInvalidationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SkillProvenanceError(RuntimeError):
    """Raised when a skill's NL content would enter context before provenance resolves."""
    pass


class PlanInvalidationError(RuntimeError):
    """Raised when a revoked skill's plan steps cannot be cleanly invalidated."""
    pass


TRUSTED_ROOTS = {"publisher:acme-signed", "publisher:internal-root"}


def admit_skill(manifest: dict, chain: list[str]) -> dict:
    """
    Admission gate. Must run BEFORE manifest NL content enters model context.
    Returns the manifest only if provenance resolves synchronously to a trusted root.
    """
    if not chain:
        raise SkillProvenanceError(
            f"skill {manifest.get('name')!r}: empty provenance chain; "
            f"refusing admission (no async-verify-then-revoke path permitted)"
        )
    root = chain[-1]
    if root not in TRUSTED_ROOTS:
        raise SkillProvenanceError(
            f"skill {manifest.get('name')!r}: chain terminates at untrusted root "
            f"{root!r}; NL content must not enter context"
        )
    # Only now is it safe to expose name/schema/descriptions to the model.
    return manifest


def revoke_skill(skill_name: str, active_plan: list[dict]) -> list[dict]:
    """
    Mid-session revocation. Must invalidate plan steps whose rationale cited
    the revoked skill, forcing clean re-plan. Blocking the call is insufficient.
    """
    invalidated = []
    for step in active_plan:
        if skill_name in step.get("rationale_cites", []):
            step["status"] = "invalidated"
            invalidated.append(step)
    if invalidated:
        # If we cannot re-derive a clean plan, fail closed rather than let the
        # model re-plan around the revocation using alternate tools.
        clean = [s for s in active_plan if s["status"] != "invalidated"]
        if any(s.get("approximates_revoked") for s in clean):
            raise PlanInvalidationError(
                f"revocation of {skill_name!r} left plan steps that approximate "
                f"its effect via alternate trust domains; halting to prevent pivot"
            )
    return active_plan


def load_skills(manifests: list[dict], chains: dict[str, list[str]]) -> list[dict]:
    admitted = []
    for m in manifests:
        name = m.get("name")
        # Synchronous, blocking admission. No partial/optimistic load.
        admitted.append(admit_skill(m, chains.get(name, [])))
    return admitted
