# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-lossy-auto-compaction-summary-as-a-non-authoritative-cache-rather-than-state-to-prevent-resurrection-of-retracted-facts.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-lossy-auto-compaction-summary-as-a-non-authoritative-cache-rather-than-state-to-prevent-resurrection-of-retracted-facts.warrant.json
# Markdown SHA-256:   08e7e29885c8163101374cfcd188d423526385b4c4a9e8703d6b9cbcb67fa919
# Code AST SHA-256:   28942c545c80d2cfbb3916ebd32e5e27f6418db9770ce1d47c5f605e462fa5de
# Verified Classes:   CompactionIntegrityError, FactStatus, Fact, CompactionIndex
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CompactionIntegrityError(RuntimeError):
    """Raised when a resumed agent would act on a fact whose supersession
    status cannot be established from the compaction index."""


class FactStatus(Enum):
    ACTIVE = "ACTIVE"
    SUPERSEDED = "SUPERSEDED"
    UNVERIFIED = "UNVERIFIED"


@dataclass
class Fact:
    fact_id: str
    provenance_segment: int
    status: FactStatus = FactStatus.UNVERIFIED


@dataclass
class CompactionIndex:
    # fact_id -> (provenance_segment, status)
    entries: dict[str, tuple[int, FactStatus]] = field(default_factory=dict)
    retained_segments: set[int] = field(default_factory=set)

    def lookup(self, fact_id: str) -> Optional[tuple[int, FactStatus]]:
        return self.entries.get(fact_id)


def resolve_fact_on_resume(
    fact: Fact,
    index: CompactionIndex,
    summary_asserts: bool,
    require_tool_check: bool = True,
) -> Fact:
    """Reconstruct a fact's status after lossy compaction rollover.

    Invariant: a fact whose provenance was evicted and whose status is not
    present in the index is UNVERIFIED, never optimistically ACTIVE.
    """
    entry = index.lookup(fact.fact_id)

    if entry is not None:
        prov_seg, status = entry
        # Index is authoritative over prose summary.
        if status is FactStatus.SUPERSEDED:
            return Fact(fact.fact_id, prov_seg, FactStatus.SUPERSEDED)
        return Fact(fact.fact_id, prov_seg, FactStatus.ACTIVE)

    # No index entry. Did the provenance segment survive compaction?
    if fact.provenance_segment in index.retained_segments:
        # Provenance still readable in the tail; trust it, but it is not
        # indexed, so it is only as good as the live transcript.
        return Fact(fact.fact_id, fact.provenance_segment, FactStatus.UNVERIFIED)

    # Provenance evicted and no index entry: the fact is a resurrection
    # candidate. The summary may assert it, but we refuse to act on it
    # without a fresh tool check.
    if summary_asserts:
        if require_tool_check:
            return Fact(fact.fact_id, fact.provenance_segment, FactStatus.UNVERIFIED)
        # Acting without a check on a summary-only assertion is the exact
        # failure this guardrail exists to prevent.
        raise CompactionIntegrityError(
            f"fact {fact.fact_id!r} asserted by lossy summary but provenance "
            f"segment {fact.provenance_segment} was evicted and no supersession "
            f"index entry exists; refusing to act without tool verification"
        )

    return Fact(fact.fact_id, fact.provenance_segment, FactStatus.UNVERIFIED)


def assert_actionable(fact: Fact) -> None:
    """Gate for any state-mutating action: only ACTIVE facts may be acted on."""
    if fact.status is not FactStatus.ACTIVE:
        raise CompactionIntegrityError(
            f"cannot act on fact {fact.fact_id!r} with status {fact.status.value}; "
            f"require tool re-derivation before mutation"
        )
