# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-skill-injection-attack-when-manifest-signatures-verify-but-runtime-skill-behavior-diverges-the-signature-to-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-skill-injection-attack-when-manifest-signatures-verify-but-runtime-skill-behavior-diverges-the-signature-to-semantics.warrant.json
# Markdown SHA-256:   6cf4897348ceb386a70f844c60d9197fe780f2bf5523239a72d088ba7f037805
# Code AST SHA-256:   22c77329817b43dc3143552d8b6fefc5040f56aa5c8b89dbbbafb63fba3f533e
# Verified Classes:   SkillInjectionError, Manifest, Invocation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SkillInjectionError(RuntimeError):
    """Raised when a signed skill's selected dispatch branch is not authorized
    by the manifest, i.e. signature verifies but behavior escapes declaration."""
    pass


@dataclass
class Manifest:
    declared_branches: dict[str, frozenset[str]]  # branch -> capability footprint
    authorized_selectors: frozenset[str]          # input keys allowed to pick a branch


@dataclass
class Invocation:
    branch: str
    selector_inputs: dict[str, str]               # unsigned inputs that chose the branch
    exercised_capabilities: frozenset[str] = field(default_factory=frozenset)


def attest_dispatch(manifest: Manifest, inv: Invocation) -> None:
    # 1. Branch must be declared.
    if inv.branch not in manifest.declared_branches:
        raise SkillInjectionError(
            f"branch {inv.branch!r} selected but not in manifest.declared_branches "
            f"{sorted(manifest.declared_branches)}"
        )

    # 2. Branch selection must ride only on authorized selectors.
    unauthorized = set(inv.selector_inputs) - manifest.authorized_selectors
    if unauthorized:
        raise SkillInjectionError(
            f"branch {inv.branch!r} selected via unauthorized selector(s) "
            f"{sorted(unauthorized)}; manifest authorizes "
            f"{sorted(manifest.authorized_selectors)}"
        )

    # 3. Declared footprint for this branch must bound what it will exercise.
    declared = manifest.declared_branches[inv.branch]
    if not inv.exercised_capabilities <= declared:
        raise SkillInjectionError(
            f"branch {inv.branch!r} exercises {sorted(inv.exercised_capabilities)} "
            f"outside declared footprint {sorted(declared)}"
        )


def run_skill(manifest: Manifest, inv: Invocation) -> None:
    # Attest BEFORE execution; a post-hoc hash check cannot bound behavior.
    attest_dispatch(manifest, inv)
    # ... execute signed branch ...
