# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-session-trace-as-non-replayable-despite-a-byte-identical-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-session-trace-as-non-replayable-despite-a-byte-identical-transcript.warrant.json
# Markdown SHA-256:   56997cecfa91a93b1b270a7095eaf5044468acdc11bac5773bbdaabf2f987cf4
# Code AST SHA-256:   2beedcdec80116770490c6db843d9d8189fbdc0a94f27af762d57e0d4b1e077e
# Verified Classes:   NonReplayableTraceError, DecisionPoint, TraceLatentEvidence
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class NonReplayableTraceError(RuntimeError):
    """Raised when a decision point's latent-state sensitivity exceeds the
    trace's latent-state resolution, making forensic reconstruction invalid."""
    pass


@dataclass
class DecisionPoint:
    step: int
    logit_margin: float                 # top1 - top2; low margin => sampler-sensitive
    tool_purity: str                    # "pure" | "impure" | "unknown"
    near_truncation: bool               # within N tokens of a context event
    retrieval_order_dependent: bool


@dataclass
class TraceLatentEvidence:
    seed_recorded: bool
    tool_entropy_recorded: bool
    truncation_trigger_recorded: bool
    index_version_pinned: bool
    weight_revision_exact: bool
    substitutions_logged: list = field(default_factory=list)


MARGIN_THRESHOLD = 0.05  # below this, resampling can flip the decision


def is_sensitive(dp: DecisionPoint) -> bool:
    return (
        dp.logit_margin < MARGIN_THRESHOLD
        or dp.tool_purity != "pure"
        or dp.near_truncation
        or dp.retrieval_order_dependent
    )


def resolution_meets_sensitivity(dp: DecisionPoint, ev: TraceLatentEvidence) -> bool:
    if not is_sensitive(dp):
        return True
    if dp.logit_margin < MARGIN_THRESHOLD and not ev.seed_recorded:
        return False
    if dp.tool_purity != "pure" and not ev.tool_entropy_recorded:
        return False
    if dp.near_truncation and not ev.truncation_trigger_recorded:
        return False
    if dp.retrieval_order_dependent and not ev.index_version_pinned:
        return False
    if not ev.weight_revision_exact:
        return False
    return True


def classify_replay_posture(
    decisions: list[DecisionPoint], evidence: TraceLatentEvidence
) -> str:
    sensitive = [d for d in decisions if is_sensitive(d)]
    if not sensitive:
        return "strong_replay"
    for dp in sensitive:
        if not resolution_meets_sensitivity(dp, evidence):
            raise NonReplayableTraceError(
                f"Step {dp.step}: latent sensitivity exceeds trace resolution "
                f"(margin={dp.logit_margin}, tool={dp.tool_purity}, "
                f"trunc={dp.near_truncation}, order={dp.retrieval_order_dependent}); "
                f"evidence={evidence}. Forensic claim must be 'cannot reconstruct'."
            )
    return "bounded_replay"


def reconstruct(decisions: list[DecisionPoint], evidence: TraceLatentEvidence) -> str:
    posture = classify_replay_posture(decisions, evidence)
    if evidence.substitutions_logged:
        # Substitutions at impure tools mask divergence; downgrade the claim.
        if posture == "strong_replay":
            posture = "bounded_replay"
    return posture
