# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-multi-agent-conversation-s-causal-graph-when-replaying-from-a-partial-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-multi-agent-conversation-s-causal-graph-when-replaying-from-a-partial-transcript.warrant.json
# Markdown SHA-256:   ea8634e7c690700e1fe0c4155e8c545f9e9160e6e1b62f2d6ef5bf56397dbc5b
# Code AST SHA-256:   5041525cad1a0c964f07e999d1b3bbd272f8154ad578d9393e61ad751cef094b
# Verified Classes:   CausalReplayError, ContextManifest, ReplayResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalReplayError(RuntimeError):
    """Raised when replay cannot reconstruct effective context."""


@dataclass
class ContextManifest:
    decision_seq: int
    present_msg_ids: list[str]
    present_summary_ids: list[str]
    dropped_msg_ids: list[str]
    tool_output_hashes: dict[str, str]


@dataclass
class ReplayResult:
    verdict: str
    causally_complete: bool
    divergences: list[int] = field(default_factory=list)


def replay(
    transcript: list[dict],
    manifests: dict[int, ContextManifest],
    artifact_store: dict[str, bytes],
    mode: str = "reconstruct",
) -> ReplayResult:
    if mode not in {"reconstruct", "counterfactual"}:
        raise CausalReplayError(f"unknown replay mode: {mode}")

    missing_manifests: list[int] = []
    missing_artifacts: list[str] = []

    for decision in transcript:
        seq = decision["seq"]
        manifest = manifests.get(seq)
        if manifest is None:
            missing_manifests.append(seq)
            continue
        for sid in manifest.present_summary_ids:
            if sid not in artifact_store:
                missing_artifacts.append(sid)
        for h in manifest.tool_output_hashes.values():
            if h not in artifact_store:
                missing_artifacts.append(h)

    causally_complete = not missing_manifests and not missing_artifacts

    if mode == "reconstruct" and not causally_complete:
        raise CausalReplayError(
            "cannot run reconstruction-grade replay: "
            f"missing manifests at seqs {missing_manifests[:5]}, "
            f"missing artifacts {missing_artifacts[:5]}"
        )

    # Counterfactual replay: full transcript is re-fed, so divergence from
    # the original run is expected wherever compaction dropped a constraint.
    divergences = _simulate(transcript, manifests, artifact_store)

    if not causally_complete:
        return ReplayResult(
            verdict="inconclusive: compaction-induced causality gap",
            causally_complete=False,
            divergences=divergences,
        )

    return ReplayResult(
        verdict="reconstructed" if not divergences else "non-determinism detected",
        causally_complete=True,
        divergences=divergences,
    )


def _simulate(transcript, manifests, artifact_store) -> list[int]:
    # Placeholder: real harness re-runs inference against manifest-derived
    # effective contexts and records decision-level divergences.
    return []
