# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-tool-call-and-the-aaif-warrant-chain-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-tool-call-and-the-aaif-warrant-chain-forks.warrant.json
# Markdown SHA-256:   7c3e7ed9207453b0a5bad2f91c3fb92a6b3b3568e7f3ea0e24ef153ab1dd8f62
# Code AST SHA-256:   9c1f38a0e7061bbbf0b894e1373e6621c30decebcb56110799cffdd1d6c967a8
# Verified Classes:   WarrantForkError, WarrantChain, Intent, AgentRuntime
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class WarrantForkError(RuntimeError):
    """Raised when an intent is presented under a warrant chain that did not authorize it."""


@dataclass(frozen=True)
class WarrantChain:
    jti: str
    epoch: int
    constraints: dict

    def chain_hash(self) -> str:
        payload = f"{self.jti}|{self.epoch}|{sorted(self.constraints.items())}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class Intent:
    action: str
    signing_jti: str
    chain_hash: str
    resolved: bool = False


@dataclass
class AgentRuntime:
    current_chain: WarrantChain
    outstanding: list = field(default_factory=list)

    def issue_intent(self, action: str) -> Intent:
        intent = Intent(
            action=action,
            signing_jti=self.current_chain.jti,
            chain_hash=self.current_chain.chain_hash(),
        )
        self.outstanding.append(intent)
        return intent

    def re_attest(self, successor: WarrantChain) -> None:
        # In-turn re-attestation is only safe if no intent is outstanding.
        live = [i for i in self.outstanding if not i.resolved]
        if live:
            # Stage successor but do NOT rebind outstanding intents.
            self._staged = successor
            return
        self.current_chain = successor

    def present(self, intent: Intent) -> WarrantChain:
        # Verifier-side binding: the presented chain MUST be the signing chain.
        if intent.chain_hash != self.current_chain.chain_hash():
            raise WarrantForkError(
                f"intent signed under {intent.signing_jti} "
                f"({intent.chain_hash[:12]}) presented under "
                f"{self.current_chain.jti} ({self.current_chain.chain_hash()[:12]})"
            )
        return self.current_chain


def verify_call(runtime: AgentRuntime, intent: Intent) -> None:
    chain = runtime.present(intent)
    if intent.resolved:
        raise WarrantForkError(f"intent {intent.action!r} already resolved; replay rejected")
    # ... resource-server-side authorization under `chain` ...
    intent.resolved = True
