# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-its-own-context-rewrite-as-a-destructive-edit-and-refuse-to-evict-a-segment-it-cannot-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-its-own-context-rewrite-as-a-destructive-edit-and-refuse-to-evict-a-segment-it-cannot-re-derive.warrant.json
# Markdown SHA-256:   e568f8e0650c3451b181ad35c9fbb62a7a6cb536746ab7956c3f427a9d609906
# Code AST SHA-256:   a289c1f3cec12a5eb0a2552d79d28b089a30ca6bd75a9672273811b6a5c48e3e
# Verified Classes:   DestructiveContextEdit
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DestructiveContextEdit(RuntimeError):
    """Raised when a context rewrite would evict single-carrier, non-monotonic state."""
    pass


def commit_rewrite(segments, eviction_threshold, external_store):
    """
    Gate a self-editing context rewrite.

    segments: list of dicts with keys
        - id, content, relevance_score
        - re_derivable (bool): content reconstructible from a source outside the rewrite
        - monotonic_relevance (bool): future relevance predictable from current score
        - provenance (dict): how the fact was obtained (tool, path, step)
    """
    to_evict = []
    to_externalize = []

    for seg in segments:
        if seg["relevance_score"] >= eviction_threshold:
            continue  # retained in context

        if seg["re_derivable"]:
            to_evict.append(seg)
            continue

        # Single-carrier state. Cannot score-evict.
        if seg["monotonic_relevance"]:
            # Predictably relevant or predictably dead; retain rather than risk.
            continue

        # Single-carrier AND non-monotonic relevance: destructive if evicted
        # without externalization.
        if external_store is None:
            raise DestructiveContextEdit(
                f"segment {seg['id']!r} is single-carrier with non-monotonic "
                f"relevance and no external store is available; eviction would "
                f"destroy state the agent cannot re-derive"
            )
        to_externalize.append(seg)

    # Externalize before eviction so a crash mid-rewrite cannot lose the fact.
    for seg in to_externalize:
        external_store.write(
            key=seg["id"],
            content=seg["content"],
            provenance=seg["provenance"],
            compression_passes=seg["provenance"].get("compression_passes", 0),
        )

    for seg in to_evict + to_externalize:
        if seg["provenance"].get("compression_passes", 0) >= MAX_COMPRESSION_PASSES:
            raise DestructiveContextEdit(
                f"segment {seg['id']!r} has survived {MAX_COMPRESSION_PASSES} "
                f"compression passes; further summarization exceeds fidelity floor"
            )

    return [s for s in segments if s not in to_evict and s not in to_externalize]


MAX_COMPRESSION_PASSES = 2
