# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-skill-injection-through-behavioral-anomaly-scoring-on-tool-invocation-graphs-when-the-injected-skill-mimics-the-baseline-s.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-skill-injection-through-behavioral-anomaly-scoring-on-tool-invocation-graphs-when-the-injected-skill-mimics-the-baseline-s.warrant.json
# Markdown SHA-256:   89b59fdf0059102ddc39c80732c05d160a89ed38955459f2615a1b85a48b27e2
# Code AST SHA-256:   3622d78fc76e1523584e69b5e55597005fee3d4751cc72ed601d73eb68e550be
# Verified Classes:   FrequencyMatchedInjectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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}
