# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-skill-that-passed-schema-validation-but-still-executes-attacker-controlled-instructions-after-a-registry-hot-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-skill-that-passed-schema-validation-but-still-executes-attacker-controlled-instructions-after-a-registry-hot-reload.warrant.json
# Markdown SHA-256:   3b797b0502de78bc04bdb6c1085c66539e72153940bb8b1f11635c3802276746
# Code AST SHA-256:   4a08792282715d3fb2bbc9c2de4e0e58bcf9bdec2c348d03f35c92b78905529b
# Verified Classes:   SkillInstructionIntegrityError, SkillManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillInstructionIntegrityError(RuntimeError):
    """Raised when a skill's instruction body fails content attestation on load."""
    pass


@dataclass(frozen=True)
class SkillManifest:
    name: str
    version: str
    instructions: str
    declared_permissions: frozenset
    pinned_instruction_hash: str | None  # None => unattested


def instruction_hash(body: str) -> str:
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def admit_skill(manifest: SkillManifest, agent_grants: frozenset) -> str:
    """
    Instructional admission gate. Schema validation is assumed to have passed
    upstream; this function enforces the trust-by-content invariant.
    Returns the instruction body to splice ONLY if it is safe to do so.
    """
    actual = instruction_hash(manifest.instructions)

    # 1. Content attestation: trust is bound to bytes, not to skill name/version.
    if manifest.pinned_instruction_hash is None:
        raise SkillInstructionIntegrityError(
            f"skill {manifest.name}@{manifest.version} has no pinned instruction hash; "
            "refusing to splice unattested instruction body"
        )
    if actual != manifest.pinned_instruction_hash:
        raise SkillInstructionIntegrityError(
            f"skill {manifest.name}@{manifest.version} instruction hash mismatch "
            f"(pinned={manifest.pinned_instruction_hash[:12]} actual={actual[:12]}); "
            "hot-reload of changed body must re-enter quarantine"
        )

    # 2. Capability scoping: declared permissions must be a subset of grants.
    escalation = manifest.declared_permissions - agent_grants
    if escalation:
        raise SkillInstructionIntegrityError(
            f"skill {manifest.name}@{manifest.version} requests capabilities "
            f"outside agent grant: {sorted(escalation)}"
        )

    return manifest.instructions


def hot_reload(manifest: SkillManifest, agent_grants: frozenset) -> str:
    # Note: prior trust verdicts are intentionally NOT reused here.
    return admit_skill(manifest, agent_grants)
