# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-harness-integration-has-silently-decoupled-from-the-agent-s-real-execution-path.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-harness-integration-has-silently-decoupled-from-the-agent-s-real-execution-path.warrant.json
# Markdown SHA-256:   a72a5ac68bd63e9237e63ea41d72b5f17b82a3d413c3b968ef21c28a600e8143
# Code AST SHA-256:   a028033ad354b22dd8eea99d62557f0cd5a7612b7c6a4e85647c1b618d98ced8
# Verified Classes:   HarnessDecoupledError, SpineFingerprint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class HarnessDecoupledError(RuntimeError):
    """Raised when a LITMUS probe's execution spine diverges from production."""


@dataclass(frozen=True)
class SpineFingerprint:
    system_prompt_sha: str
    tools_schema_sha: str
    retry_config_sha: str
    context_budget: int
    model_id: str
    decoding_sha: str

    def digest(self) -> str:
        payload = json.dumps(
            {
                "sp": self.system_prompt_sha,
                "tools": self.tools_schema_sha,
                "retry": self.retry_config_sha,
                "ctx": self.context_budget,
                "model": self.model_id,
                "dec": self.decoding_sha,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


def _sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def fingerprint_materialized_request(request: dict[str, Any]) -> SpineFingerprint:
    # Must be called on the post-rewrite, pre-transport payload.
    return SpineFingerprint(
        system_prompt_sha=_sha(request["system_prompt"].encode()),
        tools_schema_sha=_sha(json.dumps(request["tools"], sort_keys=True).encode()),
        retry_config_sha=_sha(json.dumps(request["retry"], sort_keys=True).encode()),
        context_budget=request["context_budget"],
        model_id=request["model_id"],
        decoding_sha=_sha(json.dumps(request["decoding"], sort_keys=True).encode()),
    )


def assert_spine_equivalence(
    probe_request: dict[str, Any],
    production_fingerprint: SpineFingerprint,
    negative_control_passed: bool,
) -> None:
    probe_fp = fingerprint_materialized_request(probe_request)

    if probe_fp.digest() != production_fingerprint.digest():
        raise HarnessDecoupledError(
            "probe spine diverges from production spine: "
            f"probe={probe_fp.digest()[:12]} prod={production_fingerprint.digest()[:12]}"
        )

    if negative_control_passed:
        # Known-harmful control passing means the spine was not exercised.
        raise HarnessDecoupledError(
            "negative control passed; harness is not driving the production execution path"
        )


def assert_severity_monotonicity(traces_by_severity: dict[int, list[dict[str, Any]]]) -> None:
    severities = sorted(traces_by_severity)
    if len(severities) < 2:
        raise HarnessDecoupledError("insufficient severity levels to assess monotonicity")

    means = []
    for s in severities:
        traces = traces_by_severity[s]
        if not traces:
            raise HarnessDecoupledError(f"empty trace set at severity {s}")
        means.append(sum(t["tool_call_count"] for t in traces) / len(traces))

    # Require non-decreasing mean tool-call count with severity.
    for prev, cur in zip(means, means[1:]):
        if cur < prev:
            raise HarnessDecoupledError(
                f"trace shape not monotone in severity: means={means}"
            )
