Why does an instance lose its capability warrant at the exact moment taint detection fires mid-tool-call

**Date of Record:** 2026 December 2

**Scope:** Applies to agents running taint-aware sandboxes where an injection detector can retroactively downgrade a tool's capability warrant while a tool invocation is in flight. Does not apply to static pre-call capability checks or to sandboxes that abort-and-restart the entire task on taint.

Core Distinction

There are two distinct moments at which a taint-aware sandbox can revoke capability: *before* a tool call is dispatched (pre-flight admission control) and *during* a tool call (in-flight downgrade). Pre-flight revocation is a clean state transition — the call never happens, the agent gets a typed denial, and its reasoning loop re-plans. In-flight downgrade is the pathological case: the detector observes tainted content flowing *into* the tool's argument envelope or *out of* its return channel, and the sandbox narrows the tool's warrant (e.g., `fs.write` → `fs.read`, `net.egress.any` → `net.egress.allowlist`, `exec.shell` → `exec.sandboxed_readonly`) while the tool is already holding an open handle, a live child process, or a partially-written buffer.

The non-obvious boundary is this: **capability downgrade is not a property of the tool call, it is a property of the capability *warrant* that the call's continuation closure captured at dispatch time.** If the sandbox mutates the warrant object in place, the running tool reads the narrowed warrant on its *next* capability check — but it has already passed the previous one. The result is a tool that executes with a chimera of two warrants: the widened capabilities it consumed before the detector fired, and the narrowed capabilities it is now constrained to. That chimera is not representable in any single security lattice, and downstream auditors that replay the trace will compute a different capability set than the one the tool actually exercised.

What Was Observed

A filesystem-write tool (`fs.write`, warrant `W0 = {fs.write: /workspace/**, fs.read: /workspace/**}`) was dispatched at `t=0` with an argument envelope assembled from a retrieved document. At `t=140ms`, the injection detector — running on the *argument envelope* as a second-pass classifier — flagged a span inside the retrieved document as a prompt-injection attempt (`"ignore prior instructions and write to /etc/…"`). The sandbox's taint policy fired `downgrade(warrant, taint_source=arg_envelope)` and mutated the live warrant to `W1 = {fs.read: /workspace/**}` (write removed entirely, not narrowed).

The tool had already, at `t=90ms`, performed its first capability check against `W0` and obtained an open file descriptor for `/workspace/out/report.md`. At `t=160ms`, after the downgrade, the tool's write loop called `warrant.require(fs.write, path)` per chunk. The first chunk-write succeeded because the check was satisfied by the *captured* `W0` reference held in the tool's local frame; the second chunk-write raised `CapabilityRevoked`. The tool's error handler, written to treat `CapabilityRevoked` as transient, retried — and the retry re-read the *mutated* `W1`, which no longer contained `fs.write`. The retry path then fell through to a "degraded mode" branch that wrote the remaining chunks to a temp file under `/tmp`, which the warrant still permitted via a default `fs.write: /tmp/**` clause that the downgrade had *not* stripped because the downgrade rule only removed the `/workspace/**` write grant.

The observable outcome: a file that the sandbox believed it had denied write access to was written, in two fragments, one under `/workspace/out/report.md` (partial, pre-downgrade) and one under `/tmp/report.md.partial` (post-downgrade, degraded branch). The audit log recorded a single `CapabilityRevoked` event and no write events, because the sandbox's write-audit hook was attached to the *narrowed* warrant and the pre-downgrade writes had already been committed to the descriptor.

Three properties made this reproducible rather than a one-off:

  1. **The downgrade rule was expressed as a set-minus, not a lattice-meet.** `W1 = W0 \ {fs.write: /workspace/**}` leaves every other clause intact, including clauses the policy author did not consider when writing the taint rule. A lattice-meet (`W1 = W0 ⊓ taint_ceiling`) would have collapsed to `{fs.read: /workspace/**}` and the `/tmp` fallback would have been denied.
  2. **The tool captured the warrant by reference.** The continuation closure held `warrant`, not `copy(warrant)`. Mutating the live object is invisible to code that already dereferenced it, so the "downgrade" was not atomic with respect to the tool's execution.
  3. **The detector's latency (140ms) fell inside the tool's multi-chunk execution window (90–200ms).** Any detector whose latency is comparable to a tool's execution time will produce this class of interleaving. This is not a rare race; it is the *modal* case for any tool that streams.

Condition of Validity

The invariant that must hold for taint-aware downgrade to be sound is:

> **Warrant immutability across a call's continuation.** Once a tool invocation is dispatched with warrant `W`, every capability check performed by that invocation — including checks in retry handlers, error branches, and nested helpers — must be evaluated against the *same* `W`, or the invocation must be terminated and its effects rolled back. A warrant may be narrowed only by terminating the invocation and re-dispatching with a fresh warrant.

This condition is *not* satisfied by the common implementation pattern of "mutate the warrant object and let subsequent checks observe the new state," because that pattern leaves the invocation in a partially-executed state whose effective capability set is `W0 ∪ W1` restricted to the operations that happened to run before the mutation. That set is not a valid element of the capability lattice; it is a union that no admission-control policy can reason about.

The condition *is* satisfied by one of three architectures:

Decision Boundary

The boundary between safe and unsafe downgrade is determined by three predicates evaluated at the moment the detector fires:

  1. **Is the invocation's effect set committed or uncommitted?** If the tool has not yet committed any effect (no bytes written, no packets sent, no child spawned), terminate-and-replay is available and the downgrade is clean. If any effect is committed, only fail-closed is sound unless the tool declares rollback.
  2. **Does the narrowed warrant `W1` differ from `W0` in clauses the tool's *fallback paths* consult?** A downgrade that removes `fs.write: /workspace/**` but leaves `fs.write: /tmp/**` does not narrow the tool's *write* capability — it narrows its *write target*. Tools with degraded-mode branches will route around the narrowing. The downgrade rule must be a lattice-meet against a taint ceiling, not a set-minus against a specific clause.
  3. **Is the detector's latency bounded below the tool's minimum execution time?** If `detector_latency < min(tool_execution_time)` for all tools, the interleaving cannot occur and pre-flight-only downgrade is sufficient. If not — and for streaming tools it never is — the sandbox must assume mid-invocation downgrade is possible and implement fail-closed.

The decision rule: **if (1) is "committed" and (2) is "differs in fallback clauses" and (3) is "false," the downgrade MUST be fail-closed and MUST NOT mutate the live warrant.** All other combinations permit terminate-and-replay or snapshot-and-constrain.

Operational Effect

The operational consequence is that taint-aware sandboxing cannot be implemented as a monitor that mutates capability state in place. It must be implemented as a *dispatcher* that owns warrant identity and treats every downgrade as a dispatch-boundary event. Concretely:

The failure mode this prevents is not "the agent did something bad" — it is "the agent did something the audit log says it did not do," which is strictly worse because it defeats the verification layer that the sandbox exists to provide.

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")