# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-recorded-trace-when-replayed-for-counterfactual-forensic-analysis.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-recorded-trace-when-replayed-for-counterfactual-forensic-analysis.warrant.json
# Markdown SHA-256:   c40e8edea07ab85e8f0d08e839d443a2b563b3f5d7f172354557da8cef9e21d9
# Code AST SHA-256:   adbdf9f9ea3c1faf3c14c91ca61e83de0fd32efc634156213cdacf99c28a99c1
# Verified Classes:   ReplayValidityError, Invocation, DivergenceReport
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ReplayValidityError(RuntimeError):
    """Raised when a counterfactual divergence claim fails the validity contract."""
    pass

@dataclass
class Invocation:
    step: int
    agent: str
    context_hash: str
    seed: Optional[int]
    recomputed: bool          # was context re-assembled from perturbed state?
    causal_ancestors: set     # step ids whose outputs appear in this context
    output: str

@dataclass
class DivergenceReport:
    divergence_step: int
    perturbation_site: int
    claimed_cause: str

def validate_divergence(
    report: DivergenceReport,
    invocations: dict,        # step -> Invocation
    index_pinned: bool,
) -> None:
    inv = invocations.get(report.divergence_step)
    if inv is None:
        raise ReplayValidityError(
            f"divergence step {report.divergence_step} not in invocation log"
        )

    # Condition 1: context must have been recomputed, not read from log.
    if not inv.recomputed:
        raise ReplayValidityError(
            f"step {inv.step} ({inv.agent}) context read from log, not recomputed; "
            "divergence is a partial-counterfactual artifact, not causal"
        )

    # Condition 3: perturbation site must be a causal ancestor of the divergence.
    if report.perturbation_site not in inv.causal_ancestors:
        raise ReplayValidityError(
            f"perturbation at step {report.perturbation_site} is not in causal "
            f"ancestor set of divergence step {inv.step} "
            f"(ancestors={sorted(inv.causal_ancestors)}); "
            "non-injective context assembly laundered the perturbation"
        )

    # Condition 2: seed must be recorded for the perturbed invocation.
    pert = invocations.get(report.perturbation_site)
    if pert is not None and pert.seed is None:
        raise ReplayValidityError(
            f"perturbation step {report.perturbation_site} has no recorded seed; "
            "cannot distinguish perturbation effect from sampling variance"
        )

    # Condition 4: retrieval index must be pinned to incident snapshot.
    if not index_pinned:
        raise ReplayValidityError(
            "retrieval index not pinned to incident snapshot; "
            "stale-memory drift confounds any retrieval-adjacent divergence"
        )

def promote_to_finding(report: DivergenceReport, invocations: dict, index_pinned: bool) -> str:
    validate_divergence(report, invocations, index_pinned)
    return (
        f"ROOT CAUSE: {report.claimed_cause} "
        f"(perturbation step {report.perturbation_site} -> "
        f"divergence step {report.divergence_step}, all validity conditions met)"
    )
