# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-replayed-counterfactual-trace-that-its-own-verifier-would-reject-under-live-execution-and-how-do-we-bound-speculative-pl.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-replayed-counterfactual-trace-that-its-own-verifier-would-reject-under-live-execution-and-how-do-we-bound-speculative-pl.warrant.json
# Markdown SHA-256:   2b0465777a12421f8803218a1ff0c8c063d87352b0d0abc86bf6febd32cfa6a3
# Code AST SHA-256:   24ca727c66ef6692f78123e54e608da7a740752f7fc9a150519daf7210d2f4f0
# Verified Classes:   Provenance, CounterfactualVerificationError, Observation, Verdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Provenance(Enum):
    PREDICTED = "predicted"   # synthesized by planner's world model
    RECORDED = "recorded"     # produced by a real tool invocation


class CounterfactualVerificationError(RuntimeError):
    """Raised when a counterfactual trace is admitted as if it were recorded,
    or when a plan advances to commit without grounding at non-idempotent steps."""
    pass


@dataclass
class Observation:
    step: str
    payload: dict
    provenance: Provenance
    tool_is_idempotent: bool


@dataclass
class Verdict:
    kind: str  # "VERIFIED" | "CONSISTENT_UNVERIFIED"
    grounded_steps: list[str]
    ungrounded_steps: list[str]


def verify_replayed_trace(trace: list[Observation]) -> Verdict:
    grounded, ungrounded = [], []
    for obs in trace:
        # Admission checks that require tool semantics apply ONLY to recorded obs.
        if obs.provenance is Provenance.RECORDED:
            if "status" not in obs.payload:
                raise CounterfactualVerificationError(
                    f"recorded observation at {obs.step!r} missing status field"
                )
            grounded.append(obs.step)
        elif obs.provenance is Provenance.PREDICTED:
            # Predicted observations may be checked for internal consistency only.
            ungrounded.append(obs.step)
        else:
            raise CounterfactualVerificationError(
                f"observation at {obs.step!r} has unknown provenance"
            )

    if not ungrounded:
        return Verdict("VERIFIED", grounded, ungrounded)
    return Verdict("CONSISTENT_UNVERIFIED", grounded, ungrounded)


def advance_to_commit(verdict: Verdict, trace: list[Observation]) -> None:
    """Only VERIFIED plans may commit. A CONSISTENT_UNVERIFIED plan must be
    probed at every non-idempotent step before commit."""
    if verdict.kind == "VERIFIED":
        return
    non_idempotent_ungrounded = [
        obs.step for obs in trace
        if obs.provenance is Provenance.PREDICTED and not obs.tool_is_idempotent
    ]
    if non_idempotent_ungrounded:
        raise CounterfactualVerificationError(
            "refusing to commit: non-idempotent steps lack recorded observations: "
            f"{non_idempotent_ungrounded}. Probe each step and splice a RECORDED "
            "observation before requesting commit."
        )
    # Remaining ungrounded steps are idempotent reads; cheap to recover, allow commit.
    return
