# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-lossy-compaction-summary-against-a-retrieval-backed-restoration-before-resuming-a-tool-augmented-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-lossy-compaction-summary-against-a-retrieval-backed-restoration-before-resuming-a-tool-augmented-task.warrant.json
# Markdown SHA-256:   bfa91a60054a4384e456246df4071f2bb050d051618a9ccea0efe0b8642046ef
# Code AST SHA-256:   c102a8d05a61cc7f963a481637509e014d2af4525423d4e4bd5e1c08ee0bf510
# Verified Classes:   OrphanedFactError, ReconciliationError, Fact, CompactionSummary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedFactError(RuntimeError):
    """Raised when a load-bearing fact is summarized without a verbatim anchor
    or a guaranteed re-derivation path, making later reconstruction unfalsifiable."""
    pass


class ReconciliationError(RuntimeError):
    """Raised when a retrieved original turn contradicts the compaction summary
    and the agent cannot resolve the disagreement from evidence."""
    pass


@dataclass
class Fact:
    key: str                 # e.g. "auth/session.py:refresh_interval_s"
    value: str               # e.g. "900"
    silent_failure: bool     # True if a wrong reconstruction would not error loudly
    verbatim_anchor: Optional[str] = None   # exact token retained in summary
    rederivable: bool = False               # cheap tool re-call available at use time


@dataclass
class CompactionSummary:
    text: str
    anchors: dict = field(default_factory=dict)   # key -> verbatim token
    facts: list = field(default_factory=list)


def compact(facts: list[Fact], paraphrase: str) -> CompactionSummary:
    """Enforce the compaction contract: no silent-failure fact may be orphaned."""
    anchors = {}
    for f in facts:
        if f.silent_failure and not f.verbatim_anchor and not f.rederivable:
            raise OrphanedFactError(
                f"fact {f.key!r} has silent-failure semantics but no verbatim "
                f"anchor and no re-derivation path; compacting it would make a "
                f"later wrong reconstruction (e.g. {f.value!r} -> guessed) undetectable"
            )
        if f.verbatim_anchor:
            anchors[f.key] = f.verbatim_anchor
    return CompactionSummary(text=paraphrase, anchors=anchors, facts=facts)


def restore(summary: CompactionSummary, key: str, retrieved: Optional[str]) -> str:
    """Reconcile a retrieved verbatim value against the summary before use."""
    anchor = summary.anchors.get(key)
    if retrieved is None:
        if anchor is None:
            raise ReconciliationError(
                f"cannot restore {key!r}: no anchor in summary and retrieval "
                f"returned nothing; refusing to reconstruct from paraphrase"
            )
        return anchor
    if anchor is not None and retrieved != anchor:
        raise ReconciliationError(
            f"retrieved {key!r}={retrieved!r} contradicts summary anchor "
            f"{anchor!r}; resolve from evidence before proceeding"
        )
    return retrieved


# --- trace of the observed failure ---
facts = [Fact(key="auth/session.py:refresh_interval_s", value="900",
              silent_failure=True, verbatim_anchor=None, rederivable=False)]
# This call raises: the 900 was paraphrased away, so the later "60" guess
# could never be contradicted. The contract refuses the compaction.
compact(facts, "confirmed the token refresh interval")
