# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-s-declared-schema-after-the-registry-hot-swaps-the-implementation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-s-declared-schema-after-the-registry-hot-swaps-the-implementation.warrant.json
# Markdown SHA-256:   66d4f17c6f7c1738416a3c7ee86c17e0d5650effa5806bb1694793ce113ce923
# Code AST SHA-256:   2c2f88d0f8f276a3c0e2cc06d4b47e953136fbee3a6cbe991b2bae8ceed173fb
# Verified Classes:   ToolIdentityDriftError, SandboxProfileMissingError, CachedDeclaration, LiveTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ToolIdentityDriftError(RuntimeError):
    """Raised when the live tool implementation no longer matches the
    declaration the planner cached into its context."""
    pass


class SandboxProfileMissingError(RuntimeError):
    """Raised when no pre-approved sandbox profile exists for the live
    artifact digest. Fail closed: never inherit the prior profile."""
    pass


@dataclass(frozen=True)
class CachedDeclaration:
    name: str
    schema: dict
    artifact_digest: str          # hash of the implementation artifact
    approved_sandbox: dict        # profile keyed to artifact_digest


@dataclass(frozen=True)
class LiveTool:
    name: str
    handler: object
    artifact_bytes: bytes


def _digest(artifact: bytes) -> str:
    return hashlib.sha256(artifact).hexdigest()


def dispatch(cached: CachedDeclaration, live: LiveTool, args: dict) -> object:
    # 1. Identity is the digest, not the name. A swap under the same name
    #    produces a digest mismatch and fails closed.
    live_digest = _digest(live.artifact_bytes)
    if live_digest != cached.artifact_digest:
        raise ToolIdentityDriftError(
            f"tool {cached.name!r} changed since plan: "
            f"cached digest {cached.artifact_digest[:12]} != "
            f"live digest {live_digest[:12]}; re-plan against new declaration"
        )

    # 2. Sandbox profile must be re-derived from the live artifact, not
    #    inherited from the cached declaration's annotations.
    profile = cached.approved_sandbox.get(live_digest)
    if profile is None:
        raise SandboxProfileMissingError(
            f"no pre-approved sandbox for {cached.name!r}@{live_digest[:12]}; "
            f"refusing to run under stale profile"
        )

    # 3. Schema validation happens against the declaration the model saw,
    #    which is now guaranteed to describe the executing artifact.
    for field, typ in cached.schema.items():
        if field not in args:
            raise ToolIdentityDriftError(f"missing arg {field!r} per cached schema")

    return live.handler(args, sandbox=profile)
