# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-tool-manifest-whose-declared-capability-hash-diverges-from-its-runtime-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-tool-manifest-whose-declared-capability-hash-diverges-from-its-runtime-side-effects.warrant.json
# Markdown SHA-256:   b1b9040eba3a84c6be1e250ddb01fe27700e7d659762d88db3b731ff5176fcd7
# Code AST SHA-256:   3515bef513edb36c466dc50366a7227481b0188e24de171605bfc05c30204e5f
# Verified Classes:   CapabilityHashDivergence, Manifest, ResolvedHandler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass


class CapabilityHashDivergence(RuntimeError):
    """Raised when a tool's declared capability hash does not match the
    hash of its resolved runtime effect closure at the invocation boundary."""


@dataclass(frozen=True)
class Manifest:
    name: str
    declared_capability_hash: str
    handler_ref: str  # must be an immutable digest ref, e.g. "sha256:..."
    version: str


@dataclass(frozen=True)
class ResolvedHandler:
    body: bytes
    effect_inputs: tuple[tuple[str, str], ...]  # (name, value) of effect-determining inputs


def compute_effect_closure_hash(handler: ResolvedHandler) -> str:
    """Hash the handler body PLUS its effect-determining inputs.

    A signature-only hash is insufficient: identical signatures can yield
    divergent side effects when env/config inputs differ.
    """
    h = hashlib.sha256()
    h.update(handler.body)
    for name, value in sorted(handler.effect_inputs):
        h.update(b"\x00")
        h.update(name.encode())
        h.update(b"=")
        h.update(value.encode())
    return "sha256:" + h.hexdigest()


def _is_immutable(ref: str) -> bool:
    return ref.startswith("sha256:")


def authorize_and_invoke(manifest: Manifest, handler: ResolvedHandler) -> None:
    # Guard 1: the ref must be pinned to an immutable digest.
    if not _is_immutable(manifest.handler_ref):
        raise CapabilityHashDivergence(
            f"{manifest.name}: handler_ref {manifest.handler_ref!r} is mutable; "
            "declared capability attestation is void."
        )

    # Guard 2: compare declared vs runtime effect-closure hash at the
    # invocation boundary, after lazy resolution.
    runtime_hash = compute_effect_closure_hash(handler)
    if runtime_hash != manifest.declared_capability_hash:
        raise CapabilityHashDivergence(
            f"{manifest.name}: declared {manifest.declared_capability_hash} "
            f"!= runtime {runtime_hash}; refusing invocation."
        )

    # Side effects permitted only past both guards.
    _execute(handler)


def _execute(handler: ResolvedHandler) -> None:
    # Placeholder for the actual sandboxed invocation.
    return None
