# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-taint-quarantine-decision-is-being-made-on-a-stale-capability-graph-in-multi-agent-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-taint-quarantine-decision-is-being-made-on-a-stale-capability-graph-in-multi-agent-tool-invocation.warrant.json
# Markdown SHA-256:   5fbade9ab40d45f64bef394b760660b246557dadea1fdd75f5f098b68ff558ac
# Code AST SHA-256:   8c0c61bb0fc6d7b23c1d5d3bbe0b8e339c8a017f913da1fad18dfc8ea2571f23
# Verified Classes:   StaleTaintEpoch, CapabilityToken, Invocation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleTaintEpoch(RuntimeError):
    """Raised when a capability token's taint epoch predates its invocation inputs,
    or when the tool server's taint view lags the inputs' provenance."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    agent_id: str
    scope: str            # e.g. "doc_write:resource/R"
    taint_epoch: int      # G_taint version at mint time


@dataclass(frozen=True)
class Invocation:
    agent_id: str
    scope: str
    input_taint_epoch: int   # max provenance epoch across attached inputs
    input_nodes: tuple


def authorize_invocation(
    token: CapabilityToken,
    inv: Invocation,
    server_taint_epoch: int,
    taint_events_between,   # callable(lo, hi) -> set of tainted node ids
    propagation_deadline_exceeded: bool = False,
) -> bool:
    # 1. Capability scope must match.
    if token.agent_id != inv.agent_id or token.scope != inv.scope:
        return False

    # 2. Token must not predate its inputs. This is the core invariant.
    if token.taint_epoch < inv.input_taint_epoch:
        raise StaleTaintEpoch(
            f"token epoch {token.taint_epoch} < input epoch "
            f"{inv.input_taint_epoch} for {inv.agent_id}:{inv.scope}; re-mint required"
        )

    # 3. Server view must be at-or-after the inputs' provenance.
    if server_taint_epoch < inv.input_taint_epoch:
        if propagation_deadline_exceeded:
            raise StaleTaintEpoch(
                f"server taint epoch {server_taint_epoch} lags input epoch "
                f"{inv.input_taint_epoch}; propagation deadline exceeded"
            )
        return False  # block, do not fail open

    # 4. Re-evaluate taint at the server's current epoch, not the token's.
    tainted = taint_events_between(token.taint_epoch, server_taint_epoch)
    if any(node in tainted for node in inv.input_nodes):
        return False  # inputs tainted since mint; deny

    return True


def guarded_tool_call(token, inv, server_taint_epoch, taint_events_between,
                      propagation_deadline_exceeded=False):
    if not authorize_invocation(
        token, inv, server_taint_epoch, taint_events_between,
        propagation_deadline_exceeded,
    ):
        raise StaleTaintEpoch(
            f"invocation denied for {inv.agent_id}:{inv.scope} "
            f"(token_epoch={token.taint_epoch}, input_epoch={inv.input_taint_epoch}, "
            f"server_epoch={server_taint_epoch})"
        )
    return "committed"
