# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-cross-turn-referent-identity-when-hierarchical-summary-compaction-collapses-a-mid-horizon-entity-into-its-parent-category.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-cross-turn-referent-identity-when-hierarchical-summary-compaction-collapses-a-mid-horizon-entity-into-its-parent-category.warrant.json
# Markdown SHA-256:   1b4b7ff9cdb0b857078f8b210bd488b1c3345ed29988118395f7f4df8fcbb3f5
# Code AST SHA-256:   640a674d7b68ae271dee379687908ce7b116d2612d6a36ac6fd6fec1bfeeea66
# Verified Classes:   ReferentResolutionError, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ReferentResolutionError(RuntimeError):
    """Raised when a tool call names an entity whose binding is not
    co-resident in the checkpoint ledger or the live turn context."""


@dataclass
class Checkpoint:
    parent_summaries: list[str]
    entity_ledger: dict[str, str] = field(default_factory=dict)  # slot -> concrete id
    live_context_ids: set[str] = field(default_factory=set)


def resolve_referent(slot: str, checkpoint: Checkpoint, proposed_id: str) -> str:
    """Resolve an anaphoric slot to a concrete identifier before tool execution.

    Safe policies: the binding is in the ledger, or the id was observed live
    this turn. Anything else is a confabulation candidate and must halt.
    """
    bound = checkpoint.entity_ledger.get(slot)
    if bound is not None:
        if proposed_id != bound:
            # Agent synthesized a different id than the retained binding.
            raise ReferentResolutionError(
                f"slot {slot!r} bound to {bound!r}; agent proposed {proposed_id!r}"
            )
        return bound
    if proposed_id in checkpoint.live_context_ids:
        return proposed_id
    # Slot survived compaction but binding was evicted: the unsafe middle.
    raise ReferentResolutionError(
        f"slot {slot!r} has no retained binding and {proposed_id!r} "
        f"was not observed this turn; re-discover before executing"
    )


def guarded_tool_call(slot: str, proposed_id: str, checkpoint: Checkpoint) -> str:
    resolved = resolve_referent(slot, checkpoint, proposed_id)
    return f"execute(tool=describe, target={resolved})"
