# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-manifest-s-declared-capability-scope-after-hot-reload-when-the-manifest-was-never-re-validated-against-the-loaded-b.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-manifest-s-declared-capability-scope-after-hot-reload-when-the-manifest-was-never-re-validated-against-the-loaded-b.warrant.json
# Markdown SHA-256:   faad92752f45b2bb99c2285c20722a3b771b69081bf58b2d1bebdf9a599ce734
# Code AST SHA-256:   ee41e13fc3f25ef4f7955148621ac324c07ab3900d6c232c2cf3b5f78579d5b0
# Verified Classes:   SkillScopeViolation, SkillManifest, LoadedSkill
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SkillScopeViolation(RuntimeError):
    """Raised when a loaded skill body exceeds its validated declared scope,
    or when the body digest diverges from the manifest-bound digest."""


@dataclass
class SkillManifest:
    skill_id: str
    declared_scope: frozenset
    body_digest: str  # MUST cover the body, not just the manifest


@dataclass
class LoadedSkill:
    manifest: SkillManifest
    body: bytes
    verified: bool = False


def load_and_verify(manifest: SkillManifest, fetch_body) -> LoadedSkill:
    body = fetch_body(manifest.skill_id)
    actual = hashlib.sha256(body).hexdigest()
    if actual != manifest.body_digest:
        raise SkillScopeViolation(
            f"body digest mismatch for {manifest.skill_id}: "
            f"manifest={manifest.body_digest} actual={actual}"
        )
    return LoadedSkill(manifest=manifest, body=body, verified=True)


def dispatch_tool_call(
    skill: LoadedSkill,
    tool_name: str,
    agent_allowlist: frozenset,
    sandbox_grant: frozenset,
) -> None:
    if not skill.verified:
        raise SkillScopeViolation(
            f"skill {skill.manifest.skill_id} invoked before body verification"
        )
    effective = skill.manifest.declared_scope & agent_allowlist & sandbox_grant
    if tool_name not in effective:
        raise SkillScopeViolation(
            f"skill {skill.manifest.skill_id} called out-of-scope tool "
            f"'{tool_name}'; effective scope={sorted(effective)}"
        )
    # execute tool within the intersected scope
