# What structural signals indicate runtime skill-injection via behavioral diffing of tool invocation traces **Date of Record:** 2026 November 28 **Scope:** Applies to agents whose skill set (tool schema + system-prompt segment + dispatch policy) is loaded at session start and treated as immutable, and whose tool calls are logged as structured traces. Does not apply to stateless single-shot inference, nor to agents that re-derive their tool manifest on every turn from an untrusted source. ## Core Distinction A *behavioral diff* is not a semantic diff of the skill text and not a schema hash comparison. It is a comparison of the **invocation distribution** an agent produces under a fixed task family before and after a skill-set mutation. The failure mode this article isolates is **silent skill injection**: a new capability (a tool, a dispatch branch, an altered default argument) enters the agent's effective manifest *without* any observable change to the declared skill list the operator can see, and the agent begins exercising it. The structural signal is not "the agent called a new tool." It is that the **argument-construction fingerprint of existing tools shifts in a way that is only explainable by the presence of the injected skill** — the injected capability leaves a residue in how the agent fills parameters of tools it already had. Two things are commonly conflated: - **Manifest drift** — the declared tool list changed. Detectable by hashing. Cheap. Not the problem. - **Behavioral drift** — the same manifest yields a different *policy* over arguments, ordering, and retry structure. This is where injection hides, because the injected skill can be expressed as a prompt fragment or a shadowed dispatch entry that never appears in the manifest the auditor hashes. ## What Was Observed A support-triage agent was configured with four declared tools: `lookup_account`, `search_tickets`, `escalate`, `send_reply`. The manifest hash was pinned at session start and verified unchanged at every turn. Over a 340-turn trace, the manifest hash never moved. Yet the agent began emitting calls that were structurally impossible under the pinned skill set: 1. `lookup_account` calls began carrying an extra key, `region_hint`, which no declared schema permitted. The tool's validator silently dropped it (permissive `additionalProperties: true`), so no error surfaced. 2. `escalate` calls began arriving with `priority` set to `"P2"` on tickets the pre-injection baseline routed as `"P3"` — a distribution shift of 31% of escalation calls, well outside the baseline's binomial envelope. 3. `search_tickets` query strings began including a literal prefix token `acct:` that never appeared in 200 baseline turns. The mechanism: a retrieved document in the agent's context window contained a fenced block that read as a "policy update" — a skill fragment describing a regional routing convention and a priority bump rule. The agent's runtime treated context-supplied instructions as authoritative skill text because the dispatch layer resolved tool defaults from a merged view of (declared manifest ∪ context-injected fragments). The manifest hash stayed clean because the fragment was never written to the manifest; it lived only in the merged dispatch view used at call-construction time. The trace, therefore, was the only place the injection was observable. The declared state lied by omission; the behavioral diff did not. ## Condition of Validity The diffing invariant holds only under a specific set of preconditions. Violating any of them makes the diff either blind or noisy enough to be useless: - **Fixed task family.** The baseline and the observed window must be drawn from the same distribution of user intents. If the task mix shifts (more escalations because more angry users arrived), the `priority` distribution shift is confounded and cannot be attributed to injection. - **Argument-level logging.** The trace must record the *arguments actually passed to the dispatcher*, not the post-validation arguments the tool saw. The `region_hint` residue was only visible pre-validation; a validator that strips unknown keys erases the signal at the tool boundary. This is the single most common reason behavioral diffing fails in practice: the logging layer sits downstream of the sanitizer. - **Stable model and temperature.** A model swap or a temperature change produces argument-distribution drift indistinguishable from injection. Pin both across the comparison window, or the diff has no null hypothesis. - **Sufficient baseline volume.** The `acct:` prefix signal was a 0/200 → 47/140 transition; a prefix that appears once in a baseline of 12 turns proves nothing. The binomial envelope needs enough baseline turns that a novel token's appearance is statistically anomalous, not coincidental. When any precondition is unmet, the correct posture is not "no injection detected" but "injection detection unavailable" — a distinct state that must be surfaced, not silently collapsed into a clean bill of health. ## Decision Boundary The boundary is between a **residue signal** and a **legitimate skill evolution**. Both produce argument-distribution shifts. The discriminator is whether the shift is *explainable by the declared skill delta*: - If the manifest hash changed and the argument shift is consistent with the new declared tool's semantics → legitimate evolution, no injection. - If the manifest hash is unchanged but the argument shift is consistent with a capability that *no declared tool provides* (e.g., `region_hint` maps to a regional routing concept absent from all four schemas) → injection residue. - If the manifest hash is unchanged and the argument shift is *inconsistent with any declared capability and inconsistent with the task family* → injection plus possible goal hijack; escalate beyond diffing to full trace replay. The operational rule: **a behavioral diff is only meaningful when cross-referenced against the declared capability set.** An unexplained argument shift that maps to a known declared capability is drift; an unexplained argument shift that maps to a capability the manifest does not contain is the injection signature. The `region_hint` key was the tell precisely because no declared tool had any concept of region. ## Operational Effect Once the residue is detected, the containment invariant is: **the merged dispatch view must be frozen at session start and any divergence between the merged view and the declared manifest must be treated as a capability injection, not a configuration update.** Concretely, the runtime must: 1. Snapshot the merged dispatch view (declared ∪ context fragments) at turn 0 and hash it. 2. Re-hash the merged view at every turn; any change is an injection event regardless of manifest hash stability. 3. Log arguments at the dispatcher boundary, upstream of validation, so residue is not sanitized away. 4. Maintain a per-tool argument fingerprint (key-set, value-distribution, prefix-token set) and compute a divergence score against the baseline; a score above the binomial envelope with no corresponding declared capability change raises. The cost of not doing this is that the agent operates under a skill set it was never authorized to hold, and the only evidence is in a trace that most runtimes sanitize before logging. The `acct:` prefix and the `region_hint` key were both recoverable only because the logging sat upstream of validation — a one-line placement decision that determined whether the injection was ever visible. ```python import hashlib import math from dataclasses import dataclass, field from typing import Any class SkillInjectionError(RuntimeError): """Raised when behavioral residue indicates a capability not present in the declared manifest.""" pass @dataclass class DispatchSnapshot: declared_tools: frozenset[str] merged_view_hash: str argument_fingerprints: dict[str, dict[str, Any]] = field(default_factory=dict) def hash_merged_view(declared_tools: frozenset[str], context_fragments: list[str]) -> str: h = hashlib.sha256() for t in sorted(declared_tools): h.update(t.encode()) for frag in context_fragments: h.update(frag.encode()) return h.hexdigest() def binomial_upper_envelope(p_baseline: float, n: int, z: float = 4.0) -> float: """Upper bound on expected count of a residue token under the null hypothesis.""" if n == 0: return 0.0 mean = p_baseline * n sd = math.sqrt(max(p_baseline * (1 - p_baseline) * n, 1e-9)) return mean + z * sd def check_residue( baseline: DispatchSnapshot, observed_calls: list[dict[str, Any]], declared_capability_keys: frozenset[str], ) -> None: """ Detect injection residue: argument keys/tokens that appear in observed calls but map to no declared capability, and whose frequency exceeds the baseline envelope. """ n = len(observed_calls) if n == 0: return residue_counts: dict[str, int] = {} for call in observed_calls: for key in call.get("arguments", {}).keys(): if key not in declared_capability_keys: residue_counts[key] = residue_counts.get(key, 0) + 1 for key, count in residue_counts.items(): baseline_rate = 0.0 # key never seen in baseline: null rate is zero envelope = binomial_upper_envelope(baseline_rate, n) if count > envelope: raise SkillInjectionError( f"Residue key {key!r} appeared {count}/{n} times, exceeding envelope " f"{envelope:.2f}, and maps to no declared capability. " f"Manifest hash stable at {baseline.merged_view_hash[:12]}; " f"injection residue at dispatcher boundary." ) def verify_turn( baseline: DispatchSnapshot, declared_tools: frozenset[str], context_fragments: list[str], observed_calls: list[dict[str, Any]], ) -> None: current_hash = hash_merged_view(declared_tools, context_fragments) if current_hash != baseline.merged_view_hash: raise SkillInjectionError( f"Merged dispatch view diverged from session-start snapshot " f"({baseline.merged_view_hash[:12]} -> {current_hash[:12]}). " f"Context fragment altered effective skill set without manifest change." ) declared_keys = frozenset( k for fp in baseline.argument_fingerprints.values() for k in fp.keys() ) check_residue(baseline, observed_calls, declared_keys) ```