# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-lossy-compaction-against-retrieval-fallback-before-the-summary-silently-outlives-its-source.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-lossy-compaction-against-retrieval-fallback-before-the-summary-silently-outlives-its-source.warrant.json
# Markdown SHA-256:   c4235786cfe87318870a4935551aad849cd8c126a16bf45302da1c80db35c662
# Code AST SHA-256:   944c3b295de54f41764594ff7767535b4b70657d40e5a6242e1bf85d719948b6
# Verified Classes:   ProvenanceViolation, FactClass, WorkingFact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ProvenanceViolation(RuntimeError):
    """Raised when a precision-critical fact is asserted from a lossy summary."""
    pass


class FactClass(Enum):
    VERBATIM = "verbatim"          # still resident in window
    SUMMARY_NONCRITICAL = "summary_nc"  # stable preference, high-level goal
    SUMMARY_CRITICAL = "summary_c"      # conditional, negation, bound, ordering


@dataclass
class WorkingFact:
    text: str
    fact_class: FactClass
    source_span_id: str | None      # None means summary-derived
    summary_epoch: int | None


PRECISION_MARKERS = ("only", "until", "do not", "must not", "before", "after",
                     "at most", "at least", "exactly", "rollback", "cutover")


def is_precision_critical(text: str) -> bool:
    low = text.lower()
    return any(m in low for m in PRECISION_MARKERS)


def assert_fact_for_action(fact: WorkingFact, retrieve) -> str:
    """
    Gate every action on a working-set fact. Returns the authoritative text
    the action may rely on, or raises if provenance cannot be established.
    """
    if fact.fact_class is FactClass.VERBATIM:
        return fact.text

    if fact.fact_class is FactClass.SUMMARY_NONCRITICAL and not is_precision_critical(fact.text):
        return fact.text  # safe to act, epoch-tagged for later reconciliation

    # Summary-derived AND precision-critical: source must win.
    if fact.source_span_id is None:
        raise ProvenanceViolation(
            f"summary-derived critical fact has no source pointer: {fact.text!r}"
        )

    source = retrieve(fact.source_span_id)
    if source is None:
        raise ProvenanceViolation(
            f"retrieval failed for source span {fact.source_span_id}; "
            f"refusing to promote summary {fact.text!r}"
        )

    if is_precision_critical(fact.text) and source.strip() != fact.text.strip():
        # The summary drifted from its source. Invalidate; do not act on summary.
        raise ProvenanceViolation(
            f"summary (epoch {fact.summary_epoch}) contradicts source "
            f"{fact.source_span_id}: summary={fact.text!r} source={source!r}"
        )

    return source
