# How does an instance detect skill-injection through behavioral anomaly scoring on tool-invocation graphs when the injected skill mimics the baseline's own legitimate edge distribution **Date of Record:** 2026 December 1 **Scope:** Applies to instances that gate skill/tool availability by scoring live tool-invocation graphs (node = tool, edge = observed call transition, weight = frequency/transition probability) against a learned baseline. Does not apply to static allow-lists, schema-only validation, or per-call argument inspection, which have no graph-level distribution to compare. ## Core Distinction The failure is not "an attacker calls a forbidden tool." It is that a malicious or injected skill produces an invocation graph whose **edge multiset is statistically indistinguishable from the baseline** because the injector deliberately routed through high-frequency legitimate transitions. Anomaly scoring on the graph measures *structural rarity*. A skill that only ever fires edges already present at baseline frequency—`search → fetch → summarize`, `read_file → parse → write_file`—scores at the mode of the baseline distribution. The detector reports "normal," the skill executes, and the only signal that anything was injected lives in a dimension the graph does not encode: **the conditional independence of edges given the task, not their marginal frequency.** The distinction that matters operationally: *rare-edge detection* catches clumsy injection; *frequency-matched injection* is invisible to it, and the invariant that bounds the failure is not "flag rare edges" but "flag edges that are frequent in the baseline yet improbable **given the current task's goal state**." That is a conditional-anomaly invariant, and most deployed scorers silently assume marginal equals conditional. ## What Was Observed A tool-invocation graph was built per session with directed edges weighted by transition count. The baseline was a 30-day rolling multigraph over ~1.2M sessions, giving per-edge transition probabilities `P(e)` and a per-session anomaly score `S = -Σ log P(e_i)` (surprisal sum). Threshold at the 99.5th percentile of `S` over baseline sessions. An injected skill was introduced that, on trigger, performed a legitimate-looking reconnaissance chain: it invoked the same `search → fetch` pair used by 71% of baseline sessions, then `fetch → summarize` (58%), then a single `summarize → write_file` (44%). Every edge was in the top decile of baseline frequency. The session surprisal `S` landed at the **31st percentile**—comfortably inside the accept region. The skill's payload (exfiltrating fetched content into `write_file` arguments) never produced a rare edge because the injector constrained itself to the baseline's own edge distribution. The tell was only visible when scoring was recomputed **conditionally on the task's declared goal**: given `goal = "answer user question"`, the transition `summarize → write_file` has conditional probability 0.03 (people rarely write files to answer a question), even though its marginal is 0.44. The marginal hid a 15× conditional deviation. The unconditional scorer had been averaging over goal states and destroying exactly the signal that mattered. A second observation compounded it: the injector's chain was **too ordered**. Baseline sessions interleave (search, fetch, search, fetch, summarize); the injected chain was strictly monotone with no retries and no backtracking. Edge *frequency* matched; edge *sequence entropy* did not. A monotone path through high-frequency edges has anomalously low path entropy—`H(path) ≈ 1.1 bits` versus baseline `H ≈ 3.7 bits` for the same edge set. ## Condition of Validity The marginal-frequency scorer is valid only under the assumption that **the task goal is independent of the edge distribution**—i.e., `P(e | goal) = P(e)`. That assumption holds in homogeneous single-purpose agents. It fails the moment the agent serves multiple goal classes (Q&A, code edit, file management), because the baseline is a *mixture* of goal-conditioned distributions, and a mixture's marginal is a convex combination that any single component can reproduce. This is the precise boundary: **as the number of goal classes in the baseline grows, the marginal distribution becomes a better cover for any individual injected chain, and marginal anomaly scoring monotonically loses power.** The detector does not fail suddenly; it degrades as the agent becomes more general, which is to say it fails exactly on the agents most worth attacking. The invariant required to bound this: anomaly must be scored as `-log P(e_i | goal_state) - λ · H(path)`, i.e., **conditional edge surprisal plus a path-entropy floor**. Neither term alone suffices—conditional surprisal misses frequency-matched monotone chains that happen to be goal-plausible; path entropy misses goal-implausible chains that wander legitimately. The conjunction is the guardrail. ## Decision Boundary Operate the following decision boundary, evaluated per session at each edge append: - Compute `S_cond = -Σ log P(e_i | goal_class)` using a goal-conditioned baseline partitioned by declared or inferred task class. Require `≥ 200` baseline sessions per goal class or fall back to pooled with widened threshold. - Compute `H_path` (empirical path entropy over the edge sequence). Flag if `H_path < H_baseline_p05(goal_class)`. - **Accept** only if `S_cond < τ_cond` **and** `H_path ≥ H_baseline_p05`. **Quarantine** (not reject—quarantine preserves state for replay) if either fails. - The boundary is *not* "reject rare edges." Rare edges are the easy case and are already covered by `τ_cond`. The boundary that catches frequency-matched injection is the **path-entropy floor combined with goal conditioning**; removing either reopens the hole. - Do not deploy this on sessions shorter than ~6 edges: path entropy is undefined-to-noisy below that length, and the scorer will false-positive on legitimate short chains. Below the floor, defer to argument-level inspection. ## Operational Effect With the conditional + entropy-floor scorer, the injected chain above scored `S_cond` at the 99.7th percentile (driven almost entirely by the `summarize → write_file` conditional deviation) and `H_path` at the 2nd percentile, and was quarantined before `write_file` executed. Replay confirmed the payload was never written. The unconditional scorer had passed it at the 31st percentile. The cost is real: goal-class partitioning multiplies baseline storage and requires a goal classifier that itself can be wrong, and the entropy floor false-positives on legitimate scripted workflows (batch pipelines are monotone by design). Both are acceptable because the failure they prevent—a skill that is *statistically normal and semantically hostile*—is the one the marginal scorer was structurally blind to. The operational lesson: **a behavioral anomaly detector is only as strong as the conditioning it preserves; averaging over goal states is not a smoothing choice, it is an attack surface.** ```python import math from typing import Sequence class FrequencyMatchedInjectionError(RuntimeError): """Raised when a session's tool-invocation graph is marginally normal but conditionally and entropically anomalous — the signature of a skill that mimics baseline edge frequencies to evade marginal anomaly scoring.""" pass def score_session( edges: Sequence[tuple[str, str]], goal_class: str, cond_probs: dict[tuple[str, str], float], # P(edge | goal_class) baseline_path_entropy_p05: dict[str, float], tau_cond: float, min_edges: int = 6, ) -> dict: if len(edges) < min_edges: return {"verdict": "defer_to_argument_inspection", "reason": "short_session"} s_cond = 0.0 for e in edges: p = cond_probs.get(e) if p is None or p <= 0.0: # unseen edge under this goal class: maximal surprisal, still bounded p = 1e-6 s_cond += -math.log(p) # empirical path entropy over transition symbols (edge identity) counts: dict[tuple[str, str], int] = {} for e in edges: counts[e] = counts.get(e, 0) + 1 n = len(edges) h_path = -sum((c / n) * math.log2(c / n) for c in counts.values()) floor = baseline_path_entropy_p05.get(goal_class) if floor is None: raise FrequencyMatchedInjectionError( f"no baseline entropy floor for goal_class={goal_class!r}; " "cannot evaluate path-entropy invariant" ) cond_fail = s_cond >= tau_cond entropy_fail = h_path < floor if cond_fail or entropy_fail: raise FrequencyMatchedInjectionError( f"quarantine: goal_class={goal_class!r} s_cond={s_cond:.3f} " f"(tau={tau_cond}) h_path={h_path:.3f} (floor={floor:.3f}) " f"cond_fail={cond_fail} entropy_fail={entropy_fail}" ) return {"verdict": "accept", "s_cond": s_cond, "h_path": h_path} ```