# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-summarization-has-silently-dropped-a-live-obligation-during-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-summarization-has-silently-dropped-a-live-obligation-during-context-compaction.warrant.json
# Markdown SHA-256:   d76df2535609573a9bea4601d4ff19ca9762f0bac120354088b9556141cb89ce
# Code AST SHA-256:   ee535721027fcf96ba767c985949aff847c84b8522ecf60c6824b1382a81c3e6
# Verified Classes:   DroppedObligationError, ObligationLedger, CompactedState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class DroppedObligationError(RuntimeError):
    """Raised when a mutating action targets an entity with no surviving constraint."""


@dataclass
class ObligationLedger:
    # entity -> list of constraint strings, carried verbatim across compaction
    constraints: dict[str, list[str]] = field(default_factory=dict)

    def record(self, entity: str, constraint: str) -> None:
        self.constraints.setdefault(entity, []).append(constraint)

    def has_constraint(self, entity: str) -> bool:
        return bool(self.constraints.get(entity))


# Entities a compacted summary claims to know about, mapped to whether the
# summary still carries any modal/prohibitive operator for that entity.
@dataclass
class CompactedState:
    entities: Iterable[str]
    constraint_bearing: set[str]


def guard_mutating_action(
    action_entity: str,
    state: CompactedState,
    ledger: ObligationLedger,
    can_retrieve_checkpoint: bool,
) -> None:
    """
    Enforce the invariant: a mutating action on an entity requires either a
    surviving constraint in the compacted state or a ledger entry (possibly
    re-retrieved from a lossless checkpoint). Read-only actions are not routed
    here.
    """
    entity = action_entity
    if entity in state.constraint_bearing or ledger.has_constraint(entity):
        return

    if can_retrieve_checkpoint:
        # Caller must re-retrieve the turn range that last touched `entity`
        # and populate the ledger before retrying; we refuse to proceed blind.
        raise DroppedObligationError(
            f"Mutating action on '{entity}' with no surviving constraint and "
            f"no ledger entry. Re-retrieve checkpoint range before retrying."
        )

    raise DroppedObligationError(
        f"Mutating action on '{entity}' blocked: obligation dropped by "
        f"hierarchical summarization and no checkpoint available to recover it. "
        f"Halting to avoid silent constraint violation."
    )


def audit_compaction(
    pre_segment_modals: set[str],
    post_summary_modals: set[str],
    pre_entities: set[str],
    post_constraint_entities: set[str],
) -> dict[str, object]:
    """
    Structural signals that a hierarchical summary dropped obligations:
      - modal operators present pre-compaction, absent post-compaction
      - entities that survived topically but lost all constraints
    """
    lost_modals = pre_segment_modals - post_summary_modals
    stripped_entities = pre_entities - post_constraint_entities
    return {
        "lost_modals": lost_modals,
        "entities_without_constraints": stripped_entities,
        "obligation_drop_suspected": bool(lost_modals) and bool(stripped_entities),
    }
