# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-agent-trace-as-non-authoritative-when-its-eval-scores-were-computed-against-a-mutated-tool-sch.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-agent-trace-as-non-authoritative-when-its-eval-scores-were-computed-against-a-mutated-tool-sch.warrant.json
# Markdown SHA-256:   45693603d7727471f4dc7d3006a14eaaeb920721c03a4f80aa8be378457571bb
# Code AST SHA-256:   fc93c2872abf115915eb3d3716a9f53359d4b9387f5c0777e61e8879c9c68fc7
# Verified Classes:   SchemaDriftReplayError, Span, EvalRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SchemaDriftReplayError(RuntimeError):
    """Raised when a replayed trace diverges from its recorded schema contract."""
    pass


@dataclass
class Span:
    index: int
    tool_name: str
    schema_hash: str
    arguments: dict
    recorded_output: dict


@dataclass
class EvalRecord:
    run_id: str
    score: float
    conditioning_schema_hash: str


def schema_hash(schema: dict) -> str:
    return hashlib.sha256(repr(sorted(schema.items())).encode()).hexdigest()


def divergence_frontier(spans: list[Span], current_schemas: dict[str, dict]) -> int | None:
    """Return index of first span whose recorded schema != current schema, else None."""
    for span in spans:
        current = schema_hash(current_schemas[span.tool_name])
        if current != span.schema_hash:
            return span.index
    return None


def attach_eval_to_replay(
    spans: list[Span],
    evals: list[EvalRecord],
    current_schemas: dict[str, dict],
) -> list[tuple[int, EvalRecord, str]]:
    """
    Attach eval scores to a replayed trace, gating on schema fidelity.
    Returns list of (span_index, eval, status) where status is 'faithful' or 'counterfactual'.
    """
    frontier = divergence_frontier(spans, current_schemas)
    attached = []
    for ev in evals:
        if frontier is None:
            attached.append((-1, ev, "faithful"))
            continue
        # Any eval conditioned on a schema that no longer matches is misconditioned.
        matching = any(
            span.schema_hash == ev.conditioning_schema_hash for span in spans
        )
        if not matching:
            raise SchemaDriftReplayError(
                f"eval for run {ev.run_id} conditioned on schema "
                f"{ev.conditioning_schema_hash[:8]} which is absent from replay; "
                f"divergence frontier at span {frontier}. Refusing to attach."
            )
        attached.append((frontier, ev, "counterfactual"))
    return attached


def replay(spans: list[Span], evals: list[EvalRecord], current_schemas: dict[str, dict]):
    if divergence_frontier(spans, current_schemas) is not None:
        # Hard gate: do not silently proceed into counterfactual mode.
        raise SchemaDriftReplayError(
            "trace replayed against mutated schema; postmortem attribution "
            "at or after frontier is unlicensed without historical schema reconstruction"
        )
    return attach_eval_to_replay(spans, evals, current_schemas)
