# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-refuse-a-self-editing-context-policy-that-has-silently-converted-salience-scoring-into-a-self-reinforcing-attractor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-refuse-a-self-editing-context-policy-that-has-silently-converted-salience-scoring-into-a-self-reinforcing-attractor.warrant.json
# Markdown SHA-256:   a5ec0453bfbfb663780d55266b2bad129c44bf1e2ce6bf7bbed26669c238a384
# Code AST SHA-256:   0efe479962f266a122ef00c04514fcb3c7cf224ba55ce5df9e29f238ea703792
# Verified Classes:   SelfReinforcingPolicyError, ContextItem, RubricRewrite
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from statistics import pstdev


class SelfReinforcingPolicyError(RuntimeError):
    """Raised when a self-authored context policy would close its own feedback loop."""


@dataclass
class ContextItem:
    key: str
    salience: float
    pinned: bool = False
    is_canary: bool = False


@dataclass
class RubricRewrite:
    cited_keys: list[str]
    evicts: list[str]
    changes_definition: bool
    new_scores: dict[str, float] = field(default_factory=dict)


SALIENCE_VARIANCE_FLOOR = 0.10


def validate_rewrite(items: list[ContextItem], rewrite: RubricRewrite) -> None:
    retained = [i for i in items if i.key not in rewrite.evicts]

    # 1. Self-erasing justification: cited evidence is being evicted.
    erased = set(rewrite.cited_keys) & set(rewrite.evicts)
    if erased:
        raise SelfReinforcingPolicyError(
            f"rewrite cites and evicts the same items: {sorted(erased)}"
        )

    # 2. Definition change invalidates all prior scores.
    if rewrite.changes_definition:
        unpinned = [i.key for i in items if not i.pinned]
        if unpinned:
            raise SelfReinforcingPolicyError(
                "definition change requires all prior-scored items pinned; "
                f"unpinned: {unpinned[:5]}"
            )

    # 3. Homogeneity check on the retained set.
    if len(retained) >= 3:
        sigma = pstdev(i.salience for i in retained)
        if sigma < SALIENCE_VARIANCE_FLOOR:
            raise SelfReinforcingPolicyError(
                f"retained salience sigma {sigma:.3f} < {SALIENCE_VARIANCE_FLOOR}; "
                "attractor convergence, not quality"
            )

    # 4. Canary survival: at least one low-salience load-bearing item remains.
    if not any(i.is_canary for i in retained):
        raise SelfReinforcingPolicyError(
            "no canary survived; rubric has consumed its own test set"
        )

    # 5. Justification must be pinned through the next cycle.
    for key in rewrite.cited_keys:
        item = next((i for i in items if i.key == key), None)
        if item is None or not item.pinned:
            raise SelfReinforcingPolicyError(
                f"cited justification item {key!r} not pinned for next cycle"
            )


def apply_self_edit(items: list[ContextItem], rewrite: RubricRewrite) -> list[ContextItem]:
    validate_rewrite(items, rewrite)
    return [i for i in items if i.key not in rewrite.evicts]
