# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-eviction-policy-rewrite-policy-interference-when-a-self-editing-context-window-rewrites-tokens-that-the-eviction-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-eviction-policy-rewrite-policy-interference-when-a-self-editing-context-window-rewrites-tokens-that-the-eviction-policy.warrant.json
# Markdown SHA-256:   e63d4f00f9d23d69bb8775f57ec99f056f64f0dece28385ab93f461af7bdfe74
# Code AST SHA-256:   607e4cf6dde140ffeed2ee8653a1e0b9e9ac8f1d0459c5ac95c967d66fa124db
# Verified Classes:   RewriteEvictionInterference
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RewriteEvictionInterference(RuntimeError):
    """Raised when an in-place rewrite destroys the surface features that justified a span's retention."""
    pass


def apply_rewrite(span: dict, rewritten_text: str, degradation_threshold: float = 0.15) -> dict:
    """
    span: {
        "id": str,
        "text": str,
        "salience": float,           # score at retention time
        "predicates": list[str],     # literals/negations that justified retention
        "synthesized": bool,
    }
    Returns the span with rewritten text, or raises if the rewrite is unsafe.
    """
    missing = [p for p in span["predicates"] if p not in rewritten_text]
    if missing:
        raise RewriteEvictionInterference(
            f"Span {span['id']}: rewrite dropped load-bearing predicate(s) {missing!r}; "
            f"retention was justified by surface features the rewrite removed. "
            f"Downgrade to evict-and-replace or reject rewrite."
        )

    # Re-score proxy: if the rewrite is much shorter and predicate coverage is thin,
    # treat as degraded and exclude from eviction candidates until revalidated.
    length_ratio = len(rewritten_text) / max(len(span["text"]), 1)
    if length_ratio < (1.0 - degradation_threshold) and not span["predicates"]:
        span["rewrite_degraded"] = True
        span["exclude_from_eviction"] = True

    if span.get("synthesized") and not span["predicates"]:
        # Phantom-constraint guard: rewrite injected content with no user-stated basis.
        raise RewriteEvictionInterference(
            f"Span {span['id']}: rewrite introduced synthesized constraint with no "
            f"user-stated predicate; mark synthesized=True and require audit before retention."
        )

    span["text"] = rewritten_text
    span["salience"] = None  # force re-score before next eviction cycle
    return span


def eviction_cycle(spans: list[dict], budget: int) -> list[dict]:
    for s in spans:
        if s.get("salience") is None:
            # Invariant: no span enters eviction without a post-rewrite score.
            raise RewriteEvictionInterference(
                f"Span {s['id']} has no valid salience (rewritten without re-score). "
                f"Re-score before eviction; refusing to evict on stale feature vectors."
            )
    ranked = sorted(spans, key=lambda s: (s.get("exclude_from_eviction", False), s["salience"]), reverse=True)
    return ranked[:budget]
