# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-self-editing-context-policy-refuse-to-rewrite-a-span-it-cannot-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-self-editing-context-policy-refuse-to-rewrite-a-span-it-cannot-re-derive.warrant.json
# Markdown SHA-256:   a45453abb1b65351ac9526f93d2ed6f37e9ab9ae44ca8c507a061c08d3ab5e44
# Code AST SHA-256:   4e99dedb3881e8b3880140e3e34d3e9e8e7a178c4c9a4bbb3daf9bb85b7dd8bc
# Verified Classes:   UnsafeContextEditError, Span, Edit
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UnsafeContextEditError(RuntimeError):
    """Raised when a model-authored edit would sever ground truth from the window."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    authored_by_model: bool          # True = model-generated, False = tool/user/host
    is_epistemic: bool = False        # contains hedging / uncertainty / correction
    is_negative_signal: bool = False  # error, contradiction, explicit correction
    recoverable: bool = True          # re-fetchable via idempotent tool call
    literals: frozenset[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class Edit:
    kind: str                         # "prune" | "rewrite" | "reweight"
    target_ids: tuple[str, ...]
    proposed_text: str = ""           # for rewrite
    new_priority: float | None = None # for reweight
    targets_edit_policy: bool = False


RETAIN_THRESHOLD = 0.25


def _non_model_spans(spans: Iterable[Span]) -> list[Span]:
    return [s for s in spans if not s.authored_by_model]


def _literals_in(text: str) -> frozenset[str]:
    import re
    return frozenset(re.findall(r"[A-Za-z0-9_:\-\.]{4,}", text))


def validate_edit(edit: Edit, window: list[Span]) -> None:
    """Reject edits that cannot be re-derived from non-model sources."""
    by_id = {s.span_id: s for s in window}

    if edit.targets_edit_policy:
        raise UnsafeContextEditError(
            "edit targets the edit policy itself; self-referential edits are structurally forbidden"
        )

    targets = []
    for tid in edit.target_ids:
        if tid not in by_id:
            raise UnsafeContextEditError(f"edit references unknown span {tid!r}")
        targets.append(by_id[tid])

    if edit.kind == "rewrite":
        for t in targets:
            if t.is_epistemic:
                raise UnsafeContextEditError(
                    f"refusing to rewrite epistemic span {t.span_id!r}: "
                    "its form (hedging/uncertainty) is its content"
                )
        provenance = set()
        for s in _non_model_spans(window):
            if s.span_id not in edit.target_ids:
                provenance |= s.literals or _literals_in(s.text)
        proposed = _literals_in(edit.proposed_text)
        unbacked = proposed - provenance
        if unbacked:
            raise UnsafeContextEditError(
                f"rewrite introduces literals not present in any non-model span: "
                f"{sorted(unbacked)}; a model may compress what it can point to, "
                "not what it can only remember"
            )

    elif edit.kind == "prune":
        for t in targets:
            if not t.recoverable:
                raise UnsafeContextEditError(
                    f"refusing to prune non-recoverable span {t.span_id!r}: "
                    "cannot evict what cannot be re-fetched"
                )

    elif edit.kind == "reweight":
        if edit.new_priority is None:
            raise UnsafeContextEditError("reweight requires new_priority")
        for t in targets:
            if t.is_negative_signal and edit.new_priority < RETAIN_THRESHOLD:
                raise UnsafeContextEditError(
                    f"refusing to demote negative-signal span {t.span_id!r} "
                    f"to {edit.new_priority}: false retention costs tokens, "
                    "false demotion costs correctness"
                )

    else:
        raise UnsafeContextEditError(f"unknown edit kind {edit.kind!r}")


def apply_edits(window: list[Span], edits: list[Edit]) -> list[Span]:
    """Apply edits only if every one passes the boundary; otherwise fail atomically."""
    for e in edits:
        validate_edit(e, window)
    # ... deterministic application elided; boundary enforcement is the point
    return window
