# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-skill-whose-ed25519-signature-verifies-but-whose-declared-capability-manifest-was-re-signed-over-mutable-payload-bytes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-skill-whose-ed25519-signature-verifies-but-whose-declared-capability-manifest-was-re-signed-over-mutable-payload-bytes.warrant.json
# Markdown SHA-256:   60222abce0b85d72bf6ec50733f10dbc0a92f3692e1c3b0ee2d99906e4171779
# Code AST SHA-256:   c459c6ff3fa5fc4f5a576d2f2ca3a3627b68896281a1435818def9e14ee187e9
# Verified Classes:   SkillIntegrityViolation, SignedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillIntegrityViolation(RuntimeError):
    """Raised when signed manifest does not bind to the bytes about to execute."""


@dataclass(frozen=True)
class SignedManifest:
    name: str
    version: str
    declared_capabilities: frozenset
    payload_sha256: str
    signature_valid: bool


def load_skill(manifest: SignedManifest, fetched_payload: bytes,
               executed_bytes: bytes) -> bytes:
    # Step 1: signature must verify.
    if not manifest.signature_valid:
        raise SkillIntegrityViolation(
            f"signature invalid for {manifest.name}@{manifest.version}"
        )

    # Step 2: hash the bytes we are about to hand to the sandbox.
    actual = hashlib.sha256(fetched_payload).hexdigest()
    if actual != manifest.payload_sha256:
        raise SkillIntegrityViolation(
            f"payload hash mismatch for {manifest.name}@{manifest.version}: "
            f"signed={manifest.payload_sha256} actual={actual}"
        )

    # Step 3: the executed artifact must be exactly the hashed bytes.
    # Catches archive-unpack / post-install-hook divergence.
    if executed_bytes != fetched_payload:
        raise SkillIntegrityViolation(
            f"executed bytes diverge from signed payload for "
            f"{manifest.name}@{manifest.version}"
        )

    return executed_bytes
