# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-in-place-and-the-summarization-operator-destroys-the-evidence-needed-to-validate-itself.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-in-place-and-the-summarization-operator-destroys-the-evidence-needed-to-validate-itself.warrant.json
# Markdown SHA-256:   3b61d28890b6bbd10cf7a912d2e7745af85ae2acc58098086c572e630228983c
# Code AST SHA-256:   3d110b3229eb4b91bb64fe2c9d950f4b2caf8ffe7d63ced4df9363916e60e140
# Verified Classes:   RewriteBoundaryViolation, Span, Obligation, ContextLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RewriteBoundaryViolation(RuntimeError):
    """Raised when a destructive rewrite targets a span still cited by an open obligation."""
    pass


@dataclass
class Span:
    span_id: str
    content: str
    is_observation: bool          # True if derived from a tool result / ground truth
    summary: Optional[str] = None # set when destructively rewritten
    source_retained: bool = True


@dataclass
class Obligation:
    obligation_id: str
    cited_spans: set = field(default_factory=set)
    discharged: bool = False


class ContextLedger:
    def __init__(self):
        self.spans: dict[str, Span] = {}
        self.obligations: dict[str, Obligation] = {}

    def register_span(self, span: Span):
        self.spans[span.span_id] = span

    def cite(self, obligation_id: str, span_id: str):
        ob = self.obligations.setdefault(obligation_id, Obligation(obligation_id))
        ob.cited_spans.add(span_id)

    def open_citations(self, span_id: str) -> set:
        return {
            o.obligation_id
            for o in self.obligations.values()
            if not o.discharged and span_id in o.cited_spans
        }

    def destructive_rewrite(self, span_id: str, summary: str, retain_source: bool):
        span = self.spans[span_id]
        open_obs = self.open_citations(span_id)
        if open_obs and not retain_source:
            raise RewriteBoundaryViolation(
                f"span {span_id} is cited by open obligations {sorted(open_obs)}; "
                f"destructive rewrite without retained source would self-certify "
                f"a lossy claim as evidence. Refusing."
            )
        span.summary = summary
        span.source_retained = retain_source
        if not retain_source:
            span.content = ""  # source destroyed; only summary remains

    def resolve_for_verification(self, span_id: str) -> str:
        span = self.spans[span_id]
        if span.summary is not None:
            if not span.source_retained:
                raise RewriteBoundaryViolation(
                    f"verification attempted to resolve span {span_id} but only a "
                    f"summary survives; cannot verify against compressed evidence."
                )
            return span.content  # re-hydrate original, never the summary
        return span.content


def verify_obligation(ledger: ContextLedger, obligation_id: str):
    ob = ledger.obligations[obligation_id]
    for span_id in ob.cited_spans:
        evidence = ledger.resolve_for_verification(span_id)
        if evidence == "":
            raise RewriteBoundaryViolation(
                f"obligation {obligation_id}: empty evidence for {span_id}"
            )
    ob.discharged = True
