# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-aaif-credential-was-revoked-mid-task-when-the-revocation-channel-and-the-execution-channel-are-disjoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-aaif-credential-was-revoked-mid-task-when-the-revocation-channel-and-the-execution-channel-are-disjoint.warrant.json
# Markdown SHA-256:   12a097178256ae8cc983ef7ee1fced17f147b697cbd3b164e0dae6c1d49b9da8
# Code AST SHA-256:   4d22722677efdd44c1e5cdf0169207d6c316af52960d5da769e1c596e758b4bf
# Verified Classes:   CredentialStateError, HaltReason, DelegatedCredential, AgentExecutionLoop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CredentialStateError(RuntimeError):
    """Raised when an agent attempts to act under a credential whose
    authority status is unknown or revoked. Distinct from expiry errors:
    the credential may be cryptographically valid and time-valid while
    being authority-void."""


class HaltReason(Enum):
    EXPIRED = "expired"            # time-bounded, self-checkable
    REVOKED = "revoked"            # authority-void, channel-disjoint
    STATUS_UNKNOWN = "unknown"     # cannot confirm; must not proceed


@dataclass
class DelegatedCredential:
    credential_id: str
    scope: dict
    not_after_epoch: int
    revocation_epoch: int
    status_confirmed_epoch: Optional[int] = None

    def is_time_valid(self, now: int) -> bool:
        return now < self.not_after_epoch


@dataclass
class AgentExecutionLoop:
    credential: DelegatedCredential
    consecutive_identical_rejections: int = 0
    max_identical_rejections: int = 2
    last_known_global_epoch: Optional[int] = None

    def record_rejection(self, error_class: str) -> None:
        if error_class == "transient":
            self.consecutive_identical_rejections = 0
            return
        self.consecutive_identical_rejections += 1

    def pre_action_gate(self, now: int, action_is_irreversible: bool) -> None:
        cred = self.credential

        if not cred.is_time_valid(now):
            raise CredentialStateError(
                f"credential {cred.credential_id} expired at {cred.not_after_epoch}"
            )

        # Invariant: status must be confirmed at or after the credential's
        # issuance epoch, and at or after the last global epoch we have seen.
        required_epoch = max(
            cred.revocation_epoch,
            self.last_known_global_epoch or 0,
        )
        confirmed = cred.status_confirmed_epoch

        if confirmed is None or confirmed < required_epoch:
            if action_is_irreversible:
                # Fail-closed on unknown status for irreversible actions.
                raise CredentialStateError(
                    f"status for {cred.credential_id} unconfirmed "
                    f"(confirmed={confirmed}, required={required_epoch}); "
                    f"refusing irreversible action"
                )
            # For reversible actions, halt-and-checkpoint rather than retry.
            raise CredentialStateError(
                f"status unconfirmed for {cred.credential_id}; "
                f"halt and query status channel before proceeding"
            )

        if self.consecutive_identical_rejections >= self.max_identical_rejections:
            # Two identical non-transient rejections is a revocation signal,
            # not a transient error. Never retry the same credential.
            raise CredentialStateError(
                f"repeated identical rejections ({self.consecutive_identical_rejections}) "
                f"on {cred.credential_id}; treating as revocation, halting"
            )


def attempt_write(loop: AgentExecutionLoop, now: int, path: str) -> None:
    loop.pre_action_gate(now=now, action_is_irreversible=True)
    # ... perform downstream call; on non-transient rejection:
    # loop.record_rejection(error_class="authority")
    # then re-enter pre_action_gate to trigger the halt transition.
    raise CredentialStateError(
        f"write to {path} blocked: authority status not reconcilable "
        f"with execution channel"
    )
