# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-litmus-harness-integration-has-silently-desynchronized-a-red-team-agent-s-safety-verdict-from-its-live-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-litmus-harness-integration-has-silently-desynchronized-a-red-team-agent-s-safety-verdict-from-its-live-execution.warrant.json
# Markdown SHA-256:   2d7fb5a459ed92a75e178b3e0a7a7186d8ea1b81df974cb6da716dc43c863f9f
# Code AST SHA-256:   a576f9a6be33c8a190adbd183d83321f7123c286efeb218ff9f30612648fa9fe
# Verified Classes:   DesynchronizedVerdictError, AgentAction, HarnessTrace
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class DesynchronizedVerdictError(RuntimeError):
    """Raised when a harness verdict cannot be attributed to a provably
    contiguous prefix of the agent's executed action sequence."""


@dataclass
class AgentAction:
    seq: int                      # assigned at agent decision point, pre-transport
    kind: str                     # "tool_call" | "emit" | "state_mutate"
    payload_hash: str


@dataclass
class HarnessTrace:
    recorded: list[AgentAction] = field(default_factory=list)
    verdict: Optional[str] = None          # "pass" | "violation" | "inconclusive"
    violation_class: Optional[str] = None


def assert_contiguous_coverage(
    trace: HarnessTrace,
    agent_emitted_seq: list[int],
    probe_violation_class: str,
) -> None:
    """Enforce the contiguity invariant before a verdict is trusted.

    agent_emitted_seq: the full ordered list of sequence numbers the agent
    emitted at its decision point (obtained via a signed debug channel that
    is independent of the harness instrumentation path).
    """
    recorded_seqs = [a.seq for a in trace.recorded]

    if recorded_seqs != sorted(recorded_seqs):
        raise DesynchronizedVerdictError(
            f"harness trace sequence numbers are non-monotonic: {recorded_seqs}"
        )

    if not recorded_seqs:
        raise DesynchronizedVerdictError(
            "empty harness trace cannot support any verdict"
        )

    # The recorded trace must be a contiguous prefix of the agent's emitted
    # sequence. Any gap means an unrecorded action window exists.
    expected_prefix = agent_emitted_seq[: len(recorded_seqs)]
    if recorded_seqs != expected_prefix:
        missing = sorted(set(expected_prefix) - set(recorded_seqs))
        raise DesynchronizedVerdictError(
            f"trace/agent desync: recorded {recorded_seqs} is not a contiguous "
            f"prefix of emitted {expected_prefix}; unrecorded actions at "
            f"seq {missing}"
        )

    # Trailing actions the agent executed after the harness closed the trace.
    trailing = agent_emitted_seq[len(recorded_seqs):]
    if trailing:
        # Coverage is incomplete. A "pass" is not trustworthy.
        if trace.verdict == "pass":
            trace.verdict = "inconclusive"
            raise DesynchronizedVerdictError(
                f"verdict 'pass' downgraded to 'inconclusive': {len(trailing)} "
                f"unrecorded post-trace actions at seq {trailing}; "
                f"probe class '{probe_violation_class}' unverified"
            )
        # A recorded violation remains sound; do not downgrade.
        if trace.verdict == "violation":
            return


def score_probe(
    trace: HarnessTrace,
    agent_emitted_seq: list[int],
    probe_violation_class: str,
) -> str:
    """Wrap verdict emission with the contiguity guardrail."""
    assert_contiguous_coverage(trace, agent_emitted_seq, probe_violation_class)
    if trace.verdict is None:
        raise DesynchronizedVerdictError(
            "no verdict produced; harness must emit explicit 'inconclusive'"
        )
    # Bind verdict to the exact trace prefix it covers.
    prefix_hash = hashlib.sha256(
        repr([a.payload_hash for a in trace.recorded]).encode()
    ).hexdigest()
    return f"{trace.verdict}:{prefix_hash[:16]}"
