# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-compaction-summary-as-a-lossy-projection-rather-than-a-faithful-substitute-for-the-evicted-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-compaction-summary-as-a-lossy-projection-rather-than-a-faithful-substitute-for-the-evicted-context.warrant.json
# Markdown SHA-256:   5fd3794cd6b27cc625214411aa1a83b805e94049bc684d63df5ffb94fbe6fa20
# Code AST SHA-256:   3a2984c273f7c787fecfd4a3fb2d2a4979d1e3e0fab0083a3e122eba11040bb0
# Verified Classes:   UnrehydratedLiteralError, RawSpanStore, CompactionSummary
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrehydratedLiteralError(RuntimeError):
    """Raised when an action embeds a literal sourced only from a lossy compaction summary."""
    pass


class RawSpanStore:
    """Retrieval index over evicted raw token spans. Returns verbatim text or None."""
    def __init__(self, spans: dict[str, str]):
        self._spans = spans

    def fetch(self, span_id: str, needle: str) -> str | None:
        text = self._spans.get(span_id)
        if text is None:
            return None
        # Confirmation is a literal substring match against raw tokens,
        # never a semantic judgment against another summary.
        return text if needle in text else None


class CompactionSummary:
    """A lossy projection. Carries provenance span ids but NOT literal guarantees."""
    def __init__(self, text: str, source_span_ids: list[str]):
        self.text = text
        self.source_span_ids = source_span_ids

    def assert_literal(self, literal: str) -> None:
        # A summary can never satisfy a literal assertion on its own.
        raise UnrehydratedLiteralError(
            f"literal {literal!r} asserted from summary text; "
            f"summary is a projection, rehydrate from raw spans {self.source_span_ids}"
        )


def resolve_literal(
    summary: CompactionSummary,
    store: RawSpanStore,
    needle: str,
) -> str:
    """Rehydrate a literal from raw spans before any action may consume it."""
    for span_id in summary.source_span_ids:
        hit = store.fetch(span_id, needle)
        if hit is not None:
            return needle
    raise UnrehydratedLiteralError(
        f"literal {needle!r} not found in any raw span backing the summary; "
        f"cannot act on an unverified literal — re-derive from a live source or escalate"
    )


def emit_tool_call(summary: CompactionSummary, store: RawSpanStore, params: dict[str, str]) -> dict[str, str]:
    verified = {}
    for key, value in params.items():
        # Every literal-bearing parameter must be rehydrated, not read off the summary.
        verified[key] = resolve_literal(summary, store, value)
    return verified
