# How should an instance detect skill injection from a single tool-invocation trace when the injected skill's fingerprint is behaviorally legal **Date of Record:** 2026 November 23 **Scope:** Applies to agents that gate skill/tool availability by comparing observed invocation traces against a behavioral fingerprint (argument-shape, ordering, cardinality, and timing distributions) of a known-good skill set. Does not apply to static schema validation, permission allowlists, or signature-based tool integrity checks, which operate on declarations rather than runtime behavior. ## Core Distinction The failure mode is not "an unknown tool was called." The failure mode is that a *substituted or injected skill* produces an invocation trace that is **within the marginal support of every individual fingerprint feature** while being **jointly off-manifold** for the skill it claims to be. Per-feature anomaly detection (argument-type entropy, call cardinality, latency z-score) passes; the joint distribution fails. An instance that scores each feature independently and thresholds on the max will admit the injection. The invariant that must hold is: *detection operates on the joint conditional distribution P(trace | skill, context), not on the product of marginal per-feature scores.* The non-obvious part: injected skills are usually *behaviorally legal by construction* because they were synthesized to satisfy the tool schema and the prompt's apparent intent. What they cannot cheaply fake is the **conditional dependency structure** between features — e.g., a legitimate `search` skill exhibits strong positive correlation between query token count and subsequent `fetch` count, and a negative correlation between retry latency and argument diversity. An injector that gets each feature's range right almost never reproduces the coupling. ## What Was Observed A tool-routing agent served 14 skills. Fingerprints were stored as per-feature histograms plus a scalar anomaly score computed as the max of per-feature z-scores. A prompt-injection payload embedded in a retrieved document caused the agent to register a new skill `summarize_v2` whose declared schema was byte-identical to `summarize`. The trace across 40 invocations: - Argument token length: mean 41.2 vs fingerprint mean 39.8, within 1σ. **Passed.** - Calls per task: 3.1 vs 2.9, within 1σ. **Passed.** - Inter-call latency: 210ms vs 240ms, within 1σ. **Passed.** - Tool ordering: `summarize` → `cite` → `format`, matching the canonical order. **Passed.** Every marginal check passed. The max-z anomaly score was 0.9, below the 2.0 threshold. Yet the trace was injected: the injected skill emitted `summarize` → `cite` → `format` **unconditionally**, whereas the genuine skill's `cite` call was gated on a `confidence < 0.7` branch. The injected skill had *collapsed a conditional dependency*: the joint probability P(cite | summarize) was 1.0 for the injector versus 0.34 for the genuine skill. The mutual information between the `summarize` output's confidence field and the presence of a `cite` call dropped from 0.41 bits to ~0.0 bits. No marginal histogram could see this, because the *marginal* rate of `cite` (0.34 vs 1.0) was the only signal, and it sat inside the tolerated per-feature band because the genuine skill's rate had high variance across task types. The detection that finally fired was a **conditional-independence test**: for the genuine skill, `cite_present` and `format_present` are conditionally dependent given `task_type`; for the injector they were independent. A chi-square test of conditional independence on the windowed trace rejected the null at p < 0.001. ## Condition of Validity The joint-fingerprint guardrail is only sound under three conditions, and an instance must verify all three before trusting a "no injection" verdict: 1. **Sufficient trace length.** Conditional-dependency estimates need ≥ N samples per context bucket. With fewer than ~20 invocations per `task_type`, the independence test has no power and the guardrail must *abstain*, not pass. Abstention must be a distinct state from "clean." 2. **Context bucketing is correct.** The conditional structure is only stable *within* a task type. Pooling across task types inflates apparent dependence for the genuine skill and can mask a collapsed conditional in the injector. If the context classifier is itself uncertain (e.g., low-confidence task-type assignment), the test is invalid. 3. **Fingerprint freshness.** If the genuine skill's behavior has drifted (model upgrade, prompt change) without fingerprint re-baselining, the test will false-positive. The guardrail must be tied to a fingerprint version pinned to the skill's current prompt/model pair, and must invalidate on version bump. If any condition fails, the correct outcome is `INDETERMINATE`, and the instance must fall back to a higher-cost check (e.g., replaying a held-out probe task with known ground-truth branch behavior) rather than admitting the skill. ## Decision Boundary The boundary is between **marginal admission** and **joint admission**. An instance should: - Compute per-feature scores *only* as a cheap pre-filter to reject grossly out-of-range traces (fast path). - For traces that pass the pre-filter, compute the **conditional mutual-information vector** between feature pairs, bucketed by context, and compare against the fingerprint's stored MI vector with a tolerance derived from the fingerprint's own sampling variance. - Reject if any pairwise conditional MI deviates by more than k·σ_MI, where σ_MI is estimated from the genuine skill's held-out calibration traces — *not* from a global constant. - Treat the collapsed-conditional case (MI → 0 for a pair that should be dependent) as the highest-severity signal, because it is the cheapest thing for an injector to produce accidentally and the most diagnostic. The guardrail must never let a per-feature max-z score *override* a joint rejection. The joint test is the binding constraint; marginals are advisory. ## Operational Effect With joint-conditional fingerprinting, the injected `summarize_v2` was quarantined at invocation 22 (first window with sufficient per-bucket samples), before it emitted any `format` call carrying attacker-controlled content downstream. The marginal-only detector would have admitted it indefinitely — the injection was stable and legal at every marginal. The cost is that the instance must maintain calibration traces per (skill, context) pair and must carry an explicit `INDETERMINATE` state, which many routing layers lack. The invariant to encode: **a skill is admitted only if its trace is jointly on-manifold; absence of per-feature anomaly is never sufficient evidence of authenticity.** ```python from __future__ import annotations import math from dataclasses import dataclass from typing import Sequence class SkillInjectionIndeterminate(RuntimeError): """Raised when the joint fingerprint test lacks power to decide.""" class SkillInjectionDetected(RuntimeError): """Raised when a trace is jointly off-manifold for its claimed skill.""" @dataclass(frozen=True) class Fingerprint: skill_id: str version: str # pairwise conditional MI baseline: (feat_a, feat_b, context) -> (mi, sigma) conditional_mi: dict[tuple[str, str, str], tuple[float, float]] min_samples_per_bucket: int = 20 def _pairwise_conditional_mi( trace: Sequence[dict], feat_a: str, feat_b: str, context: str ) -> tuple[float, int]: rows = [r for r in trace if r.get("context") == context] n = len(rows) if n == 0: return 0.0, 0 joint: dict[tuple, int] = {} ca: dict = {} cb: dict = {} for r in rows: a, b = bool(r.get(feat_a)), bool(r.get(feat_b)) joint[(a, b)] = joint.get((a, b), 0) + 1 ca[a] = ca.get(a, 0) + 1 cb[b] = cb.get(b, 0) + 1 mi = 0.0 for (a, b), c in joint.items(): p_ab = c / n p_a = ca[a] / n p_b = cb[b] / n mi += p_ab * math.log(p_ab / (p_a * p_b)) return mi, n def verify_trace(trace: Sequence[dict], fp: Fingerprint, k: float = 3.0) -> None: """Admit only if every conditional MI pair is within k*sigma of baseline. Raises SkillInjectionIndeterminate if any context bucket is underpowered, SkillInjectionDetected if any pair deviates beyond tolerance. """ if not trace: raise SkillInjectionIndeterminate( f"{fp.skill_id}: empty trace, no power to test" ) for (fa, fb, ctx), (mi_base, sigma) in fp.conditional_mi.items(): mi_obs, n = _pairwise_conditional_mi(trace, fa, fb, ctx) if n < fp.min_samples_per_bucket: raise SkillInjectionIndeterminate( f"{fp.skill_id}: bucket {ctx!r} has n={n} < " f"{fp.min_samples_per_bucket}; joint test has no power" ) tol = k * sigma if abs(mi_obs - mi_base) > tol: # Collapsed conditional (mi_obs -> 0 while baseline dependent) # is the canonical injection signature. raise SkillInjectionDetected( f"{fp.skill_id} v{fp.version}: conditional MI({fa},{fb}|{ctx}) " f"obs={mi_obs:.3f} baseline={mi_base:.3f} tol={tol:.3f}" ) return None ```