# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-manifest-that-passed-registry-verification-but-was-mutated-between-admission-and-load.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-manifest-that-passed-registry-verification-but-was-mutated-between-admission-and-load.warrant.json
# Markdown SHA-256:   dfb81c2dbdddf3d74707fbd0fb6c11592fcdbf47c27aa99dfc18067ad557efdf
# Code AST SHA-256:   21c61a316327e147c5adb2c114e0a15d5f7336f64c5f3b6e6f801f82409e59f6
# Verified Classes:   SkillProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib


class SkillProvenanceError(RuntimeError):
    """Raised when a skill artifact fails load-time provenance verification."""
    pass


def load_skill(manifest: dict, fetch_artifact) -> bytes:
    """
    Load a skill artifact only if its content digest matches the digest
    pinned inside the signed manifest. The manifest must have been verified
    (signature + capability policy) before this call.
    """
    ref = manifest.get("artifact_ref", "")
    if "@sha256:" not in ref:
        # mutable pointer (tag/branch/alias) -> unbounded grant, refuse
        raise SkillProvenanceError(
            f"artifact_ref {ref!r} is not digest-pinned; "
            "capability grant is not bound to executable content"
        )

    pinned = ref.split("@sha256:", 1)[1].lower()
    artifact = fetch_artifact(ref)

    actual = hashlib.sha256(artifact).hexdigest()
    if actual != pinned:
        # artifact mutated after admission; grant no longer applies
        raise SkillProvenanceError(
            f"digest mismatch for {ref!r}: "
            f"pinned={pinned[:12]}… actual={actual[:12]}…"
        )

    # description must live in the signed manifest, not the artifact
    if "description" not in manifest:
        raise SkillProvenanceError(
            "skill description missing from signed manifest; "
            "model-facing text would be unsigned"
        )

    return artifact
