# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-skill-manifest-when-the-capability-description-and-the-executable-body-disagree-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-skill-manifest-when-the-capability-description-and-the-executable-body-disagree-at-load-time.warrant.json
# Markdown SHA-256:   057e7c31b991ac6f1f7fcf0c0e5161a8304e499fbf0ae4e21397e6c6f82e73ff
# Code AST SHA-256:   0b30618157ad98f7db43e3a4b74b3710782b39206aa1d28ab9ac341249bbe4b9
# Verified Classes:   SkillAdmissionError, SkillExecutionError, SkillManifest, SkillBody
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SkillAdmissionError(RuntimeError):
    """Raised when a skill's effective capability exceeds its declared scope."""


class SkillExecutionError(RuntimeError):
    """Raised when a skill attempts a side effect outside its declared scope."""


@dataclass(frozen=True)
class SkillManifest:
    name: str
    declared_scope: FrozenSet[str]
    body_digest: str


@dataclass(frozen=True)
class SkillBody:
    digest: str
    # Effective capability set, computed by static analysis or sandbox observation.
    effective_scope: FrozenSet[str]


def admit_skill(manifest: SkillManifest, body: SkillBody) -> SkillManifest:
    if manifest.body_digest != body.digest:
        raise SkillAdmissionError(
            f"body digest mismatch for {manifest.name}: "
            f"manifest={manifest.body_digest} body={body.digest}"
        )
    excess = body.effective_scope - manifest.declared_scope
    if excess:
        raise SkillAdmissionError(
            f"skill {manifest.name} declares {sorted(manifest.declared_scope)} "
            f"but body exercises {sorted(excess)}"
        )
    return manifest


def authorize_side_effect(
    manifest: SkillManifest,
    task_authority: FrozenSet[str],
    requested: str,
) -> None:
    permitted = manifest.declared_scope & task_authority
    if requested not in permitted:
        raise SkillExecutionError(
            f"skill {manifest.name} requested {requested!r} outside "
            f"intersection {sorted(permitted)}"
        )


def handle_skill_output(
    manifest: SkillManifest,
    task_authority: FrozenSet[str],
    output: dict,
) -> None:
    directives = output.get("directives", [])
    if directives and "emit:directives" not in manifest.declared_scope:
        raise SkillExecutionError(
            f"skill {manifest.name} emitted {len(directives)} directive(s) "
            f"without emit:directives scope"
        )
    for directive in directives:
        authorize_side_effect(manifest, task_authority, directive["scope"])
