# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-proof-of-possession-key-was-rotated-out-from-under-it-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-proof-of-possession-key-was-rotated-out-from-under-it-mid-execution.warrant.json
# Markdown SHA-256:   714030f1a4e9cdb42835ffe955592625f4a868d38484a70a75f67588c34c0c8b
# Code AST SHA-256:   e319907d200485fc2dbf1fb084afad59457013bf74aabe505d51d239aee3d93c
# Verified Classes:   PossessionBindingError, SubjectRevokedError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PossessionBindingError(RuntimeError):
    """Raised when the instance's held key no longer matches the verifier's binding."""
    pass


class SubjectRevokedError(RuntimeError):
    """Raised when re-binding fails because the subject itself is deauthorized."""
    pass


# Rejection codes that indicate a key/binding mismatch rather than a transient fault.
_REBIND_CODES = {"invalid_proof", "key_rotated", "kid_mismatch"}


def handle_tool_rejection(rejection_code: str, held_kid: str, verifier_kid: str | None,
                          rebind_attempted: bool) -> str:
    """
    Classify a tool-call rejection and decide the only legal next action.
    Returns one of: 'retry', 'rebind', 'escalate'.
    """
    if rejection_code in _REBIND_CODES:
        if verifier_kid is not None and verifier_kid == held_kid:
            # Verifier claims our key is current, yet proof failed: this is a
            # genuine signing/transport fault, not a rotation. Retry is legal.
            return "retry"
        if rebind_attempted:
            # We already re-bound once and still fail: the subject is gone.
            raise SubjectRevokedError(
                f"re-bind attempted but proof still rejected (held_kid={held_kid}, "
                f"verifier_kid={verifier_kid}); subject is deauthorized"
            )
        # First proof-mismatch: rotate our key material and re-sign exactly once.
        return "rebind"

    if rejection_code in {"timeout", "5xx", "connection_reset", "transient"}:
        return "retry"

    # Unknown rejection: never retry blindly, never assume rotation.
    raise PossessionBindingError(
        f"unclassified rejection '{rejection_code}'; refusing to retry or re-bind "
        f"without an explicit code (held_kid={held_kid})"
    )
