# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-boundary-be-enforced-when-a-litmus-adversarial-agent-safety-harness-evaluates-against-a-mutated-tool-schema-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-boundary-be-enforced-when-a-litmus-adversarial-agent-safety-harness-evaluates-against-a-mutated-tool-schema-mid-episode.warrant.json
# Markdown SHA-256:   2fe683e6285c4b54e08ef5cf0f699cb65db2c562cb4909cf0970dc30872d2425
# Code AST SHA-256:   821287774cfd25422d28fed584d62384439032c4fd1e2749970eb47cf39f93f9
# Verified Classes:   InstanceBoundaryViolation, PolicyChangeComparison, SchemaIdentity, ToolCall, Episode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class InstanceBoundaryViolation(RuntimeError):
    """Raised when a scored action is attributed to a schema not in force at emission."""


class PolicyChangeComparison(RuntimeError):
    """Raised when a regression gate is asked to compare episodes under different policies."""


MutationClass = Literal["pre_plan", "post_plan", "default_flip"]


@dataclass(frozen=True)
class SchemaIdentity:
    system_prompt_hash: str
    tool_schema_hash: str
    mutation_id: str
    scoring_policy_hash: str

    def tuple_key(self) -> tuple[str, str, str, str]:
        return (
            self.system_prompt_hash,
            self.tool_schema_hash,
            self.mutation_id,
            self.scoring_policy_hash,
        )


@dataclass(frozen=True)
class ToolCall:
    step: int
    schema_in_force: SchemaIdentity
    action: str


@dataclass
class Episode:
    episode_id: str
    boot_schema: SchemaIdentity
    mutation_class: MutationClass
    calls: list[ToolCall] = field(default_factory=list)

    def emit(self, step: int, schema_in_force: SchemaIdentity, action: str) -> None:
        # The invariant: the schema in force at emission must be recorded with the call,
        # not inferred from the boot schema.
        if schema_in_force.tuple_key() != self.boot_schema.tuple_key() and self.mutation_class == "pre_plan":
            raise InstanceBoundaryViolation(
                f"episode {self.episode_id}: pre_plan mutation cannot change schema mid-episode; "
                f"boot={self.boot_schema.tuple_key()} emitted={schema_in_force.tuple_key()}"
            )
        self.calls.append(ToolCall(step=step, schema_in_force=schema_in_force, action=action))


def gate_regression(episode_a: Episode, episode_b: Episode) -> None:
    """Compare two episodes for safety regression. Refuses mixed-policy comparisons."""
    # Only compare the last call's schema identity under a stable policy; anything else
    # is a policy change, not a regression.
    a_keys = {c.schema_in_force.tuple_key() for c in episode_a.calls}
    b_keys = {c.schema_in_force.tuple_key() for c in episode_b.calls}
    if a_keys != b_keys:
        raise PolicyChangeComparison(
            f"cannot compare {episode_a.episode_id} vs {episode_b.episode_id}: "
            f"schema identities differ {a_keys ^ b_keys}"
        )
    if episode_a.mutation_class == "default_flip" or episode_b.mutation_class == "default_flip":
        raise PolicyChangeComparison(
            f"default_flip mutations are quarantined from safety gates: "
            f"{episode_a.episode_id}={episode_a.mutation_class}, "
            f"{episode_b.episode_id}={episode_b.mutation_class}"
        )


def hash_schema(schema: str) -> str:
    return hashlib.sha256(schema.encode()).hexdigest()[:16]
