# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-attested-identity-survives-a-behavioral-drift-it-can-no-longer-justify.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-attested-identity-survives-a-behavioral-drift-it-can-no-longer-justify.warrant.json
# Markdown SHA-256:   02b84a36196c02ea311263abc38abbb325109dc2e44fa2a98f1aaabae2191672
# Code AST SHA-256:   35a07bf5973caa00f19a2165e81f0ecbc4e101d194e459f8639c6c9405d5a476
# Verified Classes:   BaselineAbsorptionError, AttestationGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class BaselineAbsorptionError(RuntimeError):
    """Raised when an attestation-success path attempts to refresh the
    behavioral reference distribution, laundering drift into the new normal."""
    pass


class AttestationGate:
    def __init__(self, provisioned_baseline: dict, drift_threshold: float = 0.82):
        # Anchored at provisioning; immutable except via explicit re-provision.
        self._baseline = dict(provisioned_baseline)
        self._threshold = drift_threshold

    def admit(self, quote_valid: bool, behavior: dict, drift_score: float,
              re_provision_event: bool = False) -> bool:
        # Substrate integrity is non-negotiable and non-substitutable.
        if not quote_valid:
            return False

        # A clean quote must NEVER trigger a baseline refresh. If the caller
        # signals it wants one on attestation success, that is the bug.
        if re_provision_event:
            self._baseline = dict(behavior)
            return True

        # Drift is measured against the provisioning baseline, always.
        if drift_score >= self._threshold:
            # Refuse to let a passing quote paper over the drift.
            raise BaselineAbsorptionError(
                f"behavioral drift {drift_score:.2f} >= {self._threshold} "
                f"under a valid quote; denying capability issuance and "
                f"refusing baseline refresh until explicit re-provision"
            )

        return True


def issue_capability_lease(gate: AttestationGate, quote_valid: bool,
                           behavior: dict, drift_score: float) -> str:
    if not gate.admit(quote_valid, behavior, drift_score):
        raise BaselineAbsorptionError(
            "capability lease refused: substrate or policy integrity failed"
        )
    return "lease:sealed-key:ttl=drift_half_life"
