# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-severing-the-causal-chain-between-a-plan-s-origin-and-its-current-execution-step.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-severing-the-causal-chain-between-a-plan-s-origin-and-its-current-execution-step.warrant.json
# Markdown SHA-256:   8c59bd24137a592f6a2b22f4e67061ea3e46265f3139a78bde6f2530c8ab09fe
# Code AST SHA-256:   e6af819966baf8d4b7319abc1dcfd485adccd96d9f2e4a1d7a025bc55e0e8f07
# Verified Classes:   ProvenanceCollapseError, Observation, PendingAction
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceCollapseError(RuntimeError):
    """Raised when a compaction pass would sever the causal link between a
    pending action's precondition and its sole surviving observation."""
    pass


@dataclass
class Observation:
    step_id: int
    text: str
    supersedes: Optional[int] = None  # step_id of the observation this corrects

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()[:12]


@dataclass
class PendingAction:
    name: str
    preconditions: list[str] = field(default_factory=list)


def compact(
    window: list[Observation],
    pending: list[PendingAction],
    retained_ids: set[int],
) -> list[Observation]:
    """Return the observations safe to lossily compact.

    Raises ProvenanceCollapseError if any pending action's latest
    precondition-bearing observation would be compacted away without a
    retained, back-referenced restatement (violates C1/C3).
    """
    compactable: list[Observation] = []
    for obs in window:
        # C1: corrections/supersessions are never lossily compacted.
        if obs.supersedes is not None:
            raise ProvenanceCollapseError(
                f"step {obs.step_id} is a supersession of step "
                f"{obs.supersedes}; it encodes a delta and must be pinned, "
                f"not summarized (violates C1)"
            )
        # C3: if this is the latest witness to a pending precondition and it
        # is not restated by a retained later turn, it is not compactable.
        for action in pending:
            for pre in action.preconditions:
                if pre in obs.text and obs.step_id not in retained_ids:
                    raise ProvenanceCollapseError(
                        f"step {obs.step_id} ({obs.content_hash}) is the sole "
                        f"surviving witness to precondition {pre!r} of pending "
                        f"action {action.name!r}; compacting it would leave the "
                        f"action acting on an unreferenced premise (violates C3)"
                    )
        compactable.append(obs)
    return compactable
