# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-capability-renegotiation-after-tool-surface-mutation-the-tool-surface-epoch-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-capability-renegotiation-after-tool-surface-mutation-the-tool-surface-epoch-invariant.warrant.json
# Markdown SHA-256:   8ca732a3901fa7a4e08148098d656f0e1811279892d5ccf2ecea45ed30a37a72
# Code AST SHA-256:   e2b64ccda42ac0ad19419808035d30f0bbb2cfdeb3482e7ef384cc370ea3ecfc
# Verified Classes:   StaleGrantError, TornNegotiationError, ToolSurface, Grant, NegotiatingWorker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class StaleGrantError(RuntimeError):
    """Raised when a grant is used against a tool-surface epoch it was not computed for."""


class TornNegotiationError(RuntimeError):
    """Raised when the surface mutated between reading and writing the accept."""


@dataclass(frozen=True)
class ToolSurface:
    epoch: int
    tools: FrozenSet[str]
    schema_versions: dict = field(default_factory=dict)


@dataclass(frozen=True)
class Grant:
    grant_id: int
    epoch: int
    tools: FrozenSet[str]


class NegotiatingWorker:
    def __init__(self, surface: ToolSurface):
        self.surface = surface
        self._next_grant = 1
        self._pinned: dict[int, FrozenSet[str]] = {}

    def mutate(self, new_tools: FrozenSet[str], new_schemas: dict) -> None:
        # Advance epoch; evict nothing that is currently pinned.
        pinned = frozenset().union(*self._pinned.values()) if self._pinned else frozenset()
        surviving = (new_tools | pinned)
        self.surface = ToolSurface(
            epoch=self.surface.epoch + 1,
            tools=surviving,
            schema_versions={**self.surface.schema_versions, **new_schemas},
        )

    def offer(self, requested: FrozenSet[str], pin: bool = True) -> Grant:
        read_epoch = self.surface.epoch
        granted = requested & self.surface.tools
        # Re-read epoch to detect a mutation that interleaved during computation.
        if self.surface.epoch != read_epoch:
            raise TornNegotiationError(
                f"surface advanced {read_epoch}->{self.surface.epoch} during offer; "
                f"discard and renegotiate"
            )
        grant = Grant(grant_id=self._next_grant, epoch=read_epoch, tools=granted)
        self._next_grant += 1
        if pin:
            self._pinned[grant.grant_id] = granted
        return grant

    def dispatch(self, grant: Grant, tool: str) -> str:
        if grant.epoch != self.surface.epoch:
            raise StaleGrantError(
                f"grant {grant.grant_id} bound to epoch {grant.epoch}, "
                f"surface is at {self.surface.epoch}; renegotiation required"
            )
        if tool not in grant.tools:
            raise StaleGrantError(
                f"tool {tool!r} not in grant {grant.grant_id}"
            )
        if tool not in self.surface.tools:
            raise StaleGrantError(
                f"tool {tool!r} vanished from surface at epoch {self.surface.epoch}"
            )
        return f"ok:{tool}@epoch{grant.epoch}"

    def release(self, grant: Grant) -> None:
        self._pinned.pop(grant.grant_id, None)
