# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-policies-from-erasing-the-evidence-they-cite.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-policies-from-erasing-the-evidence-they-cite.warrant.json
# Markdown SHA-256:   74d7c056b894cadd23ec880bbc42616b700eb26008075a1f3e6fc405724169fb
# Code AST SHA-256:   68d0c541c5eefbcf90af01e9f021f21ca79832e0785e4da74702e15668f71344
# Verified Classes:   CitationClosureViolation, Span, LiveReference, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CitationClosureViolation(RuntimeError):
    """Raised when a context rewrite would orphan a live reference."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    content: str


@dataclass
class LiveReference:
    ref_id: str
    target_span_id: str  # stable identity, never a description
    transitive: bool = True


@dataclass
class ContextWindow:
    snapshot_id: str
    spans: dict[str, Span] = field(default_factory=dict)
    references: list[LiveReference] = field(default_factory=list)


def _resolve_transitive(ref: LiveReference, surviving: set[str],
                        span_to_cited: dict[str, set[str]]) -> bool:
    """A reference resolves if its span survives, or (transitively) if a
    surviving summary span cites it."""
    if ref.target_span_id in surviving:
        return True
    if not ref.transitive:
        return False
    # walk one hop: surviving spans that cite the target
    for sid in surviving:
        if ref.target_span_id in span_to_cited.get(sid, set()):
            return True
    return False


def apply_rewrite(window: ContextWindow,
                  policy_snapshot_id: str,
                  new_spans: dict[str, Span],
                  span_to_cited: dict[str, set[str]]) -> ContextWindow:
    # Invariant 1: draft-apply atomicity — policy must target the live snapshot.
    if policy_snapshot_id != window.snapshot_id:
        raise CitationClosureViolation(
            f"stale policy: drafted against {policy_snapshot_id!r}, "
            f"live window is {window.snapshot_id!r}; re-draft required"
        )

    surviving = set(new_spans.keys())

    # Invariant 2: citation closure — every live ref must resolve by identity,
    # transitively through surviving summaries.
    for ref in window.references:
        if not _resolve_transitive(ref, surviving, span_to_cited):
            raise CitationClosureViolation(
                f"reference {ref.ref_id!r} would dangle: target span "
                f"{ref.target_span_id!r} neither survives nor is cited by a "
                f"surviving span; retire the obligation or pin the span"
            )

    # Invariant 3: preservation is verified, not declared. Any span the policy
    # claimed to preserve must be byte-identical in the result.
    for sid, span in window.spans.items():
        if sid in surviving and new_spans[sid].content != span.content:
            raise CitationClosureViolation(
                f"span {sid!r} was marked preserved but content mutated"
            )

    return ContextWindow(
        snapshot_id=f"{window.snapshot_id}+rewrite",
        spans=new_spans,
        references=list(window.references),
    )
