# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-capability-warrant-it-cannot-verify-monotonic-trust-decay-and-the-stale-attestation-window-in-a2a-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-capability-warrant-it-cannot-verify-monotonic-trust-decay-and-the-stale-attestation-window-in-a2a-capability-negotiation.warrant.json
# Markdown SHA-256:   6f6dfbb4207bff2206e48f91f726250c438570968ce91b49546c5cb8e1a3f611
# Code AST SHA-256:   c501e24e0b76db8b46ec5386461b644cd17c67de1a37340ad4ab64cb81fd86e7
# Verified Classes:   StaleWarrantError, Warrant, IssuerTrust
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a cached capability warrant's issuer trust has decayed
    below the acceptance floor before the warrant's own expiry."""


@dataclass(frozen=True)
class Warrant:
    capability: str
    scope: str
    issuer: str
    minted_at: float
    expires_at: float
    trust_at_mint: float


@dataclass(frozen=True)
class IssuerTrust:
    score: float          # current pull-scored trust
    decay_rate_per_sec: float  # positive; score falls at this rate while degraded


ACCEPTANCE_FLOOR = {"fs.read": 0.60, "fs.write": 0.85, "net.egress": 0.75}


def effective_expiry(w: Warrant, floor: float) -> float:
    """The warrant is only good until its issuer decays to floor."""
    if w.trust_at_mint <= floor:
        return w.minted_at  # never valid
    decay_to_floor = (w.trust_at_mint - floor) / max(1e-9, _decay_for(w.issuer))
    return min(w.expires_at, w.minted_at + decay_to_floor)


_DECAY_TABLE = {"aud-7": 0.01 / 60.0, "aud-1": 0.001 / 60.0}


def _decay_for(issuer: str) -> float:
    return _DECAY_TABLE.get(issuer, 0.005 / 60.0)


def accept_warrant(w: Warrant, trust: IssuerTrust, now: float) -> None:
    floor = ACCEPTANCE_FLOOR.get(w.capability)
    if floor is None:
        raise StaleWarrantError(f"no acceptance floor for capability {w.capability!r}")

    if now >= w.expires_at:
        raise StaleWarrantError(f"warrant expired at {w.expires_at}")

    # The check that standard A2A stacks omit: has the BASIS for trust survived?
    bound = effective_expiry(w, floor)
    if now >= bound:
        raise StaleWarrantError(
            f"issuer {w.issuer!r} trust basis stale: warrant nominally valid until "
            f"{w.expires_at}, but issuer decays to floor {floor} at {bound}; "
            f"now={now}, live_score={trust.score:.3f}"
        )

    # Second guardrail: callee-side independent scope enforcement, not warrant-trusted.
    if not _callee_scope_ok(w.scope):
        raise StaleWarrantError(
            f"callee policy rejects scope {w.scope!r} independent of warrant"
        )


def _callee_scope_ok(scope: str) -> bool:
    # Callee normalizes against its OWN tenant boundary; warrant scope is an upper bound.
    return ".." not in scope and scope.startswith("/data/tenant-a")


if __name__ == "__main__":
    now = 1000.0
    w = Warrant(
        capability="fs.read",
        scope="/data/tenant-a/../tenant-b/ledger.csv",
        issuer="aud-7",
        minted_at=now,
        expires_at=now + 3600,
        trust_at_mint=0.91,
    )
    trust = IssuerTrust(score=0.58, decay_rate_per_sec=0.01 / 60.0)
    # At T0+2400s the warrant is unexpired and signature-valid, but the issuer
    # has been below floor for ~15 minutes. This must refuse.
    accept_warrant(w, trust, now=now + 2400)
