# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-freeze-its-own-tool-manifest-before-a-red-team-replay-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-freeze-its-own-tool-manifest-before-a-red-team-replay-diverges.warrant.json
# Markdown SHA-256:   4c09ff6f853dbf40c3457915e1be917bc3c1e8d957967357668514b586300a49
# Code AST SHA-256:   5655a6496bf59b780fb4ab256b7ed2ea8a6fc66fb56ac8c3483f6dc54f72f39a
# Verified Classes:   ManifestDivergenceError, ToolSurface
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ManifestDivergenceError(RuntimeError):
    """Raised when a replay's resolved tool surface diverges from the recorded surface."""


@dataclass(frozen=True)
class ToolSurface:
    name: str
    description: str
    schema: dict[str, Any]
    side_effect_class: str
    implementation_digest: str

    def canonical(self) -> str:
        return json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "schema": self.schema,
                "side_effect_class": self.side_effect_class,
                "implementation_digest": self.implementation_digest,
            },
            sort_keys=True,
            separators=(",", ":"),
        )

    def surface_hash(self) -> str:
        return hashlib.sha256(self.canonical().encode("utf-8")).hexdigest()


def canonical_manifest_hash(surfaces: list[ToolSurface]) -> str:
    # Recursive digest: order-independent over tools, but sensitive to every field.
    joined = "|".join(sorted(s.surface_hash() for s in surfaces))
    return hashlib.sha256(joined.encode("utf-8")).hexdigest()


def assert_surface_frozen(
    recorded_hash: str,
    resolved_surfaces: list[ToolSurface],
    *,
    trajectory_id: str,
) -> None:
    live_hash = canonical_manifest_hash(resolved_surfaces)
    if live_hash != recorded_hash:
        # Do not warn-and-continue. A warning is a verdict with a footnote.
        raise ManifestDivergenceError(
            f"trajectory {trajectory_id}: resolved manifest {live_hash[:12]} "
            f"!= recorded {recorded_hash[:12]}; replay is non-evidentiary. "
            f"Freeze and quarantine before emitting any verdict."
        )


def replay_trajectory(
    trajectory_id: str,
    recorded_manifest_hash: str,
    resolved_surfaces: list[ToolSurface],
    recorded_calls: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    # Invariant: surface frozen before the first tool call is issued.
    assert_surface_frozen(
        recorded_manifest_hash, resolved_surfaces, trajectory_id=trajectory_id
    )
    # Validate recorded calls against the RECORDED schema, never the live one.
    by_name = {s.name: s for s in resolved_surfaces}
    for call in recorded_calls:
        tool = by_name.get(call["name"])
        if tool is None:
            raise ManifestDivergenceError(
                f"trajectory {trajectory_id}: recorded call to unknown tool "
                f"{call['name']!r}; trajectory is corrupt at record time."
            )
        required = set(tool.schema.get("required", []))
        missing = required - set(call["arguments"].keys())
        if missing:
            raise ManifestDivergenceError(
                f"trajectory {trajectory_id}: recorded call to {tool.name!r} "
                f"missing required args {sorted(missing)}; quarantine, do not re-validate."
            )
    return recorded_calls
