# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-anchor-drift-when-lossy-transcript-compaction-silently-relocates-recovery-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-anchor-drift-when-lossy-transcript-compaction-silently-relocates-recovery-state.warrant.json
# Markdown SHA-256:   64558fb8c0920e7b589fe58ad574ed00ecf7c144c9eec97178473a192f6e8966
# Code AST SHA-256:   ea91867f5e03cd7f6dbc7de23df475380a9d8fc5b29d919db8a0e58a19a56866
# Verified Classes:   AnchorDriftError, Anchor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Callable, Optional


class AnchorDriftError(RuntimeError):
    """Raised when a retained recovery anchor resolves but its bound world-state has shifted."""


@dataclass(frozen=True)
class Anchor:
    anchor_id: str
    # Externally-pinned anchors reference a probeable record; transcript-resident
    # anchors carry their meaning only in prose and are drift candidates.
    externally_pinned: bool
    precondition: Optional[Callable[[], bool]]  # must be re-probed at resume
    summary_claim: str  # what the compacted summary asserts the anchor implies


def compact(anchors: list[Anchor]) -> list[Anchor]:
    """Lossy compaction: transcript-resident anchors must be promoted or demoted."""
    retained = []
    for a in anchors:
        if a.externally_pinned and a.precondition is not None:
            retained.append(a)
        elif a.precondition is not None:
            # transcript-resident but we were able to attach a probe -> keep, gated
            retained.append(a)
        else:
            # no probe, meaning lives only in prose -> demote to non-authoritative
            continue
    return retained


def resume(retained: list[Anchor], expected_digest: str) -> list[str]:
    """Re-validate every retained anchor's precondition before advancing."""
    verified = []
    for a in retained:
        if a.precondition is None:
            raise AnchorDriftError(
                f"anchor {a.anchor_id} retained without a precondition probe; "
                f"summary claim '{a.summary_claim}' is unverifiable"
            )
        if not a.precondition():
            raise AnchorDriftError(
                f"anchor {a.anchor_id} DRIFTED: summary asserts '{a.summary_claim}' "
                f"but precondition probe returned False; re-derive from external record"
            )
        verified.append(a.anchor_id)

    actual = hashlib.sha256("|".join(verified).encode()).hexdigest()
    if actual != expected_digest:
        raise AnchorDriftError(
            f"anchor set digest mismatch: expected {expected_digest}, got {actual}; "
            f"compaction relocated recovery state"
        )
    return verified
