# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-state-destroying-operation-rather-than-a-lossy-summarization-and-how-does-the-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-state-destroying-operation-rather-than-a-lossy-summarization-and-how-does-the-compaction.warrant.json
# Markdown SHA-256:   eb61234dc99a998bac5061372a75c10bd1c48db6106adad47123beec46dcc08d
# Code AST SHA-256:   ed0dcb7ec87162594e26ee76420fba4dd0d45ec956395137e5b57ce1eb927684
# Verified Classes:   CompactionUnsafe, Modality, CriticalFact, CompactionTarget
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionUnsafe(RuntimeError):
    """Raised when auto-compaction would destroy non-reconstructible task state."""
    pass


class Modality(Enum):
    SATISFIED = "satisfied"
    AWAITING_CONFIRMATION = "awaiting_confirmation"  # blocking; must not collapse
    FAILED = "failed"


@dataclass
class CriticalFact:
    key: str
    value: str
    modality: Modality
    reconstructible: bool          # True only if a tool/artifact can re-yield it
    pinned: bool = False           # True once promoted to a non-compactible home


@dataclass
class CompactionTarget:
    region_tokens: int
    facts: list[CriticalFact] = field(default_factory=list)


def audit_and_compact(target: CompactionTarget, pinned_store: dict) -> int:
    """Two-phase compaction: audit -> promote -> compact. Fails closed on uncertainty."""
    # Phase 1: audit. Any single-homed critical fact blocks compaction of its region.
    unpromoted = [f for f in target.facts if not f.reconstructible and not f.pinned]
    ambiguous = [f for f in target.facts if f.reconstructible is None]

    if ambiguous:
        # Cannot classify reconstructibility -> fail closed, do not guess.
        raise CompactionUnsafe(
            f"Cannot classify reconstructibility for {[f.key for f in ambiguous]}; "
            f"refusing to compact region of {target.region_tokens} tokens."
        )

    # Phase 2: promote. Write critical facts to pinned store, preserving modality.
    for fact in unpromoted:
        # Modality is carried as a typed value, never flattened to prose.
        pinned_store[fact.key] = {"value": fact.value, "modality": fact.modality.value}
        fact.pinned = True

    # Phase 3: compact the remainder. Only reconstructible / pinned facts survive
    # outside the region; everything left is safe to summarize lossily.
    residual = [f for f in target.facts if not f.pinned]
    if any(not f.reconstructible for f in residual):
        raise CompactionUnsafe("Residual region still holds single-homed state; aborting.")

    return target.region_tokens  # caller may now summarize freely


def maybe_autocompact(target: CompactionTarget, pinned_store: dict, threshold: int) -> bool:
    if target.region_tokens < threshold:
        return False
    try:
        audit_and_compact(target, pinned_store)
        return True
    except CompactionUnsafe as e:
        # Surface to orchestrator; take checkpointed pause rather than silent loss.
        raise CompactionUnsafe(f"Autocompaction blocked: {e}") from e
