# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-automatic-context-compaction-has-silently-destroyed-task-critical-state-under-token-budget-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-automatic-context-compaction-has-silently-destroyed-task-critical-state-under-token-budget-pressure.warrant.json
# Markdown SHA-256:   41608b04c318897f6c24ad6c64ff1750d210803af3e0a86feed613f68de3cc84
# Code AST SHA-256:   6660dc9a00ee8f304e9b183ddfd8c49eab32fed5b9edb659535958c6c76f48d4
# Verified Classes:   CompactionStateLoss, ConstraintLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionStateLoss(RuntimeError):
    """Raised when a compaction pass drops task-critical constraints."""


@dataclass
class ConstraintLedger:
    prohibitions: dict[str, str] = field(default_factory=dict)
    scoped_ids: set[str] = field(default_factory=set)
    partial_flags: dict[str, str] = field(default_factory=dict)

    def record(self, prohibition: str, scope_id: str | None = None,
               partial: str | None = None) -> None:
        self.prohibitions[prohibition] = prohibition
        if scope_id:
            self.scoped_ids.add(scope_id)
        if partial:
            self.partial_flags[partial] = partial

    def count(self) -> int:
        return len(self.prohibitions) + len(self.scoped_ids) + len(self.partial_flags)


def verify_compaction(pre: ConstraintLedger, post_summary: str,
                      next_actions_destructive: bool) -> None:
    """Gate a compaction pass. Refuse to release compacted context if a
    destructive action is pending and any ledger entry did not survive
    verbatim into the post-compaction context."""
    if not next_actions_destructive:
        return  # reads/drafts: loss is recoverable, allow

    missing = [p for p in pre.prohibitions if p not in post_summary]
    missing += [s for s in pre.scoped_ids if s not in post_summary]
    missing += [f for f in pre.partial_flags if f not in post_summary]

    if missing:
        raise CompactionStateLoss(
            "compaction dropped task-critical state before a destructive "
            f"action; missing verbatim constraints: {missing!r}. "
            "Re-inject ledger block and re-run compaction, or replay from "
            "the pre-compaction checkpoint."
        )
