# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-that-auto-compaction-preserved-the-causal-preconditions-of-an-in-flight-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-that-auto-compaction-preserved-the-causal-preconditions-of-an-in-flight-plan.warrant.json
# Markdown SHA-256:   de912d5e848135f6e9c5144523f6eb1b0561d5104bc47d415df5fe25c3a18542
# Code AST SHA-256:   24e13d9e7cc8d2b36148f6090c57a2632e0fd6259f8b086dd2c752cc237da4d6
# Verified Classes:   PreconditionEntailmentError, PlanStep, CompactionResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PreconditionEntailmentError(RuntimeError):
    """Raised when post-compaction context does not entail a remaining step's preconditions."""
    pass


@dataclass
class PlanStep:
    step_id: int
    action: str
    preconditions: list[str]  # obligations that must be derivable from context


@dataclass
class CompactionResult:
    retained_context: str
    side_channel: dict[int, list[str]] = field(default_factory=dict)


def _entailed(precondition: str, retained_context: str) -> bool:
    # Real implementation delegates to a verifier model or structured store lookup.
    # Here: a precondition is entailed only if it appears as a live obligation,
    # not merely as a descriptive fact. We require the obligation marker.
    return f"OBLIGATION::{precondition}" in retained_context


def verify_post_compaction(
    steps: list[PlanStep],
    compaction: CompactionResult,
    executed_ids: set[int],
) -> list[PlanStep]:
    """Return steps whose preconditions survive; raise on the first unentailed one
    that the side-channel did not preserve verbatim."""
    unverified: list[PlanStep] = []
    for step in steps:
        if step.step_id in executed_ids:
            continue
        preserved = compaction.side_channel.get(step.step_id, [])
        for pre in step.preconditions:
            if pre in preserved:
                continue
            if _entailed(pre, compaction.retained_context):
                continue
            unverified.append(step)
            break
    if unverified:
        first = unverified[0]
        raise PreconditionEntailmentError(
            f"step {first.step_id} ({first.action!r}) has preconditions not entailed "
            f"by post-compaction context and absent from side-channel: "
            f"{[p for p in first.preconditions if p not in compaction.side_channel.get(first.step_id, [])]}. "
            f"Re-derive before executing."
        )
    return [s for s in steps if s.step_id not in executed_ids]
