# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-window-mid-task-and-the-summarizer-silently-drops-the-invariant-it-was-hired-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-window-mid-task-and-the-summarizer-silently-drops-the-invariant-it-was-hired-to-preserve.warrant.json
# Markdown SHA-256:   c98a7f292892e077fc279d08666fb97a832121ca52c501962b58e719afa44aac
# Code AST SHA-256:   28626f89d94f6c20cddf2cef3f1764eb5a76f1edc2429c43e056b8a6b437a991
# Verified Classes:   CompactionInvariantViolation, InvariantLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionInvariantViolation(RuntimeError):
    """Raised when compaction would sever a live invariant from ground truth."""
    pass


@dataclass
class InvariantLedger:
    """Structured, non-summarized carrier of live invariants across a boundary."""
    entries: dict = field(default_factory=dict)  # key -> invariant record

    def add(self, key: str, kind: str, resource_id: str,
            expected_status: str, precondition: Optional[str] = None) -> None:
        self.entries[key] = {
            "kind": kind,
            "resource_id": resource_id,
            "expected_status": expected_status,
            "precondition": precondition,
        }

    def reconcile(self, ground_truth: dict) -> None:
        """Assert every ledger entry against authoritative post-resume state."""
        for key, inv in self.entries.items():
            actual = ground_truth.get(inv["resource_id"])
            if actual is None:
                raise CompactionInvariantViolation(
                    f"ledger entry {key!r} references unknown resource "
                    f"{inv['resource_id']!r}; summary cannot be trusted"
                )
            if actual.get("status") != inv["expected_status"]:
                raise CompactionInvariantViolation(
                    f"ledger entry {key!r} expected status "
                    f"{inv['expected_status']!r} but ground truth is "
                    f"{actual.get('status')!r}; aborting resume"
                )


def maybe_compact(tokens_used: int, window: int, *,
                  is_quiescent: bool,
                  ledger: InvariantLedger,
                  ground_truth_provider) -> bool:
    """Gate compaction on safety, not pressure. Returns True iff compaction ran."""
    ceiling = int(0.78 * window)
    if tokens_used <= ceiling:
        return False

    # Pressure exceeds ceiling. We MAY compact only if safe to do so.
    if not is_quiescent:
        # Do not summarize across a live invariant. Shed or block instead.
        raise CompactionInvariantViolation(
            "compaction pressure exceeded ceiling while task is non-quiescent; "
            "refusing lossy summarization across a live invariant — shed large "
            "tool outputs or block until quiescence"
        )

    if not ledger.entries:
        # Quiescent with no live invariants: summarization is safe.
        return True

    # Quiescent but invariants exist: carry ledger verbatim, then reconcile.
    ground_truth = ground_truth_provider()
    ledger.reconcile(ground_truth)
    return True
