# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-replay-a-poisoned-agentic-session-when-tool-call-telemetry-records-intent-but-not-the-nondeterministic-tool-result.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-replay-a-poisoned-agentic-session-when-tool-call-telemetry-records-intent-but-not-the-nondeterministic-tool-result.warrant.json
# Markdown SHA-256:   cb8db61df857e82da204109328c8cc96947ba8d4b23408d6be08bc27286788b5
# Code AST SHA-256:   0339e3cc52327282c0584f708bc36868de3b731c415390c5d1350248650051d6
# Verified Classes:   ReplayAdmissibilityError, ToolSpan, Substitution
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ReplayAdmissibilityError(RuntimeError):
    """Raised when a replay cannot be admitted as evidence of agent behavior."""


@dataclass
class ToolSpan:
    span_id: str
    tool_name: str
    result_preview: bytes
    result_byte_length: int
    result_sha256: str | None  # None if full result not archived
    feeds_decisions: set[str] = field(default_factory=set)  # decision span IDs whose input window includes this result


@dataclass
class Substitution:
    span_id: str
    missing_bytes: int
    field_diff: dict


def check_admissibility(
    spans: list[ToolSpan],
    decision_under_investigation: str,
    allow_counterfactual: bool = False,
) -> list[Substitution]:
    """
    Decide whether a replay of `decision_under_investigation` is admissible.
    Returns the list of substitutions that were made (empty iff fully clean).
    Raises ReplayAdmissibilityError if a substitution would contaminate the decision.
    """
    substitutions: list[Substitution] = []

    for span in spans:
        full_archived = (
            span.result_sha256 is not None
            and len(span.result_preview) == span.result_byte_length
            and hashlib.sha256(span.result_preview).hexdigest() == span.result_sha256
        )
        if full_archived:
            continue

        # Result is incomplete. If it is on the causal path to the decision,
        # substitution would contaminate the input window.
        on_causal_path = decision_under_investigation in span.feeds_decisions

        if on_causal_path and not allow_counterfactual:
            raise ReplayAdmissibilityError(
                f"span {span.span_id} ({span.tool_name}) is on the causal path to "
                f"decision {decision_under_investigation} but only "
                f"{len(span.result_preview)}/{span.result_byte_length} bytes are archived "
                f"and no result.sha256 is pinned. Substitution would change the agent's "
                f"input window. Replay is inadmissible as evidence; report "
                f"INSUFFICIENT_TELEMETRY for byte range "
                f"[{len(span.result_preview)}, {span.result_byte_length})."
            )

        substitutions.append(
            Substitution(
                span_id=span.span_id,
                missing_bytes=span.result_byte_length - len(span.result_preview),
                field_diff={"note": "live re-execution substituted for archived preview"},
            )
        )

    if substitutions and not allow_counterfactual:
        # Off-causal-path substitutions are tolerable but must be reported.
        # The caller must tag the report mode=counterfactual if any are present
        # and any downstream divergence occurs.
        pass

    return substitutions


def replay_session(spans, decision_id, allow_counterfactual=False):
    try:
        subs = check_admissibility(spans, decision_id, allow_counterfactual)
    except ReplayAdmissibilityError as e:
        return {"status": "INSUFFICIENT_TELEMETRY", "detail": str(e)}
    mode = "counterfactual" if subs else "result_replay"
    return {
        "status": "REPLAYED",
        "mode": mode,
        "substitutions": [s.__dict__ for s in subs],
        "clean_input_window": not any(
            decision_id in s.feeds_decisions for s in spans
        ),
    }
