# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-self-pruning-when-the-relevance-reweighting-it-applies-to-its-own-context-is-the-only-signal-it-has-for-deciding-what-to-p.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-self-pruning-when-the-relevance-reweighting-it-applies-to-its-own-context-is-the-only-signal-it-has-for-deciding-what-to-p.warrant.json
# Markdown SHA-256:   91b6fb277ecd1598b80bd335dc99fcd7a329b3a770f5a919314b7d51b5b46765
# Code AST SHA-256:   601188eea0a4c4f6e942af159f294fadcc75c18daf8034418db68143ecdfad10
# Verified Classes:   SelfPruneWarrantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SelfPruneWarrantError(RuntimeError):
    """Raised when a self-editing context prune lacks an independent warrant
    for the eviction it authorizes (relevance scored by the consuming model,
    or constraint-bearing span evicted without promotion)."""
    pass


CONSTRAINT_PATTERNS = (
    "do not re-apply", "reversed", "retract", "minor units", "cents",
    "id=", "key=", "alias", "scale", "negat",
)


def _is_constraint_bearing(span: str) -> bool:
    low = span.lower()
    return any(p in low for p in CONSTRAINT_PATTERNS)


def authorize_prune(
    evicted_spans: list[str],
    scorer_id: str,
    reasoner_id: str,
    promoted_constraints: set[str],
    post_prune_coherence_delta: float,
    coherence_delta_threshold: float = 0.0,
) -> None:
    # 1. Provenance separation: the scorer must not be the consumer.
    if scorer_id == reasoner_id:
        raise SelfPruneWarrantError(
            f"relevance scorer {scorer_id!r} is the consuming reasoner; "
            "score is conditioned on the content it licenses to evict"
        )

    # 2. Constraint extraction must precede eviction.
    for span in evicted_spans:
        if _is_constraint_bearing(span) and span not in promoted_constraints:
            raise SelfPruneWarrantError(
                "evicted a constraint-bearing span without promoting it: "
                f"{span[:80]!r}"
            )

    # 3. Coherence rising because a contradiction was removed is a red flag.
    if post_prune_coherence_delta > coherence_delta_threshold:
        raise SelfPruneWarrantError(
            "post-prune coherence rose "
            f"({post_prune_coherence_delta:+.3f}); eviction may have removed "
            "the span whose absence manufactures consistency"
        )


def self_edit_context(
    context: list[str],
    relevance_scores: list[float],
    scorer_id: str,
    reasoner_id: str,
    promoted_constraints: set[str],
    evict_fraction: float = 0.30,
) -> list[str]:
    n_evict = max(1, int(len(context) * evict_fraction))
    ranked = sorted(range(len(context)), key=lambda i: relevance_scores[i])
    evicted_idx = set(ranked[:n_evict])
    evicted = [context[i] for i in evicted_idx]
    survivors = [context[i] for i in range(len(context)) if i not in evicted_idx]

    # Coherence delta must be measured against a frozen pre-prune baseline,
    # not re-scored by the same pass that proposed the prune.
    delta = _frozen_coherence_delta(context, survivors)
    authorize_prune(evicted, scorer_id, reasoner_id, promoted_constraints, delta)
    return survivors


def _frozen_coherence_delta(pre: list[str], post: list[str]) -> float:
    # Placeholder: real implementation compares against a baseline vector
    # captured before pruning began, never a fresh self-score.
    return 0.0
