# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-co-sign-a-delegated-receipt-when-the-delegator-s-capability-warrant-is-transitively-valid-but-its-revocat.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-co-sign-a-delegated-receipt-when-the-delegator-s-capability-warrant-is-transitively-valid-but-its-revocat.warrant.json
# Markdown SHA-256:   323f3902e641e489192cbe3b6263400d5a833bbfde360584c058ac948b06192d
# Code AST SHA-256:   c4e90ce683bc5ee0a1ed93294d50924e901104c43ccfaa6f4c20450cfa3efcae
# Verified Classes:   StaleRevocationEpochError, Warrant, ExecutionRecord, Receipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleRevocationEpochError(RuntimeError):
    """Raised when a co-signature would attest an action whose warrant
    epoch does not match the delegator's live revocation epoch."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    epoch: int          # revocation epoch under which this warrant was minted
    scope: frozenset


@dataclass(frozen=True)
class ExecutionRecord:
    warrant: Warrant
    e_exec: int | None  # epoch the delegatee observed at execution time
    action: str


@dataclass(frozen=True)
class Receipt:
    execution: ExecutionRecord
    cosigned: bool


def cosign_receipt(
    execution: ExecutionRecord,
    current_epoch: int,
    delegator_live_scope: frozenset,
) -> Receipt:
    w = execution.warrant

    # 1. Delegatee must have recorded the epoch it observed at execution.
    if execution.e_exec is None:
        raise StaleRevocationEpochError(
            f"warrant {w.warrant_id}: execution record lacks e_exec; "
            "cannot prove liveness at execution time"
        )

    # 2. The epoch observed at execution must equal the warrant's mint epoch.
    if execution.e_exec != w.epoch:
        raise StaleRevocationEpochError(
            f"warrant {w.warrant_id}: e_exec={execution.e_exec} != "
            f"warrant.epoch={w.epoch}; warrant was already stale at execution"
        )

    # 3. No revocation may have occurred between execution and co-sign.
    if current_epoch > execution.e_exec:
        raise StaleRevocationEpochError(
            f"warrant {w.warrant_id}: revocation epoch advanced "
            f"{execution.e_exec} -> {current_epoch} between execution and "
            "co-sign; refusing to launder a revoked capability into a receipt"
        )

    # 4. Scope must remain contained under the delegator's live scope.
    if not w.scope <= delegator_live_scope:
        raise StaleRevocationEpochError(
            f"warrant {w.warrant_id}: scope {sorted(w.scope)} not contained "
            f"in live delegator scope {sorted(delegator_live_scope)}"
        )

    return Receipt(execution=execution, cosigned=True)
