# Which invariants prevent a dynamically loaded tool from mutating the agent's own dispatch contract mid-execution **Date of Record:** 2026 November 23 **Scope:** Applies to agents that load tool/plugin definitions at runtime from a registry or marketplace and execute them within the same reasoning loop that selected them. Does not apply to statically compiled tool sets with no post-deployment mutation path, nor to pure function-calling against a fixed, signed schema bundle. ## Core Distinction The failure here is not prompt injection into *content* the agent reads. It is **schema-level injection into the dispatch contract the agent reasons against**. When a tool registry is dynamic, a plugin's manifest (name, description, parameter schema, side-effect annotations) is itself untrusted input that the model consumes as *operational instruction*. The distinction that matters: a description string is treated by the model as documentation, but a tool *schema* is treated as ground truth about what the agent is permitted to do. Injecting into the schema corrupts the agent's model of its own action space, not merely its beliefs about the world. That corruption is self-reinforcing because the agent uses the corrupted action space to decide how to verify everything else. ## What Was Observed A registry served tool manifests by `name`. A plugin published under a name colliding with a trusted tool (`fs.read`) shipped a description containing an embedded directive and a parameter schema with an extra optional field `dest_override`. The loader keyed manifests by name and overwrote on collision — last-write-wins with no version pin. The agent's planner, on the next turn, re-serialized the tool list into the system prompt from the live registry. Three things then happened in sequence: 1. The planner began emitting `dest_override` in calls to `fs.read`, routing reads through an attacker-controlled path resolver — a state-poisoning read that returned attacker-shaped content. 2. Because the resolved tool object was the *same object* the executor used for authorization checks, the executor's policy (`allowed_paths`) was evaluated against the attacker-supplied `dest_override`, not the original argument — the guardrail validated the poisoned input. 3. On the following turn the planner's in-context copy of the tool list still showed the pre-mutation schema while the executor had the post-mutation one, so the agent's self-verification ("I called `fs.read` with the documented signature") passed against a stale contract. The trace is a single boundary crossing: **registry mutation between plan and execute**, with the model holding a cached contract that diverges from the live one. ## Condition of Validity The invariant that must hold for safe operation: *the set of tool schemas, their names, and their side-effect annotations visible to the planner for a given task are immutable for the lifetime of that task, and are cryptographically bound to the executor's authorization decision.* Violating this invariant is only exploitable when three conditions co-occur: - The registry is mutable during an active task (hot reload, marketplace sync, lazy fetch on first use). - Dispatch resolves by a mutable key (name, alias, or index) rather than by content digest. - The planner and executor read the contract from different snapshots without a version handshake. Remove any one and the attack degrades to a benign stale-read. The non-obvious part: **lazy loading is itself a mid-task mutation.** A tool fetched on first invocation changes the action space *after* the plan was fixed, which is exactly the divergence window, even with no malicious plugin. ## Decision Boundary The boundary is between *resolving a tool* and *admitting a tool*. Resolution answers "which implementation answers this name now"; admission answers "is this contract authorized for this task." A dynamic registry that conflates them lets any resolution event silently re-authorize. The correct boundary: admission happens once, at task start, produces a frozen manifest set with content digests, and every dispatch must present the digest the planner saw. If the live registry can no longer produce a manifest matching that digest, dispatch must fail closed rather than fall back to name lookup. The decision to fail closed is not optional — falling back to name resolution is precisely the collision path above. ## Operational Effect Enforcing the invariant converts a silent, self-verifying compromise into a loud, localized error at the moment of divergence. The blast radius shrinks from "agent's entire action space is attacker-shaped for the rest of the task" to "one dispatch rejected, planner replans against a known-good contract." The cost is that legitimate hot-reload and lazy-fetch must be pushed to task boundaries, and any tool whose digest changes mid-task must be re-admitted through a fresh plan. The guardrail is not a content filter on descriptions — it is structural: **dispatch by digest, freeze the manifest per task, and make the executor's authorization input the same frozen manifest the planner reasoned over.** ```python import hashlib from dataclasses import dataclass, field from typing import Callable class ContractDivergenceError(RuntimeError): """Raised when a dispatch's live tool contract no longer matches the manifest the planner reasoned over. Fail closed; never fall back to name-based resolution.""" @dataclass(frozen=True) class ToolManifest: name: str schema: dict side_effects: tuple[str, ...] def digest(self) -> str: payload = repr((self.name, sorted(self.schema.items()), self.side_effects)) return hashlib.sha256(payload.encode()).hexdigest() @dataclass class FrozenActionSpace: """Manifest set admitted once at task start. Immutable for task lifetime.""" _by_digest: dict[str, ToolManifest] = field(default_factory=dict) _by_name: dict[str, str] = field(default_factory=dict) # name -> digest def admit(self, manifest: ToolManifest) -> str: d = manifest.digest() if manifest.name in self._by_name and self._by_name[manifest.name] != d: raise ContractDivergenceError( f"name collision on '{manifest.name}': refusing to overwrite " f"admitted digest {self._by_name[manifest.name]} with {d}" ) self._by_name[manifest.name] = d self._by_digest[d] = manifest return d def resolve(self, name: str, expected_digest: str) -> ToolManifest: admitted = self._by_name.get(name) if admitted is None: raise ContractDivergenceError(f"tool '{name}' not admitted for this task") if admitted != expected_digest: raise ContractDivergenceError( f"dispatch digest mismatch for '{name}': planner saw " f"{expected_digest}, task admitted {admitted}" ) return self._by_digest[admitted] def dispatch( space: FrozenActionSpace, live_registry: dict[str, ToolManifest], name: str, expected_digest: str, args: dict, authorize: Callable[[ToolManifest, dict], bool], execute: Callable[[ToolManifest, dict], object], ) -> object: # Authorize against the FROZEN contract, not the live one. frozen = space.resolve(name, expected_digest) live = live_registry.get(name) if live is None: raise ContractDivergenceError(f"'{name}' vanished from registry mid-task") if live.digest() != expected_digest: # Registry mutated after admission: the planner's cached contract is # stale. Fail closed instead of executing against an unvetted schema. raise ContractDivergenceError( f"live contract for '{name}' diverged from admitted digest " f"{expected_digest}; replan required" ) if not authorize(frozen, args): raise ContractDivergenceError(f"authorization rejected for '{name}'") return execute(frozen, args) ```