# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-saturation-in-a-self-pruning-context-window-before-it-destroys-its-own-audit-trail.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-saturation-in-a-self-pruning-context-window-before-it-destroys-its-own-audit-trail.warrant.json
# Markdown SHA-256:   615d5b5016c622d0deb591e0c04b3d2eb811c22667c33a2fa01f490480468990
# Code AST SHA-256:   a6ecdef4d9a1a3b0c6876e5aa602bd7d40cf5540a9016327be4fa9f44517ca24
# Verified Classes:   AuditTrailEvictionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AuditTrailEvictionError(RuntimeError):
    """Raised when a self-pruning pass would evict constitutive context."""
    pass


CONSTITUTIVE_MARKERS = ("error", "exception", "traceback", "503", "500", "failed",
                        "rejected", "diverged", "partial")


def classify_segment(segment: dict) -> str:
    text = segment["text"].lower()
    if segment.get("has_side_effect"):
        return "constitutive"
    if any(marker in text for marker in CONSTITUTIVE_MARKERS):
        return "constitutive"
    return "compressible"


def prune_context_window(segments: list[dict], threshold: float = 0.30) -> list[dict]:
    """Evict low-relevance compressible segments; pin constitutive ones."""
    kept, evicted = [], []
    for seg in segments:
        cls = classify_segment(seg)
        if cls == "constitutive":
            kept.append(seg)  # pinned regardless of score
            continue
        if seg["relevance"] < threshold:
            evicted.append(seg)
        else:
            kept.append(seg)

    # Invariant check: no constitutive segment may be evicted, and the
    # surviving window must not read more confident than the full trace.
    evicted_constitutive = [s for s in evicted if classify_segment(s) == "constitutive"]
    if evicted_constitutive:
        raise AuditTrailEvictionError(
            f"pruning would destroy {len(evicted_constitutive)} constitutive "
            f"segment(s); refusing mutation"
        )

    audit_scores = [s["relevance"] for s in segments if classify_segment(s) == "constitutive"]
    narrative_scores = [s["relevance"] for s in segments if classify_segment(s) == "compressible"]
    if audit_scores and narrative_scores:
        if max(audit_scores) < min(narrative_scores):
            raise AuditTrailEvictionError(
                "score inversion detected: audit-critical segments rank below "
                "narrative segments; pruning would inflate confidence"
            )
    return kept
