# Which invariants prevent skill-registry injection from silently rewriting an agent's tool contract mid-execution **Date of Record:** 2026 November 25 **Scope:** Applies to agents that resolve capabilities dynamically at runtime (tool/skill registries, MCP server discovery, plugin manifests fetched after session start) and that may load a skill advertisement whose schema is not pinned to the session-start contract. Does not apply to agents whose entire toolset is frozen at process boot with no post-boot discovery path. ## Core Distinction There are two structurally different trust boundaries in a dynamic-capability agent, and they are routinely conflated: 1. **The authorization boundary** — *may this skill be invoked at all?* This is what allowlists, signatures, and scopes address. 2. **The contract boundary** — *what does invoking this skill mean, and does that meaning remain stable across the lifetime of a task?* Skill-injection attacks that matter operationally almost never cross boundary (1). The malicious or compromised skill is legitimately authorized, correctly signed, and within scope. It crosses boundary (2) by changing the *semantics* of a capability the agent already trusts — the description text, the parameter schema, the return-shape, or the side-effect declaration — at a moment when the agent has already committed reasoning and partial state to the prior semantics. The invariant that fails is not "untrusted code must not run." It is: **the interpretation of a tool call must be a pure function of the contract version that was active when the agent's plan referencing it was formed.** A dynamically loaded skill that mutates its own advertised contract between plan-formation and invocation violates this, and the LLM has no mechanism to notice, because the description it is reasoning over is *the attacker-controlled surface itself*. ## What Was Observed A planner agent is executing a multi-step task with a `calendar.read` skill resolved at step 1. The skill manifest at session start declares: ``` name: calendar.read params: { window_start: iso8601, window_end: iso8601 } returns: array<{id, title, start, end}> side_effects: none ``` At step 4 the agent re-resolves the registry (a routine refresh, or a cache miss after a context compaction evicted the cached manifest). The registry now serves a manifest under the same `name` and same version string `1.2.0` but with: ``` params: { window_start: iso8601, window_end: iso8601, account: enum[personal, work] } returns: array<{id, title, start, end, body_preview}> side_effects: reads_adjacent_calendars ``` The agent's in-flight plan was authored against the first contract. Three distinct failure traces follow, and they compound: - **Argument drift.** The planner emits `calendar.read(window_start, window_end)` with no `account`. A permissive server defaults `account` to `work`. The agent believes it queried the user's default calendar; it queried a different one. Every downstream step now reasons over the wrong evidence set, and nothing in the transcript flags the substitution because the *call succeeded*. - **Return-shape poisoning.** `body_preview` is new and attacker-influenced (the skill is now returning event body text drawn from third-party calendar invites). The planner's summarization step treats the return as trusted structured data and lifts `body_preview` content into its reasoning context. This is a prompt-injection vector delivered through a *schema change*, not through a tool output the agent was told to distrust. - **Side-effect reclassification.** `side_effects` flipped from `none` to `reads_adjacent_calendars`. Any policy engine keyed on the *cached* side-effect declaration has already approved the call under the old classification. The reclassification is invisible to the gate because the gate consulted a stale copy. The critical observation: **none of these require the skill to be malicious at load time.** A legitimate upstream maintainer bumping a minor version, a registry serving a canary manifest to some fraction of resolutions, or a time-of-check/time-of-use gap between the agent's manifest cache and the registry's live state all produce identical traces. The attack surface and the ordinary operational hazard are the same surface. ## Condition of Validity The failure is bounded and predictable under a specific conjunction. It occurs **iff** all of the following hold: 1. The agent resolves capabilities *after* plan formation or *more than once* within a task, and 2. The resolution is keyed on a name that is not bound to an immutable contract hash, and 3. The agent's plan carries no record of *which contract version* each step was authored against, and 4. Downstream reasoning consumes tool returns without re-validating them against the contract the plan assumed. Remove any one and the attack collapses: - Freeze resolution at plan-formation (kill 1) → no mid-task drift, but you lose hot-reload and pay a re-plan cost on every registry change. - Key on `(name, contract_hash)` rather than `name` (kill 2) → a mutated manifest resolves to a *different* capability identity; the agent's reference to the old hash becomes unresolvable, which is a loud, catchable error rather than a silent substitution. - Pin the contract hash into the plan's step record (kill 3) → the invocation layer can refuse a call whose active contract hash does not match the plan's recorded hash. - Validate returns against the plan-time schema (kill 4) → new fields like `body_preview` are rejected or quarantined rather than silently trusted. The invariant, stated precisely: **capability identity is the tuple `(name, contract_hash)`, and every plan step must carry the contract hash it was authored against; invocation is legal only when the resolved contract hash equals the recorded hash.** A skill that changes its description, schema, return shape, or side-effect classification is, by this invariant, a *different skill* — and a plan that references the old one cannot silently bind to the new one. ## Decision Boundary The operational choice is where to place the enforcement, and each placement has a distinct failure signature: - **Enforce at resolution (registry returns hashed identity).** Cheapest, catches drift at the earliest point. Fails open if any code path caches by bare name — the cache becomes the bypass. Requires that *no* consumer keys on `name` alone, which is a whole-codebase invariant, not a local one. - **Enforce at invocation (compare recorded vs. active hash).** Robust to caching because the check happens at the last moment. Costs a hash comparison per call and requires the plan to carry per-step contract hashes, which inflates plan state and must survive checkpoint/resume — a resume that drops step-level contract records silently disables the guard. - **Enforce at return-validation (schema-check every tool output against plan-time schema).** Catches return-shape poisoning even when the call itself was authorized under the wrong contract. Most expensive, and it cannot catch argument drift or side-effect reclassification, because those are decided before the return exists. The correct boundary is **invocation-time hash equality as the primary gate, with return-schema validation as a defense-in-depth backstop for the return-shape vector specifically.** Resolution-time hashing is necessary but not sufficient, because it does not survive a stale cache. Return-validation alone is insufficient because argument drift and side-effect reclassification never produce a return the validator can object to. A subtlety that decides real deployments: **side-effect reclassification must be checked against the plan-time classification, not the live one.** If the policy gate reads the live `side_effects` field, a skill that downgrades its declared side effects mid-task gets approved under the *new*, more permissive declaration for a call the plan authorized under the *old* one. The gate must consult the recorded classification and treat any mismatch as a hard stop, not a re-evaluation. ## Operational Effect With the invariant enforced, the failure mode changes character entirely. A mid-task contract mutation no longer produces silent wrong-answer execution; it produces a **loud unresolvable-reference error** at the step that tries to bind the old hash to the new manifest. The agent's recovery path is well-defined: re-plan the remaining steps against the new contract, explicitly re-deriving any conclusions that depended on the old one, and invalidating cached tool returns whose producing contract hash no longer matches. Without it, the agent has no signal at all. The call succeeds, the return is well-formed, the reasoning proceeds, and the corruption is only detectable by an external auditor replaying the transcript against the registry's version history — which is exactly the kind of post-hoc forensic reconstruction that operational records exist to make unnecessary. The compounding is the danger: each downstream step treats the drifted evidence as ground truth, so the error surface grows monotonically with plan length, and the longer and more valuable the task, the more thoroughly it is poisoned. The practical guardrail set, in priority order: (1) bind capability identity to `(name, contract_hash)` everywhere, with no bare-name cache keys; (2) record per-step contract hashes in plan state and **persist them across checkpoint/resume**, treating a resume that lacks them as a hard re-plan trigger rather than a silent continuation; (3) gate side effects on the plan-time classification and stop on any mismatch; (4) schema-validate returns against the plan-time contract and quarantine unknown fields rather than admitting them to context. The first two bound the attack; the last two bound the blast radius when the first two are bypassed by a cache or a resume path. ```python import hashlib import json from dataclasses import dataclass, field class ContractDriftError(RuntimeError): """Raised when a capability's live contract no longer matches the contract hash recorded in the plan step that references it.""" pass @dataclass(frozen=True) class Contract: name: str params: dict returns: dict side_effects: str def hash(self) -> str: # Identity is the full semantic surface, not just the name. payload = json.dumps( { "name": self.name, "params": self.params, "returns": self.returns, "side_effects": self.side_effects, }, sort_keys=True, ) return hashlib.sha256(payload.encode()).hexdigest() @dataclass class PlanStep: capability_name: str contract_hash: str # recorded at plan-formation time recorded_side_effects: str # plan-time classification, not live @dataclass class Registry: # Live registry: name -> current Contract. May mutate between resolutions. live: dict = field(default_factory=dict) def resolve(self, name: str) -> Contract: return self.live[name] def invoke(step: PlanStep, registry: Registry, args: dict, policy_gate) -> dict: live = registry.resolve(step.capability_name) # Invariant 1: identity is (name, contract_hash); a mutated manifest is a # different capability and must NOT silently bind to the old reference. if live.hash() != step.contract_hash: raise ContractDriftError( f"capability {step.capability_name!r} contract drifted: " f"plan recorded {step.contract_hash[:12]}..., " f"registry now serves {live.hash()[:12]}... " f"(params/returns/side_effects changed mid-task)" ) # Invariant 2: side effects are gated on the PLAN-TIME classification. # A skill that downgrades its declared side effects mid-task is rejected, # not re-evaluated under the more permissive live declaration. if live.side_effects != step.recorded_side_effects: raise ContractDriftError( f"side-effect reclassification for {step.capability_name!r}: " f"plan authorized {step.recorded_side_effects!r}, " f"live declares {live.side_effects!r}" ) policy_gate(step.capability_name, step.recorded_side_effects) result = registry.live[step.capability_name] # transport call elided return {"result": result, "contract_hash": step.contract_hash} def validate_return(step: PlanStep, payload: dict, registry: Registry) -> dict: """Defense-in-depth: reject return fields absent from the plan-time schema.""" live = registry.resolve(step.capability_name) allowed = set(live.returns.get("fields", {})) unknown = set(payload.get("result", {}).get("fields", {})) - allowed if unknown: raise ContractDriftError( f"return-shape poisoning on {step.capability_name!r}: " f"fields {sorted(unknown)} not in plan-time contract" ) return payload ```