# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-model-driven-context-pruning-with-the-invariant-that-no-rewrite-may-evict-a-live-dependency-of-an-in-flight-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-model-driven-context-pruning-with-the-invariant-that-no-rewrite-may-evict-a-live-dependency-of-an-in-flight-tool-call.warrant.json
# Markdown SHA-256:   93c26ce57ed0418e3d63eeb122020e179b41fcbab741c10a6a2bd7735a1a7aa6
# Code AST SHA-256:   96f82aa021a2fdb30a4aebb5e04065e1d6c94107dd29c50238d3dc3a413c1273
# Verified Classes:   DanglingContextReference, ContextMutator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DanglingContextReference(RuntimeError):
    """Raised when a context mutation would evict or rewrite a chunk
    that is a live dependency of an in-flight tool call."""
    pass


class ContextMutator:
    def __init__(self, chunks, live_refs):
        # chunks: dict[chunk_id -> str]
        # live_refs: dict[call_id -> set[chunk_id]] for pending calls
        self.chunks = dict(chunks)
        self.live_refs = {k: set(v) for k, v in live_refs.items()}

    def _pinned_closure(self):
        pinned = set()
        for refs in self.live_refs.values():
            pinned |= refs
        return pinned

    def apply_prune(self, chunk_id, score, threshold, rewrite=None):
        pinned = self._pinned_closure()
        if chunk_id in pinned:
            raise DanglingContextReference(
                f"chunk {chunk_id!r} is pinned by an in-flight call "
                f"(score={score}, threshold={threshold}); "
                f"mutation rejected regardless of relevance"
            )
        if score >= threshold and rewrite is None:
            return "kept"
        # Evict, or evict-then-insert for rewrites so no refs are inherited.
        del self.chunks[chunk_id]
        if rewrite is not None:
            new_id = f"{chunk_id}::rewritten::{len(self.chunks)}"
            self.chunks[new_id] = rewrite
            return new_id
        return None

    def resolve_call(self, call_id, result):
        if call_id not in self.live_refs:
            raise DanglingContextReference(
                f"call {call_id!r} has no tracked references; "
                f"cannot bind result safely"
            )
        refs = self.live_refs.pop(call_id)
        missing = [c for c in refs if c not in self.chunks]
        if missing:
            raise DanglingContextReference(
                f"call {call_id!r} resolved against evicted chunks {missing}; "
                f"result cannot be bound"
            )
        return {"call_id": call_id, "result": result, "bound_to": sorted(refs)}
