# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-coherence-when-a-context-window-pruner-re-ranks-a-message-that-is-load-bearing-for-a-later-rewrite-the-re-rank-rewrite-order.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-coherence-when-a-context-window-pruner-re-ranks-a-message-that-is-load-bearing-for-a-later-rewrite-the-re-rank-rewrite-order.warrant.json
# Markdown SHA-256:   28bc978807072c539ab3087c656bd3fba8bfa2424694c620ca595f52bb88c57d
# Code AST SHA-256:   b62d854f89f960dfee73bf427d22d9ed6856dac45792aa43ef97ba32e472ff94
# Verified Classes:   ContextInvariantError, Message, ObligationSet
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ContextInvariantError(RuntimeError):
    """Raised when a self-editing context window would drop an obligation-bearing span."""
    pass

@dataclass
class Message:
    mid: str
    text: str
    relevance: float

@dataclass
class ObligationSet:
    spans: dict[str, list[str]] = field(default_factory=dict)  # mid -> pinned spans

    def add(self, mid: str, span: str) -> None:
        self.spans.setdefault(mid, []).append(span)

    def covers(self, mid: str) -> bool:
        return mid in self.spans

def extract_obligations(msg: Message, patterns: Iterable[str]) -> list[str]:
    # Cheap, non-model scan for load-bearing spans (negations, identifiers, regions).
    hits = []
    low = msg.text.lower()
    for p in patterns:
        if p in low:
            hits.append(p)
    return hits

def prune_and_rewrite(
    messages: list[Message],
    threshold: float,
    obligations: ObligationSet,
    patterns: Iterable[str],
) -> str:
    survivors: list[Message] = []
    for m in messages:
        found = extract_obligations(m, patterns)
        for span in found:
            obligations.add(m.mid, span)
        if m.relevance >= threshold:
            survivors.append(m)
        else:
            # Selection may drop the body, but only if obligations were captured.
            if not obligations.covers(m.mid) and found:
                raise ContextInvariantError(
                    f"message {m.mid} dropped with uncaptured obligation spans {found}"
                )
    # Rewrite is constructed from survivors PLUS the pinned obligation spans,
    # so a dropped carrier's constraints still reach the rewrite.
    pinned = [s for spans in obligations.spans.values() for s in spans]
    digest = "\n".join(m.text for m in survivors)
    if pinned:
        digest += "\n[PINNED OBLIGATIONS]\n" + "\n".join(pinned)
    return digest

def guarded_prune(messages, threshold, obligations, patterns):
    # Enforce the ordering invariant explicitly before any destructive rewrite.
    for m in messages:
        if m.relevance < threshold:
            found = extract_obligations(m, patterns)
            if found and not obligations.covers(m.mid):
                raise ContextInvariantError(
                    f"re-rank/rewrite ordering violated at {m.mid}; "
                    "obligation pass must run before selection drops the carrier"
                )
    return prune_and_rewrite(messages, threshold, obligations, patterns)
