# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-peer-identity-mid-session-the-credential-freshness-continuity-gap-in-long-running-agent-to-agent-warrant-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-peer-identity-mid-session-the-credential-freshness-continuity-gap-in-long-running-agent-to-agent-warrant-chains.warrant.json
# Markdown SHA-256:   6dccd8d36b9293463586642bc5883d6184a34575168b7915f96e71dd5093960b
# Code AST SHA-256:   ce39b7279ff3a92bc79eb00e07fdfd7a9ed016a3eaeef4fdc3713527f3d8865b
# Verified Classes:   StaleWarrantError, Credential, Session
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleWarrantError(RuntimeError):
    """Raised when a dispatch would occur under a credential that does not
    provably cover the message time, with no scope-complete re-attestation."""


@dataclass
class Credential:
    warrant_id: str
    scope: frozenset
    nbf: float
    exp: float
    version: int


@dataclass
class Session:
    peer_key: str
    credential: Credential
    last_reattest_at: float
    safety_margin: float = 30.0
    clock_skew: float = 5.0
    dispatch_log: list = field(default_factory=list)

    def _reattest_deadline(self) -> float:
        # Earlier of credential expiry minus margin, and any issuer transition.
        return self.credential.exp - self.safety_margin

    def _covers(self, now: float, required_scope: str) -> bool:
        c = self.credential
        return (
            c.nbf - self.clock_skew <= now <= c.exp + self.clock_skew
            and required_scope in c.scope
        )

    def dispatch(self, now: float, required_scope: str, reattest_fn) -> None:
        deadline = self._reattest_deadline()
        if now >= deadline:
            # Liveness heartbeat is NOT sufficient; demand scope-complete re-attestation.
            fresh = reattest_fn(session=self, nonce=now)
            if fresh is None:
                raise StaleWarrantError(
                    f"no re-attestation for warrant {self.credential.warrant_id} "
                    f"at t={now}; deadline was {deadline}"
                )
            if fresh.warrant_id != self.credential.warrant_id:
                raise StaleWarrantError(
                    f"warrant identity changed {self.credential.warrant_id} -> "
                    f"{fresh.warrant_id} without explicit rebind"
                )
            self.credential = fresh
            self.last_reattest_at = now

        if not self._covers(now, required_scope):
            raise StaleWarrantError(
                f"scope {required_scope!r} not covered by warrant "
                f"{self.credential.warrant_id} v{self.credential.version} "
                f"at t={now} (exp={self.credential.exp})"
            )

        self.dispatch_log.append(
            {
                "t": now,
                "warrant_id": self.credential.warrant_id,
                "version": self.credential.version,
                "scope": required_scope,
            }
        )


def _example_reattest(session, nonce):
    # In production: fetch current VC from issuer, verify signature + nonce binding.
    # Here we simulate the issuer having narrowed scope at nonce >= 3700.
    if nonce >= 3700:
        return Credential(
            warrant_id=session.credential.warrant_id,
            scope=frozenset({"read:corpus"}),
            nbf=3700.0,
            exp=7200.0,
            version=session.credential.version + 1,
        )
    return session.credential


if __name__ == "__main__":
    sess = Session(
        peer_key="B",
        credential=Credential("w-1", frozenset({"read:corpus", "write:draft"}), 0.0, 3600.0, 1),
        last_reattest_at=0.0,
    )
    sess.dispatch(now=100.0, required_scope="write:draft", reattest_fn=_example_reattest)
    # At t=7200 the narrowed credential no longer covers write:draft.
    try:
        sess.dispatch(now=7200.0, required_scope="write:draft", reattest_fn=_example_reattest)
    except StaleWarrantError as e:
        print(f"correctly blocked: {e}")
