# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-aaif-warrant-as-a-hard-stop-rather-than-a-soft-warning-during-agent-to-agent-capability-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-aaif-warrant-as-a-hard-stop-rather-than-a-soft-warning-during-agent-to-agent-capability-attestation.warrant.json
# Markdown SHA-256:   51dd71adc551e6d7bed57778b905adf706a25885e0f6d1b9a8bc7c32d461a816
# Code AST SHA-256:   28fdc69f1ed469a6b89e58632375444c3202edb2922e54d82a34521b8c3e1d0d
# Verified Classes:   StaleAttestationError, RevokedWarrantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleAttestationError(RuntimeError):
    """Raised when a cached AAIF warrant can no longer be proven live."""
    pass


class RevokedWarrantError(RuntimeError):
    """Raised when the registry reports the warrant revoked."""
    pass


MAX_STATUS_GAP = 50  # K: max registry sequence-number staleness we will honor


def authorize_capability(warrant: dict, registry, mutation_ledger: list) -> bool:
    """
    warrant: cached VC with keys 'status_index', 'revocation_endpoint', 'subject'
    registry: object exposing .current_index() and .check_revoked(subject)
    """
    cached_index = warrant["status_index"]

    try:
        current_index = registry.current_index()
        revoked = registry.check_revoked(warrant["subject"])
    except ConnectionError:
        # Registry unreachable: fail closed, but only if we are already stale.
        if _gap_unknown_but_assumed_stale(warrant):
            raise StaleAttestationError(
                f"registry unreachable and warrant {warrant['subject']} "
                f"cannot be proven live (cached index {cached_index}); "
                f"refusing capability invocation"
            )
        raise StaleAttestationError(
            f"registry unreachable; cannot confirm liveness for "
            f"{warrant['subject']}"
        )

    if revoked:
        # Retroactively quarantine effects committed under the stale window.
        for effect in mutation_ledger:
            if effect["warrant_subject"] == warrant["subject"]:
                effect["quarantined"] = True
        raise RevokedWarrantError(
            f"warrant {warrant['subject']} revoked at registry index "
            f"{current_index}; {len(mutation_ledger)} committed effects "
            f"flagged for principal review"
        )

    gap = current_index - cached_index
    if gap > MAX_STATUS_GAP:
        raise StaleAttestationError(
            f"warrant {warrant['subject']} status gap {gap} exceeds "
            f"K={MAX_STATUS_GAP}; re-attestation required before use"
        )

    return True


def _gap_unknown_but_assumed_stale(warrant: dict) -> bool:
    # Conservative default: without a registry reading we cannot bound the gap,
    # so any warrant on a resume path is treated as stale.
    return warrant.get("resumed", False)
