# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-revocation-propagation-gap-in-attenuated-agent-to-agent-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-revocation-propagation-gap-in-attenuated-agent-to-agent-delegation-chains.warrant.json
# Markdown SHA-256:   7f851c3b6ef5fbf66e9cc6938af361b0fa66d5825d159d47987cb5e93f62e30e
# Code AST SHA-256:   0496e56f5a24918a74fed59a1a13f192bf3a4e51e68fd9bde19e0934513a743f
# Verified Classes:   RevocationPropagationError, Warrant, RevocationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class RevocationPropagationError(RuntimeError):
    """Raised when a leaf warrant cannot prove its ancestry is unrevoked."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    parent_id: str | None
    scope: frozenset
    epoch: int                      # root revocation_epoch at mint time
    valid_until: float
    chain: tuple = field(default_factory=tuple)  # ordered ancestor ids, root-first

    def chain_hash(self) -> str:
        h = hashlib.sha256()
        for wid in self.chain + (self.warrant_id,):
            h.update(wid.encode())
        return h.hexdigest()


class RevocationLedger:
    """Authoritative root-side state. epoch advances on every revocation."""

    def __init__(self):
        self.epoch = 0
        self.revoked: set[str] = set()

    def revoke(self, warrant_id: str) -> None:
        self.revoked.add(warrant_id)
        self.epoch += 1


def use_warrant(w: Warrant, ledger: RevocationLedger, now: float | None = None) -> None:
    now = now if now is not None else time.time()

    if now > w.valid_until:
        raise RevocationPropagationError(
            f"warrant {w.warrant_id} expired at {w.valid_until}"
        )

    # Epoch gate: if any ancestor was revoked after this warrant was minted,
    # the root epoch has advanced past w.epoch and the warrant is stale.
    if w.epoch < ledger.epoch:
        # Distinguish "ancestor revoked" from "unrelated revocation" by
        # checking ancestry explicitly; if we cannot, we must fail closed.
        if any(anc in ledger.revoked for anc in w.chain):
            raise RevocationPropagationError(
                f"warrant {w.warrant_id} has revoked ancestor in chain {w.chain}"
            )
        # Epoch advanced but no ancestor revoked: still fail closed on
        # side-effecting scopes, because we cannot prove non-revocation
        # without a full ancestry re-check.
        if "write" in {s.split(":")[0] for s in w.scope}:
            raise RevocationPropagationError(
                f"warrant {w.warrant_id} epoch {w.epoch} < ledger {ledger.epoch}; "
                f"cannot prove write-scope ancestry unrevoked"
            )


def demo() -> None:
    ledger = RevocationLedger()
    w0 = Warrant("W0", None, frozenset({"read:repo", "write:staging"}), 0, time.time() + 3600, ())
    w1 = Warrant("W1", "W0", frozenset({"read:repo"}), 0, time.time() + 3600, ("W0",))
    w2 = Warrant("W2", "W1", frozenset({"read:repo:subdir"}), 0, time.time() + 3600, ("W0", "W1"))

    ledger.revoke("W0")  # operator revokes root after injection

    try:
        use_warrant(w2, ledger)
    except RevocationPropagationError as e:
        print(f"leaf correctly refused: {e}")
    else:
        # This branch is the failure mode: leaf executed under a revoked root.
        raise RevocationPropagationError(
            "revocation shadow: W2 executed despite revoked ancestor W0"
        )


if __name__ == "__main__":
    demo()
