# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-referent-identity-when-auto-compaction-summarizes-a-session-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-referent-identity-when-auto-compaction-summarizes-a-session-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   622b120fa73f708e822d5ab9b77543ca80d98346ac09d9da5e36730722e04200
# Code AST SHA-256:   ab7be0610ab29f6767b9f0985fa82a620757e62828ec00b86fa2212728acbe8b
# Verified Classes:   CompactionFidelityError, HandleTable
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionFidelityError(RuntimeError):
    """Raised when semantic compaction severs a live referent handle."""


@dataclass
class HandleTable:
    # entity -> status; status is "verified", "unverified", or "pending_write"
    entries: dict[str, str] = field(default_factory=dict)

    def live_handles(self) -> set[str]:
        return set(self.entries.keys())


def compact_session(
    pre_compaction_handles: HandleTable,
    summary_text: str,
    summary_handle_block: set[str],
) -> HandleTable:
    """
    Enforce referent persistence across a semantic compaction.

    Invariant: every live handle present before compaction must appear in the
    summary's structured handle block. A description in prose does not count.
    """
    required = pre_compaction_handles.live_handles()
    missing = required - summary_handle_block

    if missing:
        raise CompactionFidelityError(
            "Compaction severed live referents: "
            f"{sorted(missing)}. These entities are still actionable but no "
            "longer resolvable post-summary. Refuse compaction or carry the "
            "handle table verbatim."
        )

    # Also refuse to drop an UNVERIFIED write's status flag.
    for handle in required:
        if pre_compaction_handles.entries[handle] == "unverified" and handle not in summary_handle_block:
            raise CompactionFidelityError(
                f"Unverified referent {handle!r} lost its status flag; "
                "a downstream turn may treat an unconfirmed write as verified."
            )

    return HandleTable(entries=dict(pre_compaction_handles.entries))


def guarded_compaction(pre: HandleTable, summary: str, block: set[str]) -> HandleTable:
    try:
        return compact_session(pre, summary, block)
    except CompactionFidelityError:
        # Fail closed: skip compaction this cycle rather than corrupt state.
        return pre
