# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-that-automatic-context-compaction-preserved-task-relevant-state-under-window-limits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-that-automatic-context-compaction-preserved-task-relevant-state-under-window-limits.warrant.json
# Markdown SHA-256:   d6451e9f07640f7c96b5185c95caa259fba10049090c405c1f31710044978f31
# Code AST SHA-256:   b78d39a5a631aac94264787e1ef51ff78adff0ac32e4a33582ea4b7ae5a025b5
# Verified Classes:   CompactionInvariantError, Obligation, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

ObligationState = Literal["open", "discharged"]


class CompactionInvariantError(RuntimeError):
    """Raised when a compaction pass would drop the resolution substrate
    of an obligation that is still open. This is a hard abort: continuing
    from a corrupted context propagates a poisoned premise downstream."""


@dataclass
class Obligation:
    oid: str
    state: ObligationState
    substrate_kind: Literal["literal", "semantic"]
    # For literal obligations, the exact tokens that must survive verbatim.
    pinned_literals: tuple[str, ...] = ()
    # For semantic obligations, the predicate that must be retained.
    predicate: str = ""


@dataclass
class CompactionPlan:
    # Tokens the compactor is allowed to paraphrase/summarize.
    compactable_region: str
    # Tokens the compactor must emit verbatim into the post-state.
    pinned_region: str
    obligations: list[Obligation] = field(default_factory=list)


def verify_compaction(plan: CompactionPlan, post_state: str) -> None:
    """Assert that every open obligation's substrate is present in the
    post-compaction context. Re-derivation must succeed from post_state
    alone; anything else is an invalid commit."""
    for ob in plan.obligations:
        if ob.state != "open":
            continue
        if ob.substrate_kind == "literal":
            for lit in ob.pinned_literals:
                if lit not in post_state:
                    raise CompactionInvariantError(
                        f"open obligation {ob.oid!r} lost literal substrate "
                        f"{lit!r}; compaction would force downstream "
                        f"regeneration of a load-bearing token"
                    )
        else:  # semantic
            if ob.predicate and ob.predicate.lower() not in post_state.lower():
                raise CompactionInvariantError(
                    f"open obligation {ob.oid!r} lost semantic predicate "
                    f"{ob.predicate!r}; summary preserved topic but not "
                    f"the constraint the future step conditions on"
                )


def compact(plan: CompactionPlan, summarizer) -> str:
    """Summarize only the compactable region, splice pinned region back
    verbatim, then gate on the re-derivation invariant."""
    summary = summarizer(plan.compactable_region)
    post_state = plan.pinned_region + "\n" + summary
    verify_compaction(plan, post_state)  # raises on violation
    return post_state
