# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-its-own-context-pruning-policy-as-a-versioned-artifact-rather-than-a-stateless-transformation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-its-own-context-pruning-policy-as-a-versioned-artifact-rather-than-a-stateless-transformation.warrant.json
# Markdown SHA-256:   3323d22fb4f09be8bca376afa8c3d9270fe2fa6eab93dd2e4e70c5e16d3c34e6
# Code AST SHA-256:   5bc19d177b8ea3d57048a3763887a472df2975409d860322b836b5b396d4773e
# Verified Classes:   UnattributablePolicyEdit, PruningPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnattributablePolicyEdit(RuntimeError):
    """Raised when a self-editing pruning policy is modified against feedback
    that cannot be attributed to a specific pruned segment class, or when
    pruned evidence is not re-admissible. Editing under these conditions
    creates an unobservable blind spot in the policy."""
    pass


class PruningPolicy:
    def __init__(self, threshold, weights, version=0):
        self.threshold = threshold
        self.weights = dict(weights)
        self.version = version
        self.pruned_segments = {}   # segment_id -> (segment, policy_version)
        self.edit_log = []          # (version, trigger_signal, attributed_segment_id)

    def prune(self, segments):
        kept, dropped = [], []
        for seg in segments:
            score = sum(self.weights.get(f, 0.0) * v for f, v in seg["features"].items())
            if score < self.threshold:
                self.pruned_segments[seg["id"]] = (seg, self.version)
                dropped.append(seg["id"])
            else:
                kept.append(seg)
        return kept, dropped

    def readmit(self, segment_id):
        # Re-admission is the invariant that makes self-editing safe.
        entry = self.pruned_segments.get(segment_id)
        if entry is None:
            raise UnattributablePolicyEdit(
                f"segment {segment_id} not re-admissible; policy blind spots are unobservable"
            )
        return entry[0]

    def edit(self, trigger_signal, attributed_segment_id, new_threshold=None, weight_delta=None,
             min_observations=3, observed_count=0):
        # Gate 1: feedback must be attributable to a specific pruned segment class.
        if attributed_segment_id is None:
            raise UnattributablePolicyEdit(
                "policy edit rejected: feedback is not attributable to a pruned segment "
                "(likely a reasoning/tool error misrouted to pruning)"
            )
        # Gate 2: the attributed segment must still be re-admissible.
        if attributed_segment_id not in self.pruned_segments:
            raise UnattributablePolicyEdit(
                f"policy edit rejected: attributed segment {attributed_segment_id} "
                "was destructively pruned; cannot verify the edit against evidence"
            )
        # Gate 3: bounded edit rate—require enough independent observations.
        if observed_count < min_observations:
            raise UnattributablePolicyEdit(
                f"policy edit rejected: {observed_count} < {min_observations} observations; "
                "editing on noise guarantees drift"
            )
        self.version += 1
        if new_threshold is not None:
            self.threshold = new_threshold
        if weight_delta:
            for f, d in weight_delta.items():
                self.weights[f] = self.weights.get(f, 0.0) + d
        self.edit_log.append((self.version, trigger_signal, attributed_segment_id))
        return self.version
