# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-past-the-summarizer-s-recall-horizon-and-resumes-with-a-silently-falsified-premise.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-past-the-summarizer-s-recall-horizon-and-resumes-with-a-silently-falsified-premise.warrant.json
# Markdown SHA-256:   3caf10d9e7e18e0ee7500895f19b2a741a3fed8c4ae761c838bdc2f358ece0c8
# Code AST SHA-256:   06888a9201210a8f13a8db09db8e6e18bc2f0e73265381920e4bf2f3e3d62526
# Verified Classes:   CompactionProvenanceError, Polarity, CompactedEntry, CompactionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionProvenanceError(RuntimeError):
    """Raised when a compacted memory entry cannot safely license an action."""
    pass


class Polarity(Enum):
    POSITIVE = "positive"
    NEGATIVE = "negative"
    PERMISSION = "permission"


@dataclass
class CompactedEntry:
    claim: str
    polarity: Polarity
    scope: tuple[str, ...] = ()
    source_tool_call_ids: tuple[str, ...] = ()
    agent_id: Optional[str] = None


@dataclass
class CompactionState:
    entries: list[CompactedEntry] = field(default_factory=list)
    recall_horizon_tool_call: Optional[str] = None  # oldest unrepresented call


def admit_compacted_entry(entry: CompactedEntry, state: CompactionState) -> None:
    # Invariant 1: permissions are never storable in compacted memory.
    if entry.polarity is Polarity.PERMISSION:
        raise CompactionProvenanceError(
            f"refusing to store action-license in compacted state: {entry.claim!r}; "
            "permissions must be re-derived by policy, not inherited from a summary"
        )
    # Invariant 2: negatives must carry scope + provenance.
    if entry.polarity is Polarity.NEGATIVE:
        if not entry.scope or not entry.source_tool_call_ids:
            raise CompactionProvenanceError(
                f"negative claim {entry.claim!r} lacks scope/provenance; "
                "a bounded search must not compress into an unbounded claim"
            )
    state.entries.append(entry)


def gate_irreversible_action(
    entry: CompactedEntry,
    state: CompactionState,
    rederived_scope: tuple[str, ...],
    rederived_hits: list[str],
) -> None:
    """Before an irreversible action licensed by a compacted negative, re-derive
    against full scope and refuse if the compacted scope was narrower."""
    if entry.polarity is not Polarity.NEGATIVE:
        return
    if set(rederived_scope) - set(entry.scope):
        # The original search did not cover the full scope we just re-checked.
        if rederived_hits:
            raise CompactionProvenanceError(
                f"compacted negative {entry.claim!r} was scoped to {entry.scope}, "
                f"but full-scope re-derivation found hits {rederived_hits} in "
                f"{sorted(set(rederived_scope) - set(entry.scope))}; "
                "premise falsified, halting before irreversible action"
            )
    if state.recall_horizon_tool_call and entry.source_tool_call_ids:
        if entry.source_tool_call_ids[0] < state.recall_horizon_tool_call:
            raise CompactionProvenanceError(
                f"claim {entry.claim!r} provenance predates recall horizon "
                f"{state.recall_horizon_tool_call}; must be re-derived"
            )
