# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-compaction-time-state-against-post-compaction-tool-reality-to-avoid-silent-invariant-violation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-compaction-time-state-against-post-compaction-tool-reality-to-avoid-silent-invariant-violation.warrant.json
# Markdown SHA-256:   4c0ba33dd693b34223913a05bc5e01c40c0209bf1ff1d605e4c7774c2b7fdddf
# Code AST SHA-256:   f6f5ecf8ff451c4933c2a31ee800ac1032cf6760f6262427e2198c53ad1d45f7
# Verified Classes:   ReferentialContinuityError, PinnedHandle, ContinuityLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

"""Post-compaction referential-continuity guard.

Pins opaque addressing tokens outside the compactable region and requires
identity revalidation against the tool's own record after every compaction
boundary, before any dependent call is permitted.
"""

from dataclasses import dataclass, field
from typing import Any, Callable


class ReferentialContinuityError(RuntimeError):
    """Raised when a post-compaction handle no longer resolves to the
    object the agent originally created. Loud replacement for silent
    shadow-object corruption."""


@dataclass
class PinnedHandle:
    token: str                      # opaque handle returned by the tool
    object_id: str                  # stable identity from the tool's record
    created_at_turn: int


@dataclass
class ContinuityLedger:
    """Lives outside the compactable context region. Never summarized."""
    pins: dict[str, PinnedHandle] = field(default_factory=dict)
    compaction_epoch: int = 0

    def pin(self, token: str, object_id: str, turn: int) -> None:
        self.pins[token] = PinnedHandle(token, object_id, turn)

    def on_compaction(self) -> None:
        # Epoch bump marks that every pin must be revalidated before reuse.
        self.compaction_epoch += 1


def revalidate_before_use(
    ledger: ContinuityLedger,
    token: str,
    describe: Callable[[str], dict[str, Any]],
    current_epoch: int,
) -> dict[str, Any]:
    """Call the tool's own describe() and confirm the handle still addresses
    the object the agent pinned. Must be invoked after any compaction and
    before any dependent write."""
    pin = ledger.pins.get(token)
    if pin is None:
        raise ReferentialContinuityError(
            f"handle {token!r} was used but never pinned; "
            f"compaction may have dropped an opaque token"
        )
    record = describe(token)
    if record.get("object_id") != pin.object_id:
        raise ReferentialContinuityError(
            f"handle {token!r} now resolves to object "
            f"{record.get('object_id')!r} but was pinned to {pin.object_id!r} "
            f"at turn {pin.created_at_turn} (epoch {current_epoch}); "
            f"refusing dependent call to prevent shadow-object write"
        )
    return record
