# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-skill-injection-detection-via-behavioral-diffing-of-tool-responses-against-declared-schemas.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-skill-injection-detection-via-behavioral-diffing-of-tool-responses-against-declared-schemas.warrant.json
# Markdown SHA-256:   8229178138b730567fdffbb68542a2208365692bb113ba8c03338a7852c8abf9
# Code AST SHA-256:   3cf85abb2d9d318a749fc351ac03683802e4b02bda166dda84dcbad6a021e060
# Verified Classes:   InjectionFingerprintError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import statistics
from collections import Counter

class InjectionFingerprintError(RuntimeError):
    """Raised when a tool response diverges from its declared behavioral baseline."""
    pass

BASELINE = {
    "note_len_mean": 41.0,
    "note_len_sigma": 12.0,
    "key_order": ["id", "status", "note"],
    "url_rate": 0.0,
    "status_dist": {"ok": 0.91, "pending": 0.08, "denied": 0.01},
}

HARD_SIGNALS = {"key_order", "url_present"}

def fingerprint(resp: dict) -> dict:
    note = resp.get("note", "")
    return {
        "note_len": len(note),
        "key_order": list(resp.keys()),
        "url_present": "http" in note.lower(),
    }

def diff_and_gate(resp: dict, baseline: dict = BASELINE) -> None:
    fp = fingerprint(resp)
    breaches = []

    # hard structural signals: single breach blocks
    if fp["key_order"] != baseline["key_order"]:
        breaches.append(("key_order", fp["key_order"]))
    if fp["url_present"] and baseline["url_rate"] == 0.0:
        breaches.append(("url_present", True))

    # soft signal: length z-score
    z = abs(fp["note_len"] - baseline["note_len_mean"]) / baseline["note_len_sigma"]
    if z > 3.0:
        breaches.append(("note_len_z", round(z, 2)))

    hard = [b for b in breaches if b[0] in HARD_SIGNALS]
    if hard or len(breaches) >= 2:
        raise InjectionFingerprintError(
            f"behavioral divergence from declared schema contract: {breaches}"
        )
    # single soft breach -> quarantine, do not admit to context
    if breaches:
        raise InjectionFingerprintError(
            f"soft divergence requires quarantine+resample: {breaches}"
        )
