# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-an-auto-compaction-pass-from-silently-reordering-the-causal-frontier-of-a-long-horizon-agent-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-an-auto-compaction-pass-from-silently-reordering-the-causal-frontier-of-a-long-horizon-agent-transcript.warrant.json
# Markdown SHA-256:   1f08532cd03604c973c84119f94beffbfe33d9881b657bd4bcb975b2373c866a
# Code AST SHA-256:   42c028dee82f9fa5c706fde463494a2c299ab9edd7450bde63c60f444334fe64
# Verified Classes:   CausalFrontierViolation, Event
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalFrontierViolation(RuntimeError):
    """Raised when a compaction pass would reorder or coalesce events that
    stand in a causal dependency relation, invalidating the agent's frontier."""


@dataclass
class Event:
    id: str
    kind: str                      # "tool_request" | "tool_result" | "decision" | "assertion"
    caused_by: Optional[str] = None
    supersedes: Optional[str] = None


def validate_compaction(original: list[Event], compacted_ids: list[str]) -> None:
    """Check that compaction preserves ordering across every causal edge whose
    endpoints both survive, and that dropped sources are explicitly superseded.

    Raises CausalFrontierViolation on the first broken edge.
    """
    pos = {eid: i for i, eid in enumerate(compacted_ids)}
    surviving = set(compacted_ids)

    for ev in original:
        if ev.caused_by is None:
            continue
        src, dst = ev.caused_by, ev.id
        src_live, dst_live = src in surviving, dst in surviving

        if src_live and dst_live and pos[src] >= pos[dst]:
            raise CausalFrontierViolation(
                f"edge {src} -> {dst} inverted in compacted transcript "
                f"(positions {pos[src]} >= {pos[dst]})"
            )

        if not src_live and dst_live:
            # source dropped: the dependent must carry an explicit supersedes
            # marker pointing at the dropped source, or the edge is lost.
            if ev.supersedes != src:
                raise CausalFrontierViolation(
                    f"dependent {dst} survived but its cause {src} was dropped "
                    f"without an explicit supersedes marker"
                )


def compact_and_resume(original: list[Event], summarizer_output: list[str],
                       pending_action: Event) -> list[str]:
    validate_compaction(original, summarizer_output)

    # Resume guard: a pending action whose cause chain is not present in the
    # compacted transcript must halt rather than execute.
    if pending_action.caused_by and pending_action.caused_by not in summarizer_output:
        raise CausalFrontierViolation(
            f"pending action {pending_action.id} depends on "
            f"{pending_action.caused_by}, absent from compacted transcript; "
            f"refusing to resume"
        )
    return summarizer_output
