# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-mid-task-and-the-pruner-deletes-the-evidence-it-needs-to-justify-the-next-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-mid-task-and-the-pruner-deletes-the-evidence-it-needs-to-justify-the-next-rewrite.warrant.json
# Markdown SHA-256:   0837a8473043bcc584d74588134a4baff9b1710a3e92154328601d8afe14b514
# Code AST SHA-256:   32898322a81c6d2e25f483cc42714bc70faf7c27f8ee3f760f600999be720cd3
# Verified Classes:   PolicyEditRejected, Policy, RationaleRecord, PolicyLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PolicyEditRejected(RuntimeError):
    """Raised when a self-edit would make its own justification evictable,
    or when the edit is an unjustifiable oscillation."""
    pass


@dataclass
class Policy:
    evict_below_salience: float
    protect_classes: frozenset
    rewrite_operator: str

    def salience_of(self, record_class: str, raw_salience: float) -> float:
        # Protected classes are pinned above any watermark.
        return 1.0 if record_class in self.protect_classes else raw_salience


@dataclass
class RationaleRecord:
    record_class: str
    raw_salience: float
    trigger_ref: str
    pre_policy: Policy


@dataclass
class PolicyLedger:
    entries: list = field(default_factory=list)

    def append(self, pre: Policy, post: Policy, trigger_ref: str) -> None:
        self.entries.append((pre, post, trigger_ref))

    def recent_targets(self, n: int = 4) -> set:
        return {e[1].evict_below_salience for e in self.entries[-n:]}


def apply_self_edit(
    current: Policy,
    proposed: Policy,
    rationale: RationaleRecord,
    ledger: PolicyLedger,
    oscillation_window: int = 4,
) -> Policy:
    # Gate 1: would the rationale survive under the *proposed* policy?
    effective = proposed.salience_of(rationale.record_class, rationale.raw_salience)
    if effective < proposed.evict_below_salience:
        raise PolicyEditRejected(
            f"self-referential edit: rationale class '{rationale.record_class}' "
            f"salience {effective:.2f} falls below proposed watermark "
            f"{proposed.evict_below_salience:.2f}; justification would be pruned "
            f"by its own patch (trigger={rationale.trigger_ref})"
        )

    # Gate 2: oscillation without surviving provenance.
    if (
        proposed.evict_below_salience in ledger.recent_targets(oscillation_window)
        and proposed.evict_below_salience != current.evict_below_salience
        and not any(
            e[2] == rationale.trigger_ref for e in ledger.entries[-oscillation_window:]
        )
    ):
        raise PolicyEditRejected(
            f"unjustifiable oscillation: target {proposed.evict_below_salience:.2f} "
            f"was held within last {oscillation_window} cycles but no surviving "
            f"rationale for the intervening change exists; cannot distinguish "
            f"revert from amnesia"
        )

    ledger.append(current, proposed, rationale.trigger_ref)
    return proposed
