# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-prunes-the-provenance-of-a-still-live-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-prunes-the-provenance-of-a-still-live-constraint.warrant.json
# Markdown SHA-256:   2787c70061352867797466dfb7d3af3dfd22cbaf258069c65da8933577b08268
# Code AST SHA-256:   62f13a05c4109b85740c9418c34fb18f4e7f1e2f69e25f94727a4e237dddfebd
# Verified Classes:   ProvenanceEvictionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceEvictionError(RuntimeError):
    """Raised when a self-editing context rewrite retains a constraining
    proposition but drops its modality or warrant, converting a binding
    constraint into an unanchored assertion."""
    pass


MODALITIES = {"hard", "soft", "hypothesis", "resolved"}


def verify_rewrite(pre_window: list[dict], post_window: list[dict]) -> None:
    """
    Enforce the modality-bearing provenance invariant across a compaction pass.

    Each segment is expected to carry:
      - text: str
      - constrains: bool           (does it restrict action?)
      - modality: str | None       (hard/soft/hypothesis/resolved)
      - warrant: str | None        (id of authorizing instruction/observation)
      - checkable: bool            (can compliance still be tested?)

    Raises ProvenanceEvictionError if any constraining proposition survives
    into post_window without its modality, warrant, or checkability.
    """
    pre_constraints = {
        s["text"]: s for s in pre_window if s.get("constrains")
    }

    for seg in post_window:
        if not seg.get("constrains"):
            continue
        # A retained constraint must still declare what kind of thing it is.
        if seg.get("modality") not in MODALITIES:
            raise ProvenanceEvictionError(
                f"Retained constraint lost modality: {seg['text']!r}. "
                f"Rewrite de-modalized a binding proposition; it will be "
                f"treated as advisory or absolute with no authority record."
            )
        # A retained constraint must still name what authorizes it.
        if not seg.get("warrant"):
            raise ProvenanceEvictionError(
                f"Retained constraint lost warrant: {seg['text']!r}. "
                f"Originating instruction was evicted without re-attachment; "
                f"agent can quote the number but not its hardness."
            )
        # A retained constraint must remain testable for compliance.
        if not seg.get("checkable"):
            raise ProvenanceEvictionError(
                f"Retained constraint is no longer checkable: {seg['text']!r}. "
                f"Bound or precondition was merged away; compliance cannot "
                f"be verified post-rewrite."
            )

    # Detect silent weakening: a hard constraint in pre that reappears in post
    # only as soft or as a merged directive with no hard clause.
    for text, pre_seg in pre_constraints.items():
        if pre_seg.get("modality") == "hard":
            survivors = [s for s in post_window if text in s.get("text", "")]
            if survivors and all(s.get("modality") != "hard" for s in survivors):
                raise ProvenanceEvictionError(
                    f"Hard constraint {text!r} reappears only as "
                    f"{[s.get('modality') for s in survivors]}; rewrite "
                    f"weakened modality without authorization."
                )


def compact(window: list[dict], scorer, floor: float) -> list[dict]:
    """Model-driven rewrite that pins low-salience-but-binding constraints."""
    rewritten = []
    for seg in window:
        score = scorer(seg)
        # Pin constraints whose salience decayed because they are being obeyed.
        if seg.get("constrains") and seg.get("modality") == "hard":
            rewritten.append(seg)
            continue
        if score < floor:
            continue  # evict non-constraining content only
        rewritten.append(seg)
    verify_rewrite(window, rewritten)
    return rewritten
