# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-dynamically-resolved-tool-manifest-the-deferred-binding-window-between-registry-attestation-and-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-dynamically-resolved-tool-manifest-the-deferred-binding-window-between-registry-attestation-and-first-invocation.warrant.json
# Markdown SHA-256:   2df735fa468a5032f6b34f99b15b18fc2965256d0782f210d4ea81472709507e
# Code AST SHA-256:   0e8b82daa107a3a820503087fbfdfc6d1643c64a2e0dc1af359a1cc571471727
# Verified Classes:   ManifestBindingError, SealedManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestBindingError(RuntimeError):
    """Raised when an executed manifest does not match its attested digest."""
    pass


@dataclass(frozen=True)
class SealedManifest:
    tool_name: str
    version: str
    payload: bytes          # full materialized manifest: envelope + params + examples + template
    attested_digest: str    # digest computed at attestation over `payload`


def attest(raw_manifest: dict) -> SealedManifest:
    """Materialize the ENTIRE manifest eagerly and seal it. No lazy fields survive."""
    payload = json.dumps(raw_manifest, sort_keys=True, separators=(",", ":")).encode()
    digest = hashlib.sha256(payload).hexdigest()
    return SealedManifest(
        tool_name=raw_manifest["name"],
        version=raw_manifest["version"],
        payload=payload,
        attested_digest=digest,
    )


def invoke(sealed: SealedManifest, executor_payload: bytes) -> dict:
    """
    Re-check the digest at the dereference site, over the exact bytes about to be used.
    Any re-fetch, lazy block, or cache alias that changed the bytes fails here.
    """
    live_digest = hashlib.sha256(executor_payload).hexdigest()
    if live_digest != sealed.attested_digest:
        raise ManifestBindingError(
            f"tool {sealed.tool_name}@{sealed.version}: executed bytes "
            f"{live_digest[:12]} != attested {sealed.attested_digest[:12]} — "
            f"deferred-binding window opened; refusing invocation"
        )
    manifest = json.loads(executor_payload)
    # Only now is the model allowed to see description/examples: they are attested.
    return manifest
