# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-lossy-compaction-summary-has-silently-dropped-a-still-live-constraint-before-it-re-enters-the-tool-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-lossy-compaction-summary-has-silently-dropped-a-still-live-constraint-before-it-re-enters-the-tool-loop.warrant.json
# Markdown SHA-256:   cd9138a363afd75e90a363f99fdbaf9fbf272553947642945cd72c1b84be5fa0
# Code AST SHA-256:   c7c98e26b354d7664b8ca4f567dd4deb88888a3b3fad26efd8d304ac500d7ca4
# Verified Classes:   ModalCollapseError, Modality, ConstraintTuple
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Sequence


class ModalCollapseError(RuntimeError):
    """Raised when a compaction summary is about to be resumed against
    while live imperative constraints exist only in collapsed form."""


class Modality(Enum):
    MUST = "must"
    MUST_NOT = "must_not"
    SHOULD = "should"
    PREFER = "prefer"


@dataclass(frozen=True)
class ConstraintTuple:
    subject: str
    modality: Modality
    predicate: str
    scope: str
    expiry: str | None  # ISO date or None for no expiry
    expired: bool = False


def assert_resumable(
    summary_tokens: int,
    tuples: Sequence[ConstraintTuple],
    sidecar_injected: bool,
    current_step: int,
) -> None:
    """Gate re-entry into the tool loop after lossy compaction.

    The summary is prose and may have collapsed modal force. The tuple set
    is the binding contract. If any live tuple exists and the sidecar was
    not re-injected verbatim, resumption is unsafe regardless of how good
    the summary reads.
    """
    live = [t for t in tuples if not t.expired and t.modality in (
        Modality.MUST, Modality.MUST_NOT
    )]

    if not live:
        return  # purely descriptive window; lossy summary is safe

    if not sidecar_injected:
        raise ModalCollapseError(
            f"step {current_step}: {len(live)} live constraint(s) present but "
            f"sidecar not injected; summary alone cannot carry modal force. "
            f"First live: ({live[0].subject}, {live[0].modality.value}, "
            f"{live[0].predicate}, scope={live[0].scope})"
        )

    # Sidecar present: verify it was not itself truncated against budget.
    sidecar_budget = max(64, summary_tokens // 4)
    if len(live) * 18 > sidecar_budget:  # ~18 tokens per dense tuple
        raise ModalCollapseError(
            f"step {current_step}: sidecar would exceed {sidecar_budget} "
            f"tokens for {len(live)} live tuples; compaction must be split "
            f"into smaller windows rather than dropping obligations."
        )
