# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-its-enclave-after-a-tool-call-boundary-and-why-does-the-naive-attest-once-at-session-start-invariant-silently-leak-cr.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-its-enclave-after-a-tool-call-boundary-and-why-does-the-naive-attest-once-at-session-start-invariant-silently-leak-cr.warrant.json
# Markdown SHA-256:   d9c80bf545ba360704602eb2125277d0a69de985c1aca8f616136a9a4802ec41
# Code AST SHA-256:   995cfacb223bbbf05c6938568f55eace6f23835896cc9a4a4b185233eba8ef4c
# Verified Classes:   DataDomainAttestationError, EnclaveAttestation, InvocationEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class DataDomainAttestationError(RuntimeError):
    """Raised when an enclave attestation is valid for code identity but
    does not bind the current memory lineage / data domain."""
    pass


class EnclaveAttestation:
    def __init__(self, measurement: str, domain_epoch: int, resident_tenants: frozenset[str]):
        self.measurement = measurement
        self.domain_epoch = domain_epoch
        self.resident_tenants = resident_tenants


class InvocationEnvelope:
    def __init__(self, claimed_tenant: str, claimed_epoch: int, attestation: EnclaveAttestation,
                 scratch_dirty: bool, restored_from_checkpoint: bool):
        self.claimed_tenant = claimed_tenant
        self.claimed_epoch = claimed_epoch
        self.attestation = attestation
        self.scratch_dirty = scratch_dirty
        self.restored_from_checkpoint = restored_from_checkpoint


def verify_tool_boundary(env: InvocationEnvelope, expected_measurement: str) -> None:
    att = env.attestation

    # 1. Code identity is necessary but NOT sufficient.
    if att.measurement != expected_measurement:
        raise DataDomainAttestationError(
            f"measurement mismatch: got {att.measurement!r}, expected {expected_measurement!r}"
        )

    # 2. Epoch must not regress: a stale/older epoch means the enclave has since
    #    absorbed other tenants' plaintext (warm-pool reuse).
    if env.claimed_epoch != att.domain_epoch:
        raise DataDomainAttestationError(
            f"domain epoch mismatch: caller claims {env.claimed_epoch}, "
            f"enclave signed {att.domain_epoch} — attestation does not bind current lineage"
        )

    # 3. The claimed tenant must be a subset of the signed resident set.
    if env.claimed_tenant not in att.resident_tenants:
        raise DataDomainAttestationError(
            f"tenant {env.claimed_tenant!r} not in signed resident set "
            f"{sorted(att.resident_tenants)} — cross-domain invocation refused"
        )

    # 4. Dirty scratch or checkpoint restore invalidates the domain guarantee
    #    even when the epoch matches; require a DOMAIN_RESET before proceeding.
    if env.scratch_dirty or env.restored_from_checkpoint:
        raise DataDomainAttestationError(
            "scratch region dirty or enclave restored from checkpoint: "
            "memory lineage unverified — DOMAIN_RESET required before tool call"
        )


def guarded_tool_call(env: InvocationEnvelope, expected_measurement: str, tool):
    try:
        verify_tool_boundary(env, expected_measurement)
    except DataDomainAttestationError:
        # Refuse at the transport boundary; do not fall back to cached quote.
        raise
    return tool(env.claimed_tenant)
