# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-reconstruct-context-from-a-lossy-compaction-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-reconstruct-context-from-a-lossy-compaction-artifact.warrant.json
# Markdown SHA-256:   1bf83cc91135cabdde75dc80aaf032fa065f5798133fa6004449efd80a904002
# Code AST SHA-256:   4a05cd4a270f6373a1c3ea967a93e17fde9e6cec434b28d0b88db8c7f538aac0
# Verified Classes:   ReconstructionUnsoundError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReconstructionUnsoundError(RuntimeError):
    """Raised when an instance is asked to restore context from a lossy artifact."""


LOSSY_GIST = "LOSSY_GIST"
LOSSY_LITERAL = "LOSSY_LITERAL"
LOSSLESS = "LOSSLESS"

# Operations that may consume a lossy artifact as a prior.
TOLERANT_OPS = frozenset({"summarize", "plan", "brainstorm", "rank"})

# Operations that require restoration semantics: literals must be exact.
RESTORATION_OPS = frozenset({"authorize", "commit", "emit_authoritative", "retry_idempotent"})


def reconstruct(artifact: dict, operation: str, durable_lookup) -> dict:
    """
    Expand or restore a context from a compaction artifact.

    `artifact` carries at least: {"loss_class": str, "payload": dict, "digest": str|None}
    `durable_lookup(key)` returns the exact value from the source of truth, or None.
    """
    loss_class = artifact.get("loss_class")
    payload = artifact.get("payload", {})

    if operation not in TOLERANT_OPS | RESTORATION_OPS:
        raise ReconstructionUnsoundError(
            f"Unknown operation class {operation!r}; refusing to guess loss tolerance."
        )

    if operation in TOLERANT_OPS:
        # Expansion: lossy artifact is a prior, not a record.
        return payload

    # Restoration path: requires a lossless, digest-verified artifact.
    if loss_class != LOSSLESS or not artifact.get("digest"):
        raise ReconstructionUnsoundError(
            f"Operation {operation!r} requires restoration semantics, but artifact "
            f"is tagged {loss_class!r} with digest={artifact.get('digest')!r}. "
            "Refusing to invent literals; re-fetch from durable source instead."
        )

    # Even for lossless artifacts, verify every literal against the durable source
    # before the instance is allowed to act on it.
    for key, value in payload.items():
        authoritative = durable_lookup(key)
        if authoritative is None:
            raise ReconstructionUnsoundError(
                f"Literal {key!r} absent from durable source; cannot restore."
            )
        if authoritative != value:
            raise ReconstructionUnsoundError(
                f"Digest-verified artifact disagrees with durable source on {key!r}: "
                f"{value!r} != {authoritative!r}. Compaction layer is corrupt."
            )

    return payload
