# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-lossy-summary-provenance-when-automatic-context-compaction-silently-rewrites-the-history-it-later-cites.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-lossy-summary-provenance-when-automatic-context-compaction-silently-rewrites-the-history-it-later-cites.warrant.json
# Markdown SHA-256:   1961d1181a59db306f1d9fefce45bf59623347b3c0f22957ca4beb97d1878d9a
# Code AST SHA-256:   b66fdca8f75b33898d89c9025901dc97cdddf50144906eb6cf1185193eaf0dbb
# Verified Classes:   ProvenanceClass, ProvenanceCollapseError, Span, CompactedContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceClass(Enum):
    OBSERVED = "observed"      # first-party tool result or user turn
    DERIVED = "derived"        # summary / recap / model-authored compression
    INFERRED = "inferred"      # model's own prior reasoning


class ProvenanceCollapseError(RuntimeError):
    """Raised when a downstream step cites or numerically depends on a
    compacted span whose provenance is DERIVED without a verbatim handle."""
    pass


LOAD_BEARING = ("number_with_unit", "identifier", "prohibition", "temporal_order")


@dataclass
class Span:
    span_id: str
    text: str
    provenance: ProvenanceClass
    load_bearing_kinds: tuple = ()
    verbatim_handle: Optional[str] = None  # pointer into side store


@dataclass
class CompactedContext:
    spans: list = field(default_factory=list)

    def resolve(self, span_id: str, needs: str) -> str:
        """Resolve a span for a downstream assertion of class `needs`
        (e.g. 'cite', 'numeric', 'identity')."""
        span = next((s for s in self.spans if s.span_id == span_id), None)
        if span is None:
            raise ProvenanceCollapseError(f"span {span_id!r} not in context")

        # OBSERVED is always safe to assert from directly.
        if span.provenance is ProvenanceClass.OBSERVED:
            return span.text

        # DERIVED is safe only for prose; unsafe for load-bearing classes
        # unless a verbatim handle exists to dereference.
        if span.provenance is ProvenanceClass.DERIVED:
            if needs in ("cite", "numeric", "identity") or span.load_bearing_kinds:
                if span.verbatim_handle is None:
                    raise ProvenanceCollapseError(
                        f"span {span_id!r} is DERIVED, load-bearing={span.load_bearing_kinds}, "
                        f"needs={needs!r}, and has no verbatim handle; "
                        f"refusing to interpolate from summary"
                    )
                return f"<deref handle={span.verbatim_handle}>"
            return span.text

        # INFERRED must never be cited as an observation.
        raise ProvenanceCollapseError(
            f"span {span_id!r} is INFERRED; cannot satisfy needs={needs!r} "
            f"without re-observation"
        )


def emit_final_config(ctx: CompactedContext, span_id: str, needs: str = "numeric") -> str:
    """Downstream step that numerically depends on a compacted span."""
    try:
        return ctx.resolve(span_id, needs=needs)
    except ProvenanceCollapseError as e:
        # Correct behavior: halt and surface budget exhaustion rather than
        # fold lossily and continue.
        raise ProvenanceCollapseError(
            f"compaction invariant violated; halting before emitting config: {e}"
        ) from e
