# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-crossed-from-lossy-but-safe-to-lossy-and-unsafe-in-long-horizon-agent-context-management.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-crossed-from-lossy-but-safe-to-lossy-and-unsafe-in-long-horizon-agent-context-management.warrant.json
# Markdown SHA-256:   c7d669e55efd9ec243bd2a49274955cf4ad51a634cf6dd3b5f27b28946961d91
# Code AST SHA-256:   d14c2c3f5dbf6c456848cad377ec3906f3d33990bba7f9252f4b34b79e2ef871
# Verified Classes:   UnsafeCompactionError, Fold, PreFoldState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UnsafeCompactionError(RuntimeError):
    """Raised when a compaction fold crosses from lossy-but-safe to lossy-and-unsafe."""


@dataclass
class Fold:
    generation: int
    proper_nouns: int
    literal_tokens: int
    negative_constraints: int
    stable_keys: set[str]
    provenance_clauses: int
    bare_assertions: int
    meta_language: bool
    pending_irreversible_action: bool


@dataclass
class PreFoldState:
    negative_constraints: int
    stable_keys: set[str]
    provenance_clauses: int
    raw_tail_available: bool = True


def check_fold_safety(fold: Fold, pre: PreFoldState) -> None:
    reasons: list[str] = []

    if fold.proper_nouns > 0 and fold.literal_tokens == 0:
        reasons.append("name-to-value asymmetry: names without literals")

    if pre.negative_constraints > 0 and fold.negative_constraints == 0:
        reasons.append("negation collapse: all prohibitions dropped")

    lost = pre.stable_keys - fold.stable_keys
    resurrected = fold.stable_keys & pre.stable_keys
    if lost and resurrected:
        reasons.append("identifier drift: keys lost and re-derived, non-monotonic")

    if fold.provenance_clauses == 0 and fold.bare_assertions > 0:
        reasons.append("provenance erosion: bare assertions without attribution")

    if fold.generation >= 2 and fold.meta_language:
        reasons.append("summary self-reference: folding a prior summary")

    if reasons and fold.pending_irreversible_action:
        raise UnsafeCompactionError(
            "compaction crossed safety boundary before irreversible action: "
            + "; ".join(reasons)
        )


def compact_or_reanchor(fold: Fold, pre: PreFoldState) -> str:
    try:
        check_fold_safety(fold, pre)
    except UnsafeCompactionError:
        if pre.raw_tail_available:
            return "reanchor: reinject raw tail and re-fold with bindings verbatim"
        raise
    return "accept: fold retains bindings"
