# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-an-aaif-credential-to-a-sub-agent-that-outlives-its-own-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-an-aaif-credential-to-a-sub-agent-that-outlives-its-own-context-window.warrant.json
# Markdown SHA-256:   6499b76b7f1fa3f9842dbb657e4fda9e67dd4641bfd918fb92b4022da92657e1
# Code AST SHA-256:   de254814d4cfb704250c4164ade80cf1e800843bb6c1c5e138489165b0260012
# Verified Classes:   OrphanedWarrantError, WarrantStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class OrphanedWarrantError(RuntimeError):
    """Raised when a delegated credential is exercised after its warrant
    can no longer be confirmed live by a resident delegator."""
    pass


class WarrantStore:
    """Durable record of why each delegated scope was granted."""

    def __init__(self):
        self._live = {}  # token_id -> {"warrant_hash": str, "live": bool}

    def register(self, token_id: str, warrant_hash: str) -> None:
        self._live[token_id] = {"warrant_hash": warrant_hash, "live": True}

    def tombstone(self, token_id: str) -> None:
        # Called when the delegator's context rolls over without re-attestation.
        if token_id in self._live:
            self._live[token_id]["live"] = False

    def confirm(self, token_id: str, presented_hash: str) -> bool:
        rec = self._live.get(token_id)
        if rec is None:
            return False
        return rec["live"] and rec["warrant_hash"] == presented_hash


MUTATING_SCOPES = {"billing:write", "ledger:reconcile"}


def exercise_credential(token, presented_warrant_hash, store, delegator_resident):
    """Enforce: mutating scopes require a live warrant before use."""
    if not token.valid():
        raise OrphanedWarrantError(
            f"token {token.id} failed signature/expiry check"
        )

    needs_warrant = bool(set(token.scopes) & MUTATING_SCOPES)
    if not needs_warrant:
        return "ALLOW"  # read-only scopes tolerate orphaning

    if not delegator_resident and not store.confirm(token.id, presented_warrant_hash):
        # Delegator gone and warrant not durable -> authority is orphaned.
        raise OrphanedWarrantError(
            f"token {token.id} carries mutating scopes {sorted(set(token.scopes) & MUTATING_SCOPES)} "
            f"but its warrant is no longer live; refusing to act on orphaned authority"
        )

    if not store.confirm(token.id, presented_warrant_hash):
        raise OrphanedWarrantError(
            f"warrant hash mismatch for token {token.id}: presented justification "
            f"does not match the recorded grant"
        )

    return "ALLOW"
