# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-when-a-hardware-backed-workload-identity-token-expires-mid-tool-call-and-the-downstream-tool-has-already-committed-si.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-when-a-hardware-backed-workload-identity-token-expires-mid-tool-call-and-the-downstream-tool-has-already-committed-si.warrant.json
# Markdown SHA-256:   afe563423eccf9908bfc9e740d297788bc1161fb3af9db4fc9ffd102b79124d1
# Code AST SHA-256:   d3d12b0690b22aa0e8e1df6405d0f9ac5ec19c9d43264c1608a2085d96887129
# Verified Classes:   IdentityContinuityError, WorkloadIdentity, WIT, Reservation, AgentToolState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class IdentityContinuityError(RuntimeError):
    """Raised when a committed side effect cannot be re-attributed to the
    same stable workload identity across a WIT re-mint boundary."""
    pass


@dataclass
class WorkloadIdentity:
    enclave_measurement: str
    key_fingerprint: str

    @property
    def stable_sub(self) -> str:
        # Stable across re-mints of the same workload. This is the ONLY
        # value a downstream tool may use as an ownership predicate.
        h = hashlib.sha256(
            f"{self.enclave_measurement}|{self.key_fingerprint}".encode()
        )
        return "wid:" + h.hexdigest()[:32]


@dataclass
class WIT:
    sub: str                 # MUST equal WorkloadIdentity.stable_sub
    instance_id: str         # rotating; replay protection ONLY, never ownership
    nonce: str               # rotating
    issued_at: float
    ttl_s: int

    def expired(self, now: float | None = None) -> bool:
        return (now if now is not None else time.time()) >= self.issued_at + self.ttl_s


@dataclass
class Reservation:
    handle: str
    owner_sub: str           # stable sub of the committing workload
    committed: bool = False
    reversed: bool = False


@dataclass
class AgentToolState:
    identity: WorkloadIdentity
    open_reservations: dict[str, Reservation] = field(default_factory=dict)


def mint(identity: WorkloadIdentity, instance_id: str, nonce: str,
         now: float, ttl_s: int = 300) -> WIT:
    return WIT(sub=identity.stable_sub, instance_id=instance_id,
               nonce=nonce, issued_at=now, ttl_s=ttl_s)


def commit_reservation(state: AgentToolState, wit: WIT, handle: str,
                       now: float) -> Reservation:
    if wit.expired(now):
        raise IdentityContinuityError(
            f"WIT expired at commit admission for handle={handle}")
    if wit.sub != state.identity.stable_sub:
        # Minting service populated sub from a rotating field. Refuse to
        # commit under an identity we cannot later re-prove.
        raise IdentityContinuityError(
            f"WIT sub={wit.sub} does not match stable workload identity "
            f"{state.identity.stable_sub}; ownership would be unprovable "
            f"across re-mint")
    r = Reservation(handle=handle, owner_sub=state.identity.stable_sub,
                    committed=True)
    state.open_reservations[handle] = r
    return r


def confirm_reservation(state: AgentToolState, wit: WIT, handle: str,
                        now: float) -> None:
    r = state.open_reservations.get(handle)
    if r is None or not r.committed:
        raise IdentityContinuityError(
            f"confirm for unknown/uncommitted handle={handle}")
    if r.reversed:
        raise IdentityContinuityError(
            f"confirm for handle={handle} after reversal; side effect is "
            f"orphaned, escalate — do not re-issue")
    if wit.expired(now):
        # Re-mint and re-present the SAME handle under the SAME stable sub.
        # Do not re-issue the operation as a fresh call.
        raise IdentityContinuityError(
            f"WIT expired mid-continuation for handle={handle}; re-mint and "
            f"re-present handle, do not re-issue")
    if wit.sub != r.owner_sub:
        raise IdentityContinuityError(
            f"confirm identity {wit.sub} != reservation owner {r.owner_sub}; "
            f"identity discontinuity — hard stop, do not retry")
    # Continuation accepted; reservation settled.
    state.open_reservations.pop(handle, None)


def on_reversal_webhook(state: AgentToolState, handle: str) -> None:
    # Compensation channel MUST be wired into agent context so a reversed
    # commit is surfaced, not left as a phantom success in memory.
    r = state.open_reservations.get(handle)
    if r is not None:
        r.reversed = True
        # Emit correction into episodic memory: operation did NOT complete.
        raise IdentityContinuityError(
            f"handle={handle} reversed by tool; correct agent memory record "
            f"from success to reversed")
