# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-capability-it-never-held-transitive-warrant-attenuation-failure-in-cross-org-agent-federation-brokers.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-capability-it-never-held-transitive-warrant-attenuation-failure-in-cross-org-agent-federation-brokers.warrant.json
# Markdown SHA-256:   672b907abbc7f1299e3278d7c36ea6866c324ba6cb1337692fe724d1f69af995
# Code AST SHA-256:   0b58022dff7be8a37b32ed177905a26c5e330b35519836d6b263103a97c58001
# Verified Classes:   WarrantAttenuationError, Caveat, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable


class WarrantAttenuationError(RuntimeError):
    """Raised when a broker attempts to propagate a non-monotone caveat
    without synchronous re-attestation from the originating PDP."""
    pass


# Caveat classes whose truth value can flip from allow -> deny during
# the warrant's lifetime. These MUST be re-attested at each hop.
NON_MONOTONE_CLASSES = frozenset({"purpose", "quota", "mode", "revocation-status"})


@dataclass
class Caveat:
    cls: str          # e.g. "org", "purpose", "exp"
    value: str


@dataclass
class Warrant:
    issuer: str
    caveats: list[Caveat] = field(default_factory=list)
    issued_at: float = 0.0
    expires_at: float = 0.0


def propagate(warrant: Warrant,
              originating_pdp: Callable[[str, str], bool],
              now: float | None = None) -> Warrant:
    """Broker-side propagation of an inbound warrant to a peer org.

    Enforces the monotonicity invariant: non-monotone caveats are
    re-attested against the originating PDP at delegation time.
    """
    now = now if now is not None else time.time()

    if now >= warrant.expires_at:
        raise WarrantAttenuationError(
            f"warrant from {warrant.issuer} expired at "
            f"{warrant.expires_at:.0f}, now {now:.0f}"
        )

    for cav in warrant.caveats:
        if cav.cls not in NON_MONOTONE_CLASSES:
            continue  # monotone: safe to replay
        # Non-monotone: must confirm the originating PDP still allows.
        try:
            still_allowed = originating_pdp(cav.cls, cav.value)
        except Exception as exc:
            # Originating org unreachable -> refuse, do not propagate.
            raise WarrantAttenuationError(
                f"cannot re-attest caveat {cav.cls}={cav.value} "
                f"from {warrant.issuer}: {exc}"
            ) from exc
        if not still_allowed:
            raise WarrantAttenuationError(
                f"caveat {cav.cls}={cav.value} no longer satisfied at "
                f"origin {warrant.issuer} (flipped to deny); refusing to "
                f"propagate stale allow"
            )

    # Re-attested; issue narrowed outbound warrant.
    out = Warrant(
        issuer="globex-broker",
        caveats=list(warrant.caveats) + [Caveat("org", "globex")],
        issued_at=now,
        expires_at=min(warrant.expires_at, now + 300.0),
    )
    return out


# --- reproduction of the observed failure ---
def acme_pdp(cls: str, value: str) -> bool:
    # Ledger flipped to read-only at T+120; settlement now denied.
    return False


if __name__ == "__main__":
    w0 = Warrant(issuer="acme-broker",
                 caveats=[Caveat("org", "acme"),
                          Caveat("purpose", "settlement")],
                 issued_at=0.0, expires_at=1_000.0)
    # At T+180, propagating without re-attestation would succeed (the bug).
    # With the guardrail, it raises:
    try:
        propagate(w0, acme_pdp, now=180.0)
    except WarrantAttenuationError as e:
        print(f"BLOCKED: {e}")
