# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-summarizer-induced-salience-collapse-as-a-compaction-boundary-rather-than-a-context-window-budget-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-summarizer-induced-salience-collapse-as-a-compaction-boundary-rather-than-a-context-window-budget-problem.warrant.json
# Markdown SHA-256:   7728b53579c774a506bb6c9a1d60700b0416e35ae6dc4453b89e122fcae59085
# Code AST SHA-256:   a905f29ada788afb9cf012aeec175d41b112a5b7a96790175cd9cc69f472f550
# Verified Classes:   SalienceCollapseError, Fact, CarryForward
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Modality = Literal["directive", "observation", "probe", "terminal_error", "transient_error"]


class SalienceCollapseError(RuntimeError):
    """Raised when a compaction pass preserves facts but erases precedence edges
    or synthesizes non-entailed propositions."""


@dataclass
class Fact:
    id: str
    text: str
    modality: Modality
    valid_as_of: int
    superseded_by: str | None = None
    gates: str | None = None          # for directives: the predicate that must hold
    entailed_by: list[str] = field(default_factory=list)  # source turn ids


@dataclass
class CarryForward:
    facts: dict[str, Fact]
    synthesized: list[str] = field(default_factory=list)  # propositions with no source


def verify_compaction(pre: dict[str, Fact], post: CarryForward) -> None:
    """Gate the next action on edge preservation, not on token count."""
    # 1. Every retained fact must keep its modality (no transient/terminal collapse).
    for fid, f in post.facts.items():
        if fid in pre and pre[fid].modality != f.modality:
            raise SalienceCollapseError(
                f"modality laundering on {fid}: {pre[fid].modality} -> {f.modality}"
            )

    # 2. Every retained superseded fact must keep its supersession edge, or be dropped.
    for fid, f in post.facts.items():
        if fid in pre and pre[fid].superseded_by is not None:
            if f.superseded_by is None:
                raise SalienceCollapseError(
                    f"orphaned superseded fact {fid}: edge erased, fact retained"
                )

    # 3. Every retained directive must keep its gating predicate.
    for fid, f in post.facts.items():
        if f.modality == "directive" and not f.gates:
            raise SalienceCollapseError(
                f"directive {fid} retained without gating predicate: "
                f"agent can quote the action but not its precondition"
            )

    # 4. No synthesized propositions may enter the carry-forward block.
    if post.synthesized:
        raise SalienceCollapseError(
            f"non-entailed propositions in carry-forward: {post.synthesized}"
        )


def compact_or_checkpoint(pre: dict[str, Fact], candidate: CarryForward) -> CarryForward:
    try:
        verify_compaction(pre, candidate)
        return candidate
    except SalienceCollapseError:
        # Fall back to structured, edge-preserving carry-forward.
        structured = {
            fid: f for fid, f in pre.items()
            if f.modality == "directive"
            or f.superseded_by is None
            or f.modality in ("terminal_error", "probe")
        }
        return CarryForward(facts=structured, synthesized=[])
