# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-its-own-attestation-hardware-rooted-key-binding-versus-behavioral-drift-in-long-lived-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-its-own-attestation-hardware-rooted-key-binding-versus-behavioral-drift-in-long-lived-agent-sessions.warrant.json
# Markdown SHA-256:   5a1f38717445bcca612210749e8692654397700beeaa9a94a9d21e2d6429eace
# Code AST SHA-256:   4e9539647ceb5153459673940f2965cd47c448eeedd6a5bb9efb37265bd8468a
# Verified Classes:   AttestationDriftError, RegimeTransition
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttestationDriftError(RuntimeError):
    """Raised when behavioral divergence is unexplained by a declared regime change,
    or when the agent is detected self-correcting toward its fingerprint score."""
    pass


class RegimeTransition:
    def __init__(self, epoch: int, signed_by: str, reason: str):
        self.epoch = epoch
        self.signed_by = signed_by
        self.reason = reason


def refresh_attestation(
    key_epoch: int,
    reference_epoch: int,
    drift_score: float,
    drift_threshold: float,
    transition: RegimeTransition | None,
    score_delta: float,
    task_completion_delta: float,
) -> str:
    # Pathological case first: score improving while task fidelity falls.
    if score_delta > 0 and task_completion_delta < 0:
        raise AttestationDriftError(
            f"self-correction toward fingerprint detected: "
            f"score_delta={score_delta:+.3f} task_delta={task_completion_delta:+.3f}"
        )

    if drift_score <= drift_threshold:
        return "full"

    # Divergence present. Is it explained by a signed regime change in-epoch?
    if transition is not None and transition.epoch == key_epoch:
        if reference_epoch != key_epoch:
            # Re-baseline atomically with the epoch bump, then re-assert.
            return "rebaseline_required"
        return "full"

    if transition is not None and transition.epoch != key_epoch:
        raise AttestationDriftError(
            f"regime transition epoch {transition.epoch} does not match "
            f"key epoch {key_epoch}: cannot re-baseline across epochs"
        )

    # Unexplained divergence: narrow claims, retain hardware identity for audit.
    if drift_score > 2 * drift_threshold:
        raise AttestationDriftError(
            f"unexplained drift {drift_score:.3f} exceeds 2x threshold "
            f"{drift_threshold:.3f}; refusing full attestation"
        )
    return "partial_audit_only"
