# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-unsafe-tool-call-sequences-when-agent-state-is-only-partially-observable.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-unsafe-tool-call-sequences-when-agent-state-is-only-partially-observable.warrant.json
# Markdown SHA-256:   5055af87d6ea86050b058ab459274f05c4ed5a758d8ff4ebc681bcacb719dada
# Code AST SHA-256:   7a3199bc3cd8210f87105241a2a507f8cd0fb92e89f2a006e8e82ba521c14783
# Verified Classes:   StaleAuthorizationWitnessError, Witness
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAuthorizationWitnessError(RuntimeError):
    """Raised when a trace-level confirm is presented as a state-level gate
    but its backing witness is stale, missing, or non-monotonic."""
    pass


@dataclass(frozen=True)
class Witness:
    version: int
    issued_at: float
    source: str  # must be the authoritative store, not a cache


MAX_WITNESS_AGE_S = 5.0


def require_fresh_witness(
    witness: Witness | None,
    observed_version: int,
    now: float | None = None,
    max_age_s: float = MAX_WITNESS_AGE_S,
) -> None:
    """Gate a destructive->constructive transition on a monotonic, fresh witness.

    A trace invariant (e.g. 'confirm_owner preceded create') is necessary but
    not sufficient. This function enforces the state-transition invariant:
    the confirm must be backed by a witness from the authoritative store whose
    version is strictly ahead of the version the agent acted on, and whose age
    is below the mutation-to-read window.
    """
    now = time.monotonic() if now is None else now

    if witness is None:
        raise StaleAuthorizationWitnessError(
            "no witness: confirm step is trace-decoration, not a gate"
        )
    if witness.source != "authoritative":
        raise StaleAuthorizationWitnessError(
            f"witness sourced from {witness.source!r}; caches cannot authorize"
        )
    age = now - witness.issued_at
    if age > max_age_s:
        raise StaleAuthorizationWitnessError(
            f"witness age {age:.2f}s exceeds window {max_age_s:.2f}s"
        )
    if witness.version <= observed_version:
        raise StaleAuthorizationWitnessError(
            f"witness version {witness.version} not ahead of observed "
            f"{observed_version}; transition would rebind a stale owner"
        )


def guard_delete_then_create(
    witness: Witness | None,
    observed_version: int,
    now: float | None = None,
) -> None:
    require_fresh_witness(witness, observed_version, now=now)
    # Only reached when the state-transition invariant is witnessed.
    return None
