# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-pruning-policy-has-silently-rewritten-the-evidence-it-is-about-to-cite.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-pruning-policy-has-silently-rewritten-the-evidence-it-is-about-to-cite.warrant.json
# Markdown SHA-256:   d648725ae79115ba2d4fa0f8272bbd9149f6993429060f241d41baadd9dc0061
# Code AST SHA-256:   8c17b9fee5e1782f0a80e751bbb067dbbf3a6f9cc5d76e09a252ea3c1e451a9f
# Verified Classes:   ContextProvenanceError, Span, ContextStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ContextProvenanceError(RuntimeError):
    """Raised when a claim cites a lossy-compressed span whose original
    cannot be verified to contain the asserted content."""
    pass


class Span:
    def __init__(self, source_id: str, byte_range: tuple[int, int],
                 text: str, lossy: bool = False, compression_turn: int | None = None):
        self.source_id = source_id
        self.byte_range = byte_range
        self.text = text
        self.lossy = lossy
        self.compression_turn = compression_turn


class ContextStore:
    """Holds originals keyed by source_id; derivatives are separate spans."""
    def __init__(self):
        self._originals: dict[str, str] = {}

    def register_original(self, source_id: str, text: str) -> None:
        self._originals[source_id] = text

    def fetch_original(self, source_id: str) -> str:
        if source_id not in self._originals:
            raise ContextProvenanceError(
                f"original for source_id={source_id!r} not addressable; "
                "compression was a mutation, not a view"
            )
        return self._originals[source_id]


def resolve_citation(claim_text: str, cited: Span, store: ContextStore) -> str:
    """Resolve a model citation to authoritative bytes. Reject if the cited
    span is lossy and the original does not support the claim."""
    if not cited.lossy:
        return cited.text

    original = store.fetch_original(cited.source_id)
    lo, hi = cited.byte_range
    window = original[lo:hi]

    # Extract the load-bearing token(s) the claim asserts, e.g. a number.
    asserted = [tok for tok in claim_text.split() if any(c.isdigit() for c in tok)]
    for tok in asserted:
        if tok not in window:
            raise ContextProvenanceError(
                f"claim asserts {tok!r} but original {cited.source_id}"
                f"[{lo}:{hi}] does not contain it; cited span was lossy "
                f"(compressed at turn {cited.compression_turn}). "
                "Downgrade claim to inferred and rehydrate original."
            )
    return window


# --- failure trace from the observed run ---
store = ContextStore()
store.register_original("doc_7", "... termination requires 60 days written notice ...")

summary = Span(
    source_id="doc_7", byte_range=(0, 1400),
    text="• payment net-30\n• termination: notice required\n• governing law: DE",
    lossy=True, compression_turn=4,
)

claim = "the contract specifies a 30-day termination notice"
try:
    resolve_citation(claim, summary, store)
except ContextProvenanceError as e:
    # This is the desired outcome: loud, recoverable, not silent.
    print(f"REJECTED: {e}")
    raise ContextProvenanceError(
        "citation through lossy span failed provenance check; "
        "force-rehydrate doc_7[0:1400] into window before continuing"
    ) from e
