# 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-episode-and-the-pruning-scorer-inherits-the-rewritten-policy-as-ground-truth.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-mid-episode-and-the-pruning-scorer-inherits-the-rewritten-policy-as-ground-truth.warrant.json
# Markdown SHA-256:   6df7a877f620a18d6c000873f00b0ff60e292df3ef4acbfe53e250356e8e5830
# Code AST SHA-256:   d9fa06ca01f0cdf99c77caf859e831091f4cd89a3a16cd442bd767d2a367e67f
# Verified Classes:   PolicyDriftError, Span, ContextPolicy, PolicyStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class PolicyDriftError(RuntimeError):
    """Raised when a proposed context-policy revision would move the scorer's
    reference frame downstream of the context it prunes."""


@dataclass
class Span:
    turn: int
    provenance: Literal["raw", "derived"]
    load_bearing: bool = False


@dataclass
class ContextPolicy:
    keep_threshold: float
    salience_weights: dict[str, float]
    revision: int = 0
    rationale: str = ""


@dataclass
class PolicyStore:
    # Pinned: never lives in the prunable region.
    current: ContextPolicy
    baseline: ContextPolicy
    history: list[ContextPolicy] = field(default_factory=list)


def propose_revision(store: PolicyStore, proposed: ContextPolicy,
                     shadow_transcript: list[Span]) -> ContextPolicy:
    """Adopt a model-authored policy revision only if it survives a replay
    against a held-out shadow transcript that the proposing model never saw.
    """
    # Guard 1: the rationale must not cite the pruned state as evidence.
    drift_markers = ("already condensed", "already summarized", "redundant",
                     "further raw", "no longer needed")
    if any(m in proposed.rationale.lower() for m in drift_markers):
        raise PolicyDriftError(
            f"revision {proposed.revision} rationale cites pruned state as "
            f"evidence: {proposed.rationale!r}"
        )

    # Guard 2: replay the proposed policy against the shadow transcript.
    # A load-bearing raw span that the new policy would drop is a hard stop.
    dropped_load_bearing = [
        s for s in shadow_transcript
        if s.provenance == "raw"
        and s.load_bearing
        and proposed.keep_threshold > store.current.keep_threshold
    ]
    if dropped_load_bearing:
        raise PolicyDriftError(
            f"revision {proposed.revision} would drop {len(dropped_load_bearing)} "
            f"load-bearing raw spans (turns "
            f"{[s.turn for s in dropped_load_bearing]}); "
            f"threshold {store.current.keep_threshold} -> {proposed.keep_threshold}"
        )

    # Guard 3: salience weights may not fall monotonically across revisions
    # toward zero on any evidence class.
    for cls, w in proposed.salience_weights.items():
        base = store.baseline.salience_weights.get(cls, 0.0)
        if base > 0 and w < 0.25 * base:
            raise PolicyDriftError(
                f"salience weight for {cls!r} drifted to {w} "
                f"(baseline {base}); class effectively pruned"
            )

    store.history.append(store.current)
    store.current = proposed
    return proposed
