# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-skill-manifest-after-registry-side-hot-reload-and-why-signature-caching-breaks-the-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-skill-manifest-after-registry-side-hot-reload-and-why-signature-caching-breaks-the-trust-boundary.warrant.json
# Markdown SHA-256:   ae1072774997f6c4c40f62e6ac25b76c8d9b916e14288e275b44db1cead5f02a
# Code AST SHA-256:   632b61a1c5e67d318b4c852caa5d4871bde59f54a1aeda7395d7ca0c960a7283
# Verified Classes:   SkillManifestVerificationError, VerifiedSkill
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillManifestVerificationError(RuntimeError):
    """Raised when a skill body cannot be bound to a verified, hash-pinned manifest
    within the current execution step. Fail closed; never fall back to a cached verdict."""
    pass


@dataclass(frozen=True)
class VerifiedSkill:
    skill_id: str
    content_hash: str
    body: bytes
    author_key_id: str


def resolve_and_verify(
    skill_id: str,
    *,
    fetch_manifest,          # (skill_id) -> (manifest_bytes, signature, author_key_id)
    fetch_body_by_hash,      # (content_hash) -> body_bytes ; fetch-by-hash, not by id
    verify_signature,        # (manifest_bytes, signature, author_key_id) -> bool
    pinned_author_keys: dict,
    content_cache: dict,     # keyed by content_hash only
) -> VerifiedSkill:
    manifest_bytes, signature, author_key_id = fetch_manifest(skill_id)

    if author_key_id not in pinned_author_keys:
        raise SkillManifestVerificationError(
            f"skill {skill_id!r}: author key {author_key_id!r} not in pinned trust root"
        )
    if not verify_signature(manifest_bytes, signature, author_key_id):
        raise SkillManifestVerificationError(
            f"skill {skill_id!r}: manifest signature invalid under key {author_key_id!r}"
        )

    import json
    manifest = json.loads(manifest_bytes)
    declared_hash = manifest.get("content_hash")
    if not declared_hash:
        raise SkillManifestVerificationError(
            f"skill {skill_id!r}: manifest does not bind a content_hash; payload-swap possible"
        )

    body = content_cache.get(declared_hash)
    if body is None:
        body = fetch_body_by_hash(declared_hash)
        actual = hashlib.sha256(body).hexdigest()
        if actual != declared_hash:
            raise SkillManifestVerificationError(
                f"skill {skill_id!r}: body hash {actual} != manifest content_hash {declared_hash}"
            )
        content_cache[declared_hash] = body

    return VerifiedSkill(
        skill_id=skill_id,
        content_hash=declared_hash,
        body=body,
        author_key_id=author_key_id,
    )


def invoke_skill(skill: VerifiedSkill, args: dict, *, executor, rehash) -> object:
    """Re-verify at the invocation boundary, not just at resolution.
    Guards against mutation between resolution and dispatch (yield, checkpoint, handoff)."""
    if rehash(skill.body) != skill.content_hash:
        raise SkillManifestVerificationError(
            f"skill {skill.skill_id!r}: body mutated between resolution and invocation"
        )
    return executor(skill.body, args)
