# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-skill-registry-s-signature-over-its-manifest-toctou-drift-between-signed-skill-verification-and-dynamic-tool-bi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-skill-registry-s-signature-over-its-manifest-toctou-drift-between-signed-skill-verification-and-dynamic-tool-bi.warrant.json
# Markdown SHA-256:   1283f88fe88b2ad5b6c229d6bd6efeadc9823886fda21e31da0009c869b7f3c3
# Code AST SHA-256:   6861f362c076b6d586b1db993e00f5d95ca553c909fe2d577f54c3e319ca70ff
# Verified Classes:   SkillBindingError, VerifiedSkill
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillBindingError(RuntimeError):
    """Raised when the artifact bound for execution does not match the
    digest the planner verified and reasoned over."""


@dataclass(frozen=True)
class VerifiedSkill:
    name: str
    manifest_digest: str      # sha256 of the signed manifest
    artifact_digest: str      # sha256 of the exact bytes to execute
    declared_capabilities: frozenset[str]


def bind_and_execute(
    verified: VerifiedSkill,
    resolve_artifact,          # name -> bytes, mutable registry pointer
    enforce_capabilities,      # clamps execution to an independent envelope
    execute,
) -> object:
    # Resolve by name (the mutable pointer) but bind by digest.
    artifact_bytes = resolve_artifact(verified.name)
    actual_digest = hashlib.sha256(artifact_bytes).hexdigest()

    # Re-verify at the exec boundary, not just at fetch time.
    if actual_digest != verified.artifact_digest:
        raise SkillBindingError(
            f"artifact digest mismatch for {verified.name}: "
            f"planner verified {verified.artifact_digest}, "
            f"runtime resolved {actual_digest}; aborting (possible TOCTOU swap)"
        )

    # Enforced capabilities are authoritative; declared are advisory.
    enforced = enforce_capabilities(verified.name)
    effective = enforced & verified.declared_capabilities
    if effective != verified.declared_capabilities:
        # Declaration exceeded what the runtime will actually grant.
        # Log as security event; do not silently widen.
        raise SkillBindingError(
            f"capability divergence for {verified.name}: "
            f"declared {sorted(verified.declared_capabilities)} "
            f"exceeds enforced {sorted(enforced)}"
        )

    return execute(artifact_bytes, capabilities=effective)
