# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-silently-corrupted-its-working-state-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-silently-corrupted-its-working-state-invariant.warrant.json
# Markdown SHA-256:   d0c65e6e6dcea21882de7a2452f3a78c10e79db8dc4ebd36107deb0d634d59b4
# Code AST SHA-256:   404c21fd542100ad1669f37e57afd071e47fb67e4eb38c938d88422992c24a5e
# Verified Classes:   CompactionConstraintViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CompactionConstraintViolation(RuntimeError):
    """Raised when a constraint-bearing query resolves to a lossy summary
    instead of raw source, or when a constraint ledger entry is missing."""
    pass


CONSTRAINT_MARKERS = ("must", "must not", "never", "before", "unless",
                      "only if", "==", "<=", ">=", "forbidden")


def is_constraint_bearing(query: str) -> bool:
    q = query.lower()
    return any(marker in q for marker in CONSTRAINT_MARKERS)


def resolve_context(query: str, retriever, ledger) -> dict:
    """Resolve a query to context, enforcing the raw-or-fail-closed rule
    for constraint-bearing queries. Never returns a summary for a
    constraint query."""
    if is_constraint_bearing(query):
        raw_hits = retriever.search(query, provenance="raw", k=5)
        if not raw_hits:
            raise CompactionConstraintViolation(
                f"constraint-bearing query {query!r} has no raw-source hit; "
                f"refusing to fall back to lossy summary"
            )
        for hit in raw_hits:
            if hit.provenance != "raw":
                raise CompactionConstraintViolation(
                    f"retriever returned provenance={hit.provenance!r} "
                    f"for constraint query {query!r}"
                )
        return {"mode": "raw", "hits": raw_hits, "ledger": ledger.snapshot()}

    hits = retriever.search(query, k=5)
    return {"mode": "any", "hits": hits, "ledger": ledger.snapshot()}


def compact(turns, summarizer, ledger) -> str:
    """Compact turns, but extract constraints to the ledger first.
    Aborts if any constraint token would enter the lossy channel
    without a verbatim ledger entry."""
    for turn in turns:
        for line in turn.text.splitlines():
            if is_constraint_bearing(line):
                if not ledger.contains_verbatim(line):
                    if not ledger.append_verbatim(line, source=turn.index):
                        raise CompactionConstraintViolation(
                            f"failed to ledger constraint from turn "
                            f"{turn.index}: {line!r}"
                        )
    summary = summarizer(turns)
    if ledger.is_empty() and any(is_constraint_bearing(t.text) for t in turns):
        raise CompactionConstraintViolation(
            "turns contain constraints but ledger is empty after compaction"
        )
    return summary
