# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-auto-compaction-from-silently-severing-causal-chains-in-long-horizon-agent-transcripts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-auto-compaction-from-silently-severing-causal-chains-in-long-horizon-agent-transcripts.warrant.json
# Markdown SHA-256:   bfe6e95a2523b309da31d9111ac6fd097345f2a50cd89eff35e89644a12a7329
# Code AST SHA-256:   c7da27adc66bbf423f9af350b9e7832e9a7ca2c41a4016bfdf5f13e1efc91e1e
# Verified Classes:   CausalClosureViolation, Span, PendingAction
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalClosureViolation(RuntimeError):
    """Raised when post-compaction state cannot justify a pending action."""
    pass


@dataclass
class Span:
    turn: int
    kind: str          # "narrative" | "constraint" | "commitment" | "error" | "correction"
    text: str
    qualifiers: dict = field(default_factory=dict)


@dataclass
class PendingAction:
    name: str
    requires_kind: str          # e.g. "commitment"
    requires_qualifier: str     # e.g. "scope"


LOAD_BEARING = {"constraint", "commitment", "error", "correction"}


def classify_for_eviction(spans: list[Span]) -> tuple[list[Span], list[Span]]:
    """Split spans into evictable (narrative) and must-retain (load-bearing)."""
    evictable, retain = [], []
    for s in spans:
        (retain if s.kind in LOAD_BEARING else evictable).append(s)
    return evictable, retain


def compact(spans: list[Span], pending: list[PendingAction]) -> list[Span]:
    """Compact narrative spans; retain load-bearing spans verbatim."""
    evictable, retained = classify_for_eviction(spans)
    # Narrative may be summarized; load-bearing spans are never summarized.
    compacted = retained  # summaries of `evictable` would be appended here as kind="narrative"
    _assert_closure(compacted, pending)
    return compacted


def _assert_closure(state: list[Span], pending: list[PendingAction]) -> None:
    for action in pending:
        justifications = [
            s for s in state
            if s.kind == action.requires_kind
            and action.requires_qualifier in s.qualifiers
        ]
        if not justifications:
            raise CausalClosureViolation(
                f"Compaction would sever causal chain for pending action "
                f"{action.name!r}: no retained {action.requires_kind!r} span "
                f"carrying qualifier {action.requires_qualifier!r}. "
                f"Refuse compaction; spill to external memory instead."
            )


# Trace of the observed failure, replayed against the guardrail:
history = [
    Span(1, "narrative", "Task: migrate the data."),
    Span(47, "commitment", "auth probe returned scope", {"scope": "read_only"}),
    Span(112, "narrative", "proceeding to write"),
]
pending = [PendingAction("write_resource", "commitment", "scope")]

try:
    compact(history, pending)   # read_only commitment is retained -> closure holds
    # Now simulate the actual eviction that occurred: the commitment was summarized away.
    broken = [Span(1, "narrative", "Task: migrate."), Span(112, "narrative", "scope confirmed")]
    _assert_closure(broken, pending)
except CausalClosureViolation as e:
    raise CausalClosureViolation(f"Auto-compaction refused: {e}") from e
