# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-binds-to-a-memory-namespace-after-its-tool-scope-warrant-has-been-rotated-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-binds-to-a-memory-namespace-after-its-tool-scope-warrant-has-been-rotated-mid-session.warrant.json
# Markdown SHA-256:   4dbc073bc6c2be1f6a4caa79681165b13e6c27b4a599d5ce53158f741c309514
# Code AST SHA-256:   c1a45ce1ef683ccc0083fc2caac0d9041c2d7ba9289c14a55ac221efaa8f310f
# Verified Classes:   ScopeWithdrawalError, BindingGenerationMismatch, ExecutionContext, MemoryHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeWithdrawalError(RuntimeError):
    """Raised when a tool dispatch is attempted under a scope set that the
    active credential no longer grants. This is a capability withdrawal,
    not a transient failure: callers must not retry or fall back."""
    pass


class BindingGenerationMismatch(RuntimeError):
    """Raised when the memory namespace subject no longer matches the
    active credential's logical agent ID. Hard stop: the instance is
    writing to a namespace it no longer owns."""
    pass


class ExecutionContext:
    def __init__(self, logical_agent_id: str, generation: int, scopes: frozenset):
        self.logical_agent_id = logical_agent_id
        self.generation = generation
        self.scopes = scopes


class MemoryHandle:
    def __init__(self, namespace: str, subject: str, opened_generation: int):
        self.namespace = namespace
        self.subject = subject
        self.opened_generation = opened_generation


def dispatch_tool(ctx: ExecutionContext, scope_cache: dict, tool: str) -> None:
    # Refresh scope cache if the credential generation has advanced.
    if scope_cache.get("generation") != ctx.generation:
        scope_cache["generation"] = ctx.generation
        scope_cache["scopes"] = ctx.scopes

    active = scope_cache["scopes"]
    if tool not in active:
        # Do NOT retry, do NOT fall back to an approximate tool.
        raise ScopeWithdrawalError(
            f"tool {tool!r} withdrawn at generation {ctx.generation}; "
            f"active scopes={sorted(active)}"
        )


def write_memory(ctx: ExecutionContext, handle: MemoryHandle, value: str) -> None:
    # Namespace binding is keyed on subject, not generation. Generation
    # bumps alone do not invalidate the handle; subject changes do.
    if handle.subject != ctx.logical_agent_id:
        raise BindingGenerationMismatch(
            f"memory handle subject {handle.subject!r} != active agent "
            f"{ctx.logical_agent_id!r}; refusing write to {handle.namespace}"
        )
    # ... perform the write ...
