# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-was-revoked-mid-execution-across-an-organizational-federation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-was-revoked-mid-execution-across-an-organizational-federation-boundary.warrant.json
# Markdown SHA-256:   bf1a4ddcb056034fc1ea8eba4af113511cde7607cb01787943e6cc3244d2d547
# Code AST SHA-256:   e21bae85ffb70a3c0c80cccadb3af435ee6b17cc227ab03be4511230730be436
# Verified Classes:   RevocationContinuityError, EpochStaleError, ProvenanceEntry, Artifact, WarrantState, FederatedPolicyEngine
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RevocationContinuityError(RuntimeError):
    """Raised when a commit would durably record an artifact whose provenance
    cites a warrant that is no longer live at commit time."""
    pass


class EpochStaleError(RevocationContinuityError):
    """Raised when the committing party's revocation epoch is behind the
    issuer's, so liveness cannot be established. Fail closed."""
    pass


@dataclass
class ProvenanceEntry:
    warrant_id: str
    step_index: int
    acquired_at: float


@dataclass
class Artifact:
    artifact_id: str
    provenance: list[ProvenanceEntry] = field(default_factory=list)
    taint: Optional[str] = None  # e.g. "DERIVED_FROM_REVOKED:w-123"


@dataclass
class WarrantState:
    warrant_id: str
    live: bool
    revoked_at: Optional[float]
    epoch: int


class FederatedPolicyEngine:
    def __init__(self, local_epoch: int):
        self.local_epoch = local_epoch
        self._warrants: dict[str, WarrantState] = {}

    def register(self, w: WarrantState) -> None:
        self._warrants[w.warrant_id] = w

    def liveness(self, warrant_id: str) -> WarrantState:
        state = self._warrants.get(warrant_id)
        if state is None:
            # Unknown warrant: fail closed, do not assume live.
            raise RevocationContinuityError(
                f"warrant {warrant_id} unknown to policy engine; refusing commit"
            )
        return state

    def check_commit(self, artifact: Artifact, issuer_epoch: int) -> None:
        # Epoch guard: if we are behind the issuer, liveness is unknowable.
        if self.local_epoch < issuer_epoch:
            raise EpochStaleError(
                f"local epoch {self.local_epoch} < issuer epoch {issuer_epoch}; "
                f"cannot establish liveness for artifact {artifact.artifact_id}"
            )
        # Provenance liveness: every cited warrant must be live, unless the
        # artifact is explicitly tainted and the taint is preserved downstream.
        if artifact.taint is not None:
            return  # tainted artifacts are allowed but must stay marked
        for entry in artifact.provenance:
            state = self.liveness(entry.warrant_id)
            if not state.live:
                raise RevocationContinuityError(
                    f"artifact {artifact.artifact_id} cites revoked warrant "
                    f"{entry.warrant_id} (revoked_at={state.revoked_at}, "
                    f"step={entry.step_index}); commit rejected — either "
                    f"re-derive or set taint='DERIVED_FROM_REVOKED:{entry.warrant_id}'"
                )


def commit_report(engine: FederatedPolicyEngine, artifact: Artifact,
                  issuer_epoch: int) -> None:
    """Commit path invoked by the receiving org (C) before writing to durable
    semantic memory. Raises if provenance cites a dead warrant."""
    engine.check_commit(artifact, issuer_epoch)
    # ... durable write happens only after check_commit returns cleanly
