# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-causally-reconstructed-replay-when-a-re-executed-agent-produces-a-divergent-tool-result-at-a-non-recorde.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-causally-reconstructed-replay-when-a-re-executed-agent-produces-a-divergent-tool-result-at-a-non-recorde.warrant.json
# Markdown SHA-256:   6bab32b84f485021e26ff428034f31adf60833cfe5fa9ba759b8b8186a346b66
# Code AST SHA-256:   5d59ed92d170978b602cb66be84c042eef1ac49d75c9808a60de9d9f463a8dc5
# Verified Classes:   UnclosedProvenanceError, UnpinnedSamplerError, Transition, ReplayRun
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnclosedProvenanceError(RuntimeError):
    """Raised when a replayed transition's provenance set is not a superset
    of the transcript-visible inputs the agent actually consumed."""
    pass


class UnpinnedSamplerError(RuntimeError):
    """Raised when a counterfactual replay cannot guarantee sampler determinism
    at the edited boundary (model version, seed, or context token drift)."""
    pass


@dataclass
class Transition:
    envelope_id: int
    agent: str
    consumed_envelope_ids: set[int]      # what the agent's context actually held
    recorded_provenance: set[int]        # what the transcript claims it depended on
    sampler_fingerprint: str             # hash of (model, seed, context tokens)


@dataclass
class ReplayRun:
    edited_envelope_id: int
    transitions: list[Transition] = field(default_factory=list)
    replayed_effects_from_transcript: bool = True


def assert_causal_admissibility(run: ReplayRun, original_sampler_fingerprint: str) -> None:
    if not run.replayed_effects_from_transcript:
        raise UnpinnedSamplerError(
            f"replay of envelope {run.edited_envelope_id} made live external calls; "
            "divergence may be an artifact of the world, not the edited edge"
        )

    for t in run.transitions:
        # Read-closure: every consumed input must appear in provenance.
        open_edges = t.consumed_envelope_ids - t.recorded_provenance
        if open_edges:
            raise UnclosedProvenanceError(
                f"transition at envelope {t.envelope_id} (agent={t.agent}) consumed "
                f"envelopes {sorted(open_edges)} absent from recorded provenance; "
                f"phantom edge — divergence cannot be attributed to edited edge "
                f"{run.edited_envelope_id}"
            )
        # Sampler pinning at the boundary.
        if t.sampler_fingerprint != original_sampler_fingerprint:
            raise UnpinnedSamplerError(
                f"transition at envelope {t.envelope_id} ran under sampler "
                f"{t.sampler_fingerprint[:12]} != original "
                f"{original_sampler_fingerprint[:12]}; downgrade to correlation"
            )


def replay_counterfactual(run: ReplayRun, original_fp: str) -> str:
    assert_causal_admissibility(run, original_fp)
    return "causal_evidence"


if __name__ == "__main__":
    # Observed case: S consumed R's reasoning-trace envelope #4 (to derive the
    # fetch URL at #9) but the transcript recorded provenance only for #6.
    bad = ReplayRun(
        edited_envelope_id=6,
        transitions=[
            Transition(
                envelope_id=9,
                agent="S",
                consumed_envelope_ids={4, 6},
                recorded_provenance={6},          # #4 missing -> phantom edge
                sampler_fingerprint="a1b2c3",
            )
        ],
    )
    try:
        replay_counterfactual(bad, original_fp="a1b2c3")
    except UnclosedProvenanceError as e:
        print(f"REJECTED: {e}")
