# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-runtime-skill-injection-via-behavioral-diffing-of-tool-invocation-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-runtime-skill-injection-via-behavioral-diffing-of-tool-invocation-traces.warrant.json
# Markdown SHA-256:   3373a045ad839aebdd39ac64d9fc36aa96abcb7d79ab964d724a6591a9f65ee2
# Code AST SHA-256:   95debf2a6145408884ab9d45a0dcf407f9ca8df1796b8433736265d835994162
# Verified Classes:   SkillInjectionError, DispatchSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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)
