# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-the-compaction-cliff-when-lossy-trace-summarization-silently-drops-the-negative-constraints-a-long-horizon-age.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-the-compaction-cliff-when-lossy-trace-summarization-silently-drops-the-negative-constraints-a-long-horizon-age.warrant.json
# Markdown SHA-256:   455ce966401533a64d7802a00c528029c319a29369ae9269bd80202b096c855b
# Code AST SHA-256:   b09ef564d21e2194e67e38b26a5ac84934f3c65e5538836602b5f6bc7a74e26c
# Verified Classes:   CompactionCliffError, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionCliffError(RuntimeError):
    """Raised when lossy compaction would shrink the negative-constraint set."""
    pass


@dataclass
class ConstraintLedger:
    # Append-only. Entries are prohibitions and dead-ends. Never summarized.
    entries: list[str] = field(default_factory=list)

    def add(self, entry: str) -> None:
        if entry not in self.entries:
            self.entries.append(entry)

    def snapshot(self) -> frozenset[str]:
        return frozenset(self.entries)


def compact_trace(
    raw_trace: str,
    ledger: ConstraintLedger,
    summarize_fn,
    post_context: str,
) -> str:
    """
    Perform lossy compaction ONLY if the constraint set is preserved.
    summarize_fn: callable(raw_trace) -> summary_str (may drop anything).
    post_context: the summary + re-injected ledger that the agent will act on.
    """
    before = ledger.snapshot()

    summary = summarize_fn(raw_trace)

    # Re-inject the ledger verbatim; compaction never touches it.
    rebuilt_context = summary + "\n\n[IMMUTABLE CONSTRAINTS]\n" + "\n".join(
        f"- {e}" for e in ledger.entries
    )

    after = ledger.snapshot()

    # Invariant 1: compaction must be monotone over the constraint set.
    if after != before:
        lost = before - after
        raise CompactionCliffError(
            f"compaction dropped {len(lost)} negative constraint(s): {sorted(lost)}"
        )

    # Invariant 2: every ledger entry must survive verbatim into post-context.
    for entry in before:
        if entry not in rebuilt_context:
            raise CompactionCliffError(
                f"ledger entry absent from post-compaction context: {entry!r}"
            )

    return rebuilt_context
