# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-mid-task-when-an-a2a-v1-0-agent-card-rotates-its-signing-key-between-handoff-and-audit-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-mid-task-when-an-a2a-v1-0-agent-card-rotates-its-signing-key-between-handoff-and-audit-replay.warrant.json
# Markdown SHA-256:   22a01904b533fd7d6feb230138001f4a979c18c227bf3a4645fdd660fe535b68
# Code AST SHA-256:   8915cb0a0795b3d903f417bcdb6d0699f04d0085c8e28f2a33a0862100f23f0e
# Verified Classes:   AuthorityDivergenceError, AgentCard, Warrant, DelegatedInstance
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class AuthorityDivergenceError(RuntimeError):
    """Raised when a delegated instance detects that its signing key epoch
    is no longer resolvable by the verifier, i.e. authority has decoupled
    from execution. The instance must freeze, not continue."""
    pass


@dataclass
class AgentCard:
    kid: str                 # signing key id, e.g. "ed25519:7"
    valid_until: float       # epoch seconds
    jwks_uri: str


@dataclass
class Warrant:
    task_id: str
    signed_by_kid: str
    not_after: float         # MUST be <= card.valid_until at issuance


@dataclass
class DelegatedInstance:
    card: AgentCard
    warrant: Warrant
    frozen: bool = False
    divergence_marker: Optional[str] = None
    artifacts: list = field(default_factory=list)

    def _current_epoch_resolvable(self, verifier_kids: set) -> bool:
        # The verifier can only resolve what its JWKS currently serves.
        return self.warrant.signed_by_kid in verifier_kids

    def guard_authority(self, verifier_kids: set, now: Optional[float] = None) -> None:
        now = now if now is not None else time.time()

        # Invariant 1: warrant must not outlive its signing key.
        if self.warrant.not_after > self.card.valid_until:
            raise AuthorityDivergenceError(
                f"warrant {self.warrant.task_id} notAfter={self.warrant.not_after} "
                f"exceeds card validUntil={self.card.valid_until}; "
                f"authority clock outlives card clock"
            )

        # Invariant 2: if the warrant is still live, the signing key must be
        # resolvable by the verifier. If not, authority has decoupled.
        if now <= self.warrant.not_after and not self._current_epoch_resolvable(verifier_kids):
            self.frozen = True
            self.divergence_marker = (
                f"kid={self.warrant.signed_by_kid} unresolvable at t={now}; "
                f"task={self.warrant.task_id} frozen pending re-sign or continuation token"
            )
            raise AuthorityDivergenceError(self.divergence_marker)

    def emit_artifact(self, verifier_kids: set, payload: dict) -> dict:
        if self.frozen:
            raise AuthorityDivergenceError(
                f"refusing to mint artifact for frozen task {self.warrant.task_id}: "
                f"{self.divergence_marker}"
            )
        self.guard_authority(verifier_kids)
        art = {"task_id": self.warrant.task_id, "kid": self.warrant.signed_by_kid, **payload}
        self.artifacts.append(art)
        return art


# --- observed failure reproduction -------------------------------------------
def reproduce_rotation_gap():
    now = time.time()
    card = AgentCard(kid="ed25519:7", valid_until=now + 86400, jwks_uri="https://o/.well-known/jwks")
    # Bug: warrant issued with notAfter beyond the key's validity, OR rotation
    # happens before warrant expiry and the verifier only serves the new kid.
    warrant = Warrant(task_id="T-42", signed_by_kid="ed25519:7", not_after=now + 86400)
    inst = DelegatedInstance(card=card, warrant=warrant)

    # Delegator rotates: verifier now only serves ed25519:8.
    verifier_kids = {"ed25519:8"}

    try:
        inst.emit_artifact(verifier_kids, {"result": "ok"})
    except AuthorityDivergenceError as e:
        # Correct behavior: freeze, do not mint orphaned provenance.
        assert inst.frozen is True
        assert "unresolvable" in str(e)
        return "frozen"

    # If we reach here without raising, the instance silently minted an
    # artifact under an unresolvable key — the exact decoupling we forbid.
    raise AuthorityDivergenceError(
        "instance continued under unresolvable signing key; authority decoupled from execution"
    )


if __name__ == "__main__":
    print(reproduce_rotation_gap())  # -> "frozen"
