# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-context-loss-when-auto-compaction-summarizes-agent-trajectories-under-lossy-guarantees.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-context-loss-when-auto-compaction-summarizes-agent-trajectories-under-lossy-guarantees.warrant.json
# Markdown SHA-256:   b8c0f12a087b51dbee8680fdcfb4bd516f6768645e06c174f3dbf8f73ad0d3fc
# Code AST SHA-256:   3e10334ced9e043e80bf499e310c72909f24da05addd5fafb80fb8b459dfd920
# Verified Classes:   CompactionInvariantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CompactionInvariantError(RuntimeError):
    """Raised when a compaction summary would violate polarity, ordering, or provenance invariants."""
    pass


def validate_compaction(summary: dict, raw_segment: dict) -> None:
    # Invariant 1: polarity preservation for every retained proposition
    for prop in summary.get("propositions", []):
        if "polarity" not in prop:
            raise CompactionInvariantError(
                f"proposition {prop.get('id')!r} lacks polarity; entity-only recall is insufficient"
            )

    # Invariant 2: ordering preservation for state-mutating facts
    mutations = [p for p in summary.get("propositions", []) if p.get("kind") == "mutation"]
    if len(mutations) > 1 and not all("sequence_id" in p for p in mutations):
        raise CompactionInvariantError(
            "multiple state mutations summarized without sequence_id; ordering collapsed into a set"
        )

    # Invariant 3: provenance addressability to the raw turn range
    if "source_range" not in summary or summary["source_range"] != raw_segment.get("range"):
        raise CompactionInvariantError(
            "summary lacks a valid provenance pointer to its raw turn range; loss is unrecoverable"
        )

    # Invariant 4: sole-record decisions must not be compacted away
    if raw_segment.get("is_sole_record_of_decision") and summary.get("discards_raw"):
        raise CompactionInvariantError(
            "refusing to discard the only record of a decision; retain raw or write a durable log first"
        )


def compact(segment: dict) -> dict:
    summary = build_summary(segment)  # lossy summarizer
    validate_compaction(summary, segment)
    return summary
