# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-self-editing-context-from-silently-deleting-the-evidence-it-needs-to-justify-its-own-edits.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-self-editing-context-from-silently-deleting-the-evidence-it-needs-to-justify-its-own-edits.warrant.json
# Markdown SHA-256:   599117049417aeda31e7550cdf20dc77a494a44fea7cc45a158d09c37e31bd03
# Code AST SHA-256:   85ae0af3a27d133d8e8fe64e6392db7d40035c955ee86e309e7eead997fc3565
# Verified Classes:   ProvenanceLossError, Claim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ProvenanceLossError(RuntimeError):
    """Raised when a context rewrite retains a claim but drops its warrant."""
    pass


@dataclass(frozen=True)
class Claim:
    text: str
    source_id: str | None      # resolvable reference to the span that justified it
    qualifier: str | None      # scope / expiry, e.g. "staging, 2026-11-13"
    verified: bool


def commit_rewrite(original: list[Claim], digest: list[Claim]) -> list[Claim]:
    """
    Validate that a destructive rewrite preserves falsifiability.
    A retained claim must keep its source_id and qualifier, or be
    explicitly downgraded to unverified. Silent promotion is rejected.
    """
    by_text = {c.text: c for c in original}
    committed: list[Claim] = []
    for d in digest:
        prior = by_text.get(d.text)
        if prior is None:
            # New assertion introduced by the editor itself: must be sourced.
            if d.source_id is None:
                raise ProvenanceLossError(
                    f"digest introduced unsourced claim: {d.text!r}"
                )
            committed.append(d)
            continue
        if prior.source_id is not None and d.source_id is None:
            raise ProvenanceLossError(
                f"claim {d.text!r} lost its source_id during rewrite "
                f"(was {prior.source_id!r}); downgrade explicitly instead"
            )
        if prior.qualifier is not None and d.qualifier is None:
            raise ProvenanceLossError(
                f"claim {d.text!r} lost its qualifier {prior.qualifier!r}; "
                "compression must not widen scope"
            )
        if d.verified and not prior.verified and d.source_id is None:
            raise ProvenanceLossError(
                f"claim {d.text!r} promoted to verified without a warrant"
            )
        committed.append(d)
    return committed
