# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-replay-divergence-fault-in-deterministic-reconstruction-of-agentic-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-replay-divergence-fault-in-deterministic-reconstruction-of-agentic-traces.warrant.json
# Markdown SHA-256:   847f96b5230e8e635651dbc922e7204936c78f33558e8ebf5883fe6a3d3566c3
# Code AST SHA-256:   d6f63a0dc3ae30b3df4e8ed96076f12a9f8fdb5419dd05b8405a1abbd131bca7
# Verified Classes:   ReplayIntegrityError, TraceStep
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ReplayIntegrityError(RuntimeError):
    """Raised when a replay step cannot be verified against recorded prompt bytes."""
    pass


@dataclass(frozen=True)
class TraceStep:
    step_index: int
    prompt_sha256: str          # hash of exact assembled prompt bytes
    decision_logprob_margin: float
    compaction_seed: int | None  # None if no compaction applied


SAMPLING_NOISE_FLOOR_NATS = 0.3


def verify_and_replay(trace: list[TraceStep], reconstructed_prompts: list[bytes]) -> int:
    """
    Replay a trace, verifying context-identity at each step.
    Returns index of first admissible divergence, or -1 if fully deterministic.
    Raises ReplayIntegrityError if a step's prompt hash cannot be verified.
    """
    if len(trace) != len(reconstructed_prompts):
        raise ReplayIntegrityError(
            f"trace has {len(trace)} steps but reconstruction produced "
            f"{len(reconstructed_prompts)} prompts; alignment impossible"
        )

    for step, prompt_bytes in zip(trace, reconstructed_prompts):
        actual = hashlib.sha256(prompt_bytes).hexdigest()
        if actual != step.prompt_sha256:
            # Hash mismatch: reconstruction is lossy at this seam.
            # A high-margin step here is a reconstruction fault, not model noise.
            if step.decision_logprob_margin > SAMPLING_NOISE_FLOOR_NATS:
                raise ReplayIntegrityError(
                    f"step {step.step_index}: prompt hash mismatch "
                    f"(recorded={step.prompt_sha256[:12]}, "
                    f"reconstructed={actual[:12]}) at high-confidence "
                    f"decision (margin={step.decision_logprob_margin:.2f} nats); "
                    f"replay inadmissible from this step forward"
                )
            # Low-margin mismatch: benign, but still flag for audit.
            return step.step_index

    return -1  # fully verified, fully deterministic


def assert_replay_admissible(trace: list[TraceStep], reconstructed_prompts: list[bytes]) -> None:
    """Wrapper enforcing that no compaction boundary is unseeded."""
    for step in trace:
        if step.compaction_seed is None and step.step_index > 0:
            raise ReplayIntegrityError(
                f"step {step.step_index}: compaction boundary present but "
                f"no seed recorded; context-identity invariant cannot be "
                f"verified — downgrade to plausibility narrative"
            )
    verify_and_replay(trace, reconstructed_prompts)
