# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-the-same-context-segment-twice-and-still-lose-the-fact-it-was-trying-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-the-same-context-segment-twice-and-still-lose-the-fact-it-was-trying-to-preserve.warrant.json
# Markdown SHA-256:   1d1f31465949b8b89afb5d22741ce1993906b0b2653acf7bd56969e185fc790a
# Code AST SHA-256:   e95eeacb843f18237492b5c03d430bdfaa40ab06591d76502d7f91cfc8b57b56
# Verified Classes:   ContextPruneInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ContextPruneInvariantError(RuntimeError):
    """Raised when a self-edit prune pass violates monotonic retention of ledger facts."""
    pass


def apply_self_prune(window: list[dict], ledger: dict[str, dict], prune_fn) -> list[dict]:
    """
    Apply a model-driven prune pass with an idempotence guard.

    window: ordered context segments, each {'id', 'text', 'is_ledger_derivative'}
    ledger: append-only map of protected facts {fact_id: {'entity','relation','value','provenance'}}
    prune_fn: callable(window, protected_ids) -> new_window
    """
    protected_ids = set(ledger.keys())

    # Guard 1: no ledger derivative may be a prune target.
    for seg in window:
        if seg.get("is_ledger_derivative") and seg["id"] in protected_ids:
            if seg.get("prunable", False):
                raise ContextPruneInvariantError(
                    f"segment {seg['id']} is a ledger derivative but marked prunable"
                )

    new_window = prune_fn(window, protected_ids)

    # Guard 2: post-prune entailment check — every ledger fact must survive.
    joined = "\n".join(s["text"] for s in new_window).lower()
    for fact_id, fact in ledger.items():
        needle = str(fact["value"]).lower()
        if needle not in joined:
            raise ContextPruneInvariantError(
                f"prune pass dropped ledger fact {fact_id} "
                f"({fact['entity']}.{fact['relation']}={fact['value']}); "
                f"aborting to prior window state"
            )

    # Guard 3: hedges are facts — certainty qualifier must be retained verbatim.
    for fact_id, fact in ledger.items():
        if fact.get("certainty") in ("pending", "unconfirmed", "likely"):
            if fact["certainty"] not in joined:
                raise ContextPruneInvariantError(
                    f"prune pass stripped certainty qualifier '{fact['certainty']}' "
                    f"from fact {fact_id}; uncertainty promoted to assertion"
                )

    return new_window
