# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-when-the-pruner-s-own-relevance-scores-are-computed-against-a-context-it-is-sim.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-when-the-pruner-s-own-relevance-scores-are-computed-against-a-context-it-is-sim.warrant.json
# Markdown SHA-256:   25c6c2bd1e3b284001e4806c19909d9a577d2ea160f6951696c44a07749ebeb2
# Code AST SHA-256:   312dd8d0b91ed1e72020db240e7f4ef6897478723de3913e423f9ad6f958fd54
# Verified Classes:   PruneAliasingError, ContextBuffer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PruneAliasingError(RuntimeError):
    """Raised when a self-edit pass would score and mutate the same live buffer,
    or when retention obligations cannot be pinned independently of the scorer."""
    pass


class ContextBuffer:
    def __init__(self, segments, generation=0):
        self.segments = list(segments)
        self.generation = generation
        self.raw_count = sum(1 for s in segments if s.get("kind") == "raw")
        self.summary_count = sum(1 for s in segments if s.get("kind") == "summary")

    def summary_to_raw_ratio(self):
        if self.raw_count == 0:
            return float("inf")
        return self.summary_count / self.raw_count


def guarded_self_edit(buffer, scorer, obligations, pending_action_params,
                      ratio_threshold=0.60):
    """Execute a model-driven prune only if the snapshot-and-freeze invariant holds.
    Refuses (raises) rather than silently editing when aliasing is possible."""
    snapshot_generation = buffer.generation

    # 1. Retention obligations must be pinned from execution state, not from text.
    unpinned = [o for o in obligations if not o.get("segment_id")]
    if unpinned:
        raise PruneAliasingError(
            f"{len(unpinned)} retention obligation(s) lack a pinnable segment_id; "
            "scorer cannot be trusted to preserve them"
        )

    # 2. Self-referential scoring check: too many summaries means the scorer is
    #    measuring redundancy it created on prior passes.
    if buffer.summary_to_raw_ratio() > ratio_threshold:
        raise PruneAliasingError(
            f"summary/raw ratio {buffer.summary_to_raw_ratio():.2f} exceeds "
            f"{ratio_threshold:.2f}; relevance scores are self-referential, "
            "re-fetch raw evidence instead of pruning"
        )

    # 3. Score against the frozen snapshot, never the live buffer.
    scores = scorer.score(snapshot_generation, buffer.segments)

    # 4. Aliasing check: buffer must not have advanced during scoring.
    if buffer.generation != snapshot_generation:
        raise PruneAliasingError(
            "buffer generation advanced during scoring; scores are stale "
            "relative to the context they will be applied to"
        )

    # 5. Pin obligations regardless of score, then check sufficiency.
    pinned_ids = {o["segment_id"] for o in obligations}
    retained = [s for s in buffer.segments
                if s["id"] in pinned_ids or scores.get(s["id"], 0.0) >= 0.5]

    surviving_text = " ".join(s["text"] for s in retained)
    for param, candidates in pending_action_params.items():
        hits = [c for c in candidates if c in surviving_text]
        if len(hits) != 1:
            raise PruneAliasingError(
                f"post-prune context is ambiguous for parameter {param!r}: "
                f"{len(hits)} surviving interpretations {hits}; refusing to mutate"
            )

    # 6. Apply mutation to a copy, bump generation.
    new_buffer = ContextBuffer(retained, generation=buffer.generation + 1)
    return new_buffer


def run_self_edit(buffer, scorer, obligations, pending_action_params):
    try:
        return guarded_self_edit(buffer, scorer, obligations, pending_action_params)
    except PruneAliasingError as e:
        # Escalate; do not retry with a looser threshold.
        return {"status": "refused", "reason": str(e), "buffer": buffer}
