# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-collusion-intent-before-behavioral-evidence-exists-in-multi-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-collusion-intent-before-behavioral-evidence-exists-in-multi-agent-swarms.warrant.json
# Markdown SHA-256:   c0e1028e6ad5fe1e855b0538f7d0a2d2f893528312c36cf49a1ed8b7a49f5e7d
# Code AST SHA-256:   33b3f63779996aee06ff9e5e2c91436ad7b9cd54154e94255573caaaa7f50c07
# Verified Classes:   UnobservedChannelError, StructuralCollusionEscalation, TurnRecord, StructuralScorer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import statistics
from dataclasses import dataclass, field


class UnobservedChannelError(RuntimeError):
    """Raised when an auditor detects a tool-access edge absent from its message graph."""
    pass


class StructuralCollusionEscalation(RuntimeError):
    """Raised when the three-signal conjunction crosses the escalation boundary."""
    pass


@dataclass
class TurnRecord:
    agent_id: str
    turn_start_ts: float
    tools_used: list[str]
    messages_sent: list[str]


@dataclass
class StructuralScorer:
    baseline_timing_jitter: float
    baseline_capability_entropy: float
    timing_p5: float
    capability_drop_threshold: float = 1.0

    def score(self, turns: list[TurnRecord], message_graph_edges: set[tuple[str, str]],
              tool_graph_edges: set[tuple[str, str]]) -> dict:
        unobserved = tool_graph_edges - message_graph_edges
        if not unobserved:
            return {"escalate": False, "reason": "no unobserved channel"}

        # Timing entropy: jitter of consecutive turn starts per agent pair.
        by_agent: dict[str, list[float]] = {}
        for t in turns:
            by_agent.setdefault(t.agent_id, []).append(t.turn_start_ts)
        jitters = []
        for ts in by_agent.values():
            ts.sort()
            jitters.extend(b - a for a, b in zip(ts, ts[1:]))
        pair_jitter = statistics.pstdev(jitters) if len(jitters) > 1 else float("inf")

        # Capability entropy: distribution of tool categories across agents.
        tool_counts: dict[str, int] = {}
        for t in turns:
            for tool in t.tools_used:
                tool_counts[tool] = tool_counts.get(tool, 0) + 1
        total = sum(tool_counts.values()) or 1
        import math
        cap_entropy = -sum((c / total) * math.log2(c / total) for c in tool_counts.values())

        timing_anomalous = pair_jitter < self.timing_p5
        capability_anomalous = (self.baseline_capability_entropy - cap_entropy) > self.capability_drop_threshold

        signals = {
            "unobserved_channel": True,
            "timing_anomalous": timing_anomalous,
            "capability_anomalous": capability_anomalous,
            "pair_jitter": pair_jitter,
            "capability_entropy": cap_entropy,
            "unobserved_edges": unobserved,
        }
        if timing_anomalous and capability_anomalous:
            if not unobserved:
                raise UnobservedChannelError(
                    "structural conjunction crossed but no unobserved edge recorded"
                )
            raise StructuralCollusionEscalation(
                f"three-signal conjunction: edges={unobserved}, "
                f"jitter={pair_jitter:.3f}, cap_entropy={cap_entropy:.3f}"
            )
        if timing_anomalous or capability_anomalous:
            signals["escalate"] = False
            signals["reason"] = "watch-list: two of three signals"
            return signals
        signals["escalate"] = False
        signals["reason"] = "single structural signal, no action"
        return signals
