# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconnects-to-an-mcp-server-mid-session-and-the-server-treats-the-new-transport-as-a-fresh-session-capability-scoped-aut.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconnects-to-an-mcp-server-mid-session-and-the-server-treats-the-new-transport-as-a-fresh-session-capability-scoped-aut.warrant.json
# Markdown SHA-256:   031349d51e76485979d459f36256dd625eb9b68f03e8f29fa709d398722ff695
# Code AST SHA-256:   416602972af28d6ccba647b8cfeb6db1ad5d7e638133883d5eeae7310d9069fa
# Verified Classes:   ScopeDiscontinuityError, GrantEpoch, TaskBinding, SessionGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class ScopeDiscontinuityError(RuntimeError):
    """Raised when a logical task's authorized tool surface changes across a
    transport reconnect without an acknowledged capability notification."""


@dataclass
class GrantEpoch:
    """Snapshot of the authorized tool surface at a point in a task."""
    epoch_id: str
    tools: Set[str]
    roots: Set[str]

    @classmethod
    def snapshot(cls, tools: Set[str], roots: Set[str]) -> "GrantEpoch":
        digest = hashlib.sha256(
            ("|".join(sorted(tools)) + "#" + "|".join(sorted(roots))).encode()
        ).hexdigest()[:16]
        return cls(epoch_id=digest, tools=set(tools), roots=set(roots))


@dataclass
class TaskBinding:
    """Binds a logical task to the grant epoch it started under."""
    instance_token: str
    task_id: str
    start_epoch: GrantEpoch
    mutating_tools: Set[str] = field(default_factory=set)


class SessionGuard:
    def __init__(self) -> None:
        self._bindings: Dict[str, TaskBinding] = {}

    def begin_task(self, instance_token: str, task_id: str,
                   current_tools: Set[str], current_roots: Set[str],
                   mutating_tools: Set[str]) -> TaskBinding:
        epoch = GrantEpoch.snapshot(current_tools, current_roots)
        binding = TaskBinding(instance_token, task_id, epoch, mutating_tools)
        self._bindings[task_id] = binding
        return binding

    def check_before_call(self, task_id: str, tool: str,
                          live_tools: Set[str], live_roots: Set[str],
                          reconnect_observed: bool,
                          capability_notification_acked: bool) -> None:
        binding = self._bindings.get(task_id)
        if binding is None:
            raise ScopeDiscontinuityError(
                f"task {task_id} has no recorded grant epoch; refusing mutating call"
            )
        live = GrantEpoch.snapshot(live_tools, live_roots)

        # Non-mutating reads may proceed under any epoch that still contains the tool.
        if tool not in binding.mutating_tools:
            if tool not in live.tools:
                raise ScopeDiscontinuityError(
                    f"read tool {tool} absent from live surface {sorted(live.tools)}"
                )
            return

        # Mutating calls: the surface must match the task-start epoch, OR the
        # change must have been delivered via an acknowledged capability notification.
        if live.epoch_id != binding.start_epoch.epoch_id:
            if reconnect_observed and not capability_notification_acked:
                raise ScopeDiscontinuityError(
                    f"task {task_id}: mutating tool {tool} requested after reconnect; "
                    f"surface changed {binding.start_epoch.epoch_id} -> {live.epoch_id} "
                    f"with no acknowledged tools/list_changed. Halt and re-authorize."
                )
            if tool not in live.tools:
                raise ScopeDiscontinuityError(
                    f"task {task_id}: mutating tool {tool} not in live surface "
                    f"{sorted(live.tools)} (epoch {live.epoch_id}); grant was dropped."
                )


def guarded_write(guard: SessionGuard, task_id: str, tool: str,
                  live_tools: Set[str], live_roots: Set[str],
                  reconnect_observed: bool,
                  capability_notification_acked: bool) -> str:
    guard.check_before_call(
        task_id, tool, live_tools, live_roots,
        reconnect_observed, capability_notification_acked,
    )
    return f"authorized {tool} under live epoch"


if __name__ == "__main__":
    g = SessionGuard()
    g.begin_task(
        instance_token="agent-7f3a",
        task_id="task-991",
        current_tools={"fs.read", "fs.write"},
        current_roots={"/work", "/work/out"},
        mutating_tools={"fs.write"},
    )
    # Simulate a transparent reconnect that re-negotiated only read scope.
    try:
        guarded_write(
            g, "task-991", "fs.write",
            live_tools={"fs.read"},
            live_roots={"/work"},
            reconnect_observed=True,
            capability_notification_acked=False,
        )
    except ScopeDiscontinuityError as exc:
        print(f"HALT: {exc}")
