# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-re-verify-a-peer-agent-s-capability-attestation-when-the-attestation-ttl-expires-mid-delegation-without-invalidating-in-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-re-verify-a-peer-agent-s-capability-attestation-when-the-attestation-ttl-expires-mid-delegation-without-invalidating-in-flight.warrant.json
# Markdown SHA-256:   0fc5852da261fd72c30a42645e2b569c865085d6468c3885db3fd12978a7de40
# Code AST SHA-256:   d426418e7c387116ba49d5702d94d656ea50a5b7a497ad090384d2766f07c000
# Verified Classes:   AttestationContinuityError, Attestation, Lease
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class AttestationContinuityError(RuntimeError):
    """Raised when a peer's capability attestation lapses mid-delegation
    and the continuation protocol cannot safely re-establish authority."""
    pass


@dataclass
class Attestation:
    attestation_id: str
    peer_did: str
    granted_tools: frozenset
    expires_at_monotonic: float
    signature: str


@dataclass
class Lease:
    attestation: Attestation
    clock_skew_grace_s: float = 30.0

    def is_current(self, now_monotonic: float) -> bool:
        return now_monotonic <= self.attestation.expires_at_monotonic + self.clock_skew_grace_s

    def expired(self, now_monotonic: float) -> bool:
        return now_monotonic > self.attestation.expires_at_monotonic + self.clock_skew_grace_s


def reattest_mid_delegation(
    lease: Lease,
    now_monotonic: float,
    identity_challenge_passes: bool,
    remaining_tools: frozenset,
    revoked_tools: frozenset,
    fresh_attestation: Optional[Attestation],
) -> Lease:
    """Called at the expiry boundary. Returns a continuation lease or raises.

    Two-dimensional decision: identity AND scope, never identity alone.
    """
    if not lease.expired(now_monotonic):
        return lease  # still inside window; nothing to do

    # Dimension 1: identity must be re-proved, not cached.
    if not identity_challenge_passes:
        raise AttestationContinuityError(
            f"peer {lease.attestation.peer_did} failed identity re-challenge at "
            f"expiry of {lease.attestation.attestation_id}; halt and quarantine"
        )

    # Dimension 2: remaining scope must be cleanly re-grantable.
    blocked = remaining_tools & revoked_tools
    if blocked:
        raise AttestationContinuityError(
            f"remaining work for {lease.attestation.peer_did} depends on revoked "
            f"tools {sorted(blocked)}; checkpoint and return to originator for re-plan"
        )

    if fresh_attestation is None:
        raise AttestationContinuityError(
            f"identity re-proved for {lease.attestation.peer_did} but no fresh "
            f"attestation issued; cannot extend authority without a new signed window"
        )

    if not remaining_tools.issubset(fresh_attestation.granted_tools):
        raise AttestationContinuityError(
            f"fresh attestation {fresh_attestation.attestation_id} does not cover "
            f"remaining tools {sorted(remaining_tools - fresh_attestation.granted_tools)}"
        )

    return Lease(attestation=fresh_attestation, clock_skew_grace_s=lease.clock_skew_grace_s)
