# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-pruning-policy-into-a-state-it-can-no-longer-evaluate.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-pruning-policy-into-a-state-it-can-no-longer-evaluate.warrant.json
# Markdown SHA-256:   a98cbc30775def56f5fc0779b7c0379ab9bc54f0ec4363a24b25be39d3695cc2
# Code AST SHA-256:   4fb0166c64377486ebc1e4c21488a4e60ae21b2698777adddd0ff0d8a1d63ce6
# Verified Classes:   PolicyProvenanceError, Rule, ContextState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PolicyProvenanceError(RuntimeError):
    """Raised when a self-authored policy edit would evict its own justification."""


@dataclass
class Rule:
    rule_id: str
    text: str
    reason_turn: int          # turn ID that motivated this rule; pinned, never evictable
    may_collapse: set[int]    # turn IDs this rule is permitted to summarize/evict


@dataclass
class ContextState:
    rules: list[Rule] = field(default_factory=list)
    pinned_turns: set[int] = field(default_factory=set)

    def pinned(self) -> set[int]:
        # Every rule's provenance anchor is pinned against eviction (C3).
        return self.pinned_turns | {r.reason_turn for r in self.rules}


def apply_policy_edit(state: ContextState, new_rule: Rule, evicting: set[int]) -> ContextState:
    """
    Attempt to install a model-authored rule that also evicts `evicting`.
    Rejects any edit that collapses a turn still needed to justify an existing
    or the new rule, or that collapses a similarity group without a discriminator.
    """
    protected = state.pinned()

    # The new rule must not eat its own reason.
    if new_rule.reason_turn in new_rule.may_collapse:
        raise PolicyProvenanceError(
            f"rule {new_rule.rule_id} would collapse its own provenance turn "
            f"{new_rule.reason_turn}; justification must live outside the evicted set"
        )

    # No existing rule's anchor may fall inside the eviction span.
    clobbered = protected & evicting
    if clobbered:
        raise PolicyProvenanceError(
            f"edit evicts provenance turns {sorted(clobbered)} still cited by "
            f"existing rules; correction chain would be severed"
        )

    # Similarity-based collapse requires a preserved discriminator per group.
    if new_rule.may_collapse and not _has_discriminator(new_rule, evicting):
        raise PolicyProvenanceError(
            f"rule {new_rule.rule_id} collapses a similarity group with no "
            f"declared discriminator field; distinct payloads would be lost"
        )

    state.rules.append(new_rule)
    return state


def _has_discriminator(rule: Rule, evicting: set[int]) -> bool:
    # Placeholder: real check inspects the rule text for a named distinguishing
    # field and verifies that field survives in the collapsed summary.
    return "discriminator:" in rule.text
