# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-the-self-referential-eviction-trap-in-model-driven-context-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-the-self-referential-eviction-trap-in-model-driven-context-pruning.warrant.json
# Markdown SHA-256:   bcc2ea6c40a266ca285a2dbef4222da5825260f0d4e0971b7695ed3940abca1c
# Code AST SHA-256:   bedcf23a3be1216f01a97bb45341b6313a36ef1464fede5c792678231acbf143
# Verified Classes:   PolicyEvictionTrap, Span, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PolicyEvictionTrap(RuntimeError):
    """Raised when a pruning pass would evict (or has evicted) its own policy artifacts."""
    pass


@dataclass
class Span:
    id: str
    text: str
    tags: tuple[str, ...] = ()
    pinned: bool = False


@dataclass
class ContextWindow:
    spans: list[Span] = field(default_factory=list)

    def policy_artifacts(self) -> list[Span]:
        return [s for s in self.spans if "POLICY" in s.tags or "RUBRIC" in s.tags]

    def policy_fingerprint(self) -> str:
        h = hashlib.sha256()
        for s in sorted(self.policy_artifacts(), key=lambda x: x.id):
            h.update(s.id.encode())
            h.update(s.text.encode())
            h.update(b"|")
        return h.hexdigest()


def run_pruning_pass(
    window: ContextWindow,
    candidate_ids: list[str],
    pruner_fn,
) -> list[str]:
    """
    Execute a model-driven pruning pass with a policy-integrity gate.

    Refuses to run if policy artifacts are present in the candidate set
    and not pinned. Verifies the policy fingerprint is unchanged after
    the pass; any change invalidates the pass.
    """
    policy_ids = {s.id for s in window.policy_artifacts()}
    unpinned_policy_in_candidates = [
        cid for cid in candidate_ids
        if cid in policy_ids
        and not next(s for s in window.spans if s.id == cid).pinned
    ]
    if unpinned_policy_in_candidates:
        raise PolicyEvictionTrap(
            f"pruning pass refused: unpinned policy artifacts in candidate set "
            f"{unpinned_policy_in_candidates}; pruner would be evaluating its own "
            f"governing rules. Pin policy spans or externalize the policy."
        )

    fp_before = window.policy_fingerprint()
    evicted = pruner_fn(window, candidate_ids)  # model-driven; may be wrong
    fp_after = window.policy_fingerprint()

    if fp_before != fp_after:
        raise PolicyEvictionTrap(
            f"pruning pass invalidated: policy fingerprint changed "
            f"{fp_before[:12]} -> {fp_after[:12]}; a policy artifact was mutated "
            f"or evicted mid-pass. Roll back to last known-good policy state."
        )
    return evicted
