# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-counterfactual-replay-from-silently-diverging-in-agentic-protocol-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-counterfactual-replay-from-silently-diverging-in-agentic-protocol-sessions.warrant.json
# Markdown SHA-256:   4cf59a38aacf23316277dc093cccb5c559a0062696b49bd3643af9f3c06f1641
# Code AST SHA-256:   b697043ddb526df64a13b3c50fc1b3b98580b80048bcc698f191c40409962e59
# Verified Classes:   ReplayInvariantViolation, ReplayManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ReplayInvariantViolation(RuntimeError):
    """Raised when a counterfactual replay would silently diverge from the recorded session."""
    pass


@dataclass(frozen=True)
class ReplayManifest:
    system_prompt_hash: str
    retrieval_snapshot_hash: str
    tool_schema_hash: str
    model_artifact_hash: str
    sampling_seed: int
    idempotency_scope: str


def assert_replayable(
    manifest: ReplayManifest | None,
    current_model_hash: str,
    mutation_delta_tokens: int,
    side_effecting_tools: list[str],
    isolation_harness: bool,
) -> None:
    if manifest is None:
        raise ReplayInvariantViolation(
            "session has no replay manifest; counterfactual audit is ineligible"
        )
    if manifest.model_artifact_hash != current_model_hash:
        raise ReplayInvariantViolation(
            f"model artifact drift: recorded {manifest.model_artifact_hash}, "
            f"current {current_model_hash}; replay would attribute new-model behavior "
            f"to the intervention"
        )
    if mutation_delta_tokens != 0:
        raise ReplayInvariantViolation(
            f"mutation changes token count by {mutation_delta_tokens}; hidden context "
            f"(eviction policy, retrieval budget) is perturbed, so the counterfactual "
            f"is not a valid intervention — synthesize and label as simulation instead"
        )
    if side_effecting_tools and not isolation_harness:
        raise ReplayInvariantViolation(
            f"side-effecting tools {side_effecting_tools} present without an isolation "
            f"harness; replay would create duplicate external effects"
        )


def compute_manifest_hash(m: ReplayManifest) -> str:
    payload = "|".join([
        m.system_prompt_hash,
        m.retrieval_snapshot_hash,
        m.tool_schema_hash,
        m.model_artifact_hash,
        str(m.sampling_seed),
        m.idempotency_scope,
    ])
    return hashlib.sha256(payload.encode()).hexdigest()
