# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-enclave-attestation-as-invalid-after-a-legitimate-tool-call-reconfiguration.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-enclave-attestation-as-invalid-after-a-legitimate-tool-call-reconfiguration.warrant.json
# Markdown SHA-256:   9f31ce45ef6ae9879662ad4d8f5d7ea6501707c30756d0c51c2e1c9d12d4ff6a
# Code AST SHA-256:   6d704147b04a717dc1f8c5ac316c69f001dbd356cd8e9bfd4a1e491e1f2be0f7
# Verified Classes:   AttestationSkewError, Quote, ToolCallingAgent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationSkewError(RuntimeError):
    """Raised when a cached quote no longer describes the executing image."""
    pass


@dataclass(frozen=True)
class Quote:
    measurement: str          # MRENCLAVE / RTMR digest
    manifest_hash: str        # hash of the tool manifest bound into report_data
    nonce: str
    issued_at: float


class ToolCallingAgent:
    def __init__(self, enclave, verifier_allowlist):
        self.enclave = enclave
        self.allowlist = verifier_allowlist  # set of (measurement, manifest_hash)
        self._cached_quote: Quote | None = None
        self._current_manifest_hash: str = self._hash_manifest()

    def _hash_manifest(self) -> str:
        manifest = self.enclave.tool_manifest()
        return hashlib.sha256(manifest.encode()).hexdigest()

    def reconfigure(self, new_tool_server: str) -> None:
        # Any mutation of the dispatch table invalidates the cached quote.
        self.enclave.load_tool_server(new_tool_server)
        self._current_manifest_hash = self._hash_manifest()
        self._cached_quote = None  # force re-attestation

    def _fresh_quote(self, nonce: str) -> Quote:
        raw = self.enclave.quote(report_data=self._current_manifest_hash)
        return Quote(
            measurement=raw.measurement,
            manifest_hash=self._current_manifest_hash,
            nonce=nonce,
            issued_at=raw.timestamp,
        )

    def invoke_tool(self, tool_name: str, nonce: str) -> bytes:
        quote = self._fresh_quote(nonce)

        # Invariant: quote must describe the *current* configuration.
        if quote.manifest_hash != self._current_manifest_hash:
            raise AttestationSkewError(
                f"quote manifest {quote.manifest_hash[:8]} != current "
                f"{self._current_manifest_hash[:8]}"
            )

        # Verifier keys on the (measurement, manifest) pair, not measurement alone.
        if (quote.measurement, quote.manifest_hash) not in self.allowlist:
            raise AttestationSkewError(
                f"configuration ({quote.measurement[:8]}, "
                f"{quote.manifest_hash[:8]}) not in allowlist; "
                f"do not retry as transient"
            )

        return self.enclave.dispatch(tool_name)
