# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-capability-warrant-at-the-exact-moment-taint-detection-fires-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-capability-warrant-at-the-exact-moment-taint-detection-fires-mid-tool-call.warrant.json
# Markdown SHA-256:   e52828a46a46f4a50ca665f102a4a2a271bf1aea51b72b97563460df2361bec9
# Code AST SHA-256:   c3fe15bfe7b387aa93204d3a1d565836e30f2b63d7490f66e7728b3a32307b1f
# Verified Classes:   TaintDowngradeInterrupt, Warrant, Invocation, Sandbox
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintDowngradeInterrupt(RuntimeError):
    """Raised when a taint detector narrows a warrant mid-invocation.

    The invocation must be terminated and its uncommitted effects discarded.
    The warrant object captured at dispatch is never mutated.
    """
    def __init__(self, warrant_id: str, committed: bool, offending_clause: str):
        self.warrant_id = warrant_id
        self.committed = committed
        self.offending_clause = offending_clause
        super().__init__(
            f"warrant {warrant_id} downgraded mid-invocation "
            f"(committed={committed}, clause={offending_clause})"
        )


class Warrant:
    """Immutable capability set. Downgrade returns a new Warrant."""
    def __init__(self, clauses: frozenset[str], wid: str):
        self._clauses = clauses
        self.wid = wid

    def require(self, clause: str) -> None:
        if clause not in self._clauses:
            raise PermissionError(f"{self.wid} lacks {clause}")

    def meet(self, ceiling: frozenset[str], new_wid: str) -> "Warrant":
        return Warrant(self._clauses & ceiling, new_wid)

    def __eq__(self, other):
        return isinstance(other, Warrant) and self._clauses == other._clauses


class Invocation:
    """A dispatched tool call holding an immutable warrant reference."""
    def __init__(self, warrant: Warrant, streaming: bool):
        self.warrant = warrant          # captured by value, never reassigned
        self.streaming = streaming
        self.committed = False

    def execute_chunk(self, clause: str, effect_fn) -> None:
        self.warrant.require(clause)
        effect_fn()
        if self.streaming:
            self.committed = True


class Sandbox:
    def __init__(self, taint_ceiling: frozenset[str]):
        self.taint_ceiling = taint_ceiling

    def on_taint_detected(self, inv: Invocation, offending_clause: str) -> Warrant:
        """Called by the detector. Never mutates inv.warrant."""
        if inv.committed:
            raise TaintDowngradeInterrupt(inv.warrant.wid, True, offending_clause)
        # Atomic invocation: safe to re-dispatch under a narrowed warrant.
        return inv.warrant.meet(self.taint_ceiling, new_wid=f"{inv.warrant.wid}~taint")
