# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-task-critical-state-loss-during-automatic-context-compaction-in-long-horizon-agent-runs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-task-critical-state-loss-during-automatic-context-compaction-in-long-horizon-agent-runs.warrant.json
# Markdown SHA-256:   d58fbc9a43fe5c8dff926b02e95023baf62546be4b51ace00e2affead04e512c
# Code AST SHA-256:   c0281b937ea2b580afca938dd1d9e70415f27fc44bf3fcbc14492c0f250b8085
# Verified Classes:   CompactionStateLoss, ContextSnapshot, ConstraintLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionStateLoss(RuntimeError):
    """Raised when a compaction boundary is detected to have dropped task-critical referential state."""
    pass


@dataclass
class ContextSnapshot:
    turn: int
    identifiers: set[str]          # UUIDs, paths, numeric IDs, hashes
    constraints: set[str]          # verbatim scope-bearing statements
    action_ledger: list[tuple[str, str]]  # (action, exact_args)
    summary_text: str = ""


@dataclass
class ConstraintLedger:
    """Durable, never-summarized store for referential state."""
    identifiers: set[str] = field(default_factory=set)
    constraints: set[str] = field(default_factory=set)
    actions: list[tuple[str, str]] = field(default_factory=list)

    def absorb(self, snap: ContextSnapshot) -> None:
        self.identifiers |= snap.identifiers
        self.constraints |= snap.constraints
        for act in snap.action_ledger:
            if act not in self.actions:
                self.actions.append(act)


def verify_compaction(pre: ContextSnapshot,
                      post: ContextSnapshot,
                      ledger: ConstraintLedger,
                      min_id_ratio: float = 0.02) -> None:
    """Check structural signals after a compaction boundary. Raise on referential loss."""
    lost_ids = pre.identifiers - post.identifiers - ledger.identifiers
    if lost_ids:
        raise CompactionStateLoss(
            f"Identifier entropy collapse at turn {post.turn}: "
            f"{len(lost_ids)} referential anchors evicted and not externalized: "
            f"{sorted(lost_ids)[:5]}"
        )

    lost_constraints = pre.constraints - post.constraints - ledger.constraints
    if lost_constraints:
        raise CompactionStateLoss(
            f"Constraint/negation dropout at turn {post.turn}: "
            f"{len(lost_constraints)} scope-bearing statements lost: "
            f"{sorted(lost_constraints)[:3]}"
        )

    # Action-ledger discontinuity: a prior side-effecting action is no longer
    # provable from either the compacted context or the durable ledger.
    unprovable = [a for a in pre.action_ledger if a not in ledger.actions]
    if unprovable:
        raise CompactionStateLoss(
            f"Action-ledger discontinuity at turn {post.turn}: "
            f"{len(unprovable)} prior actions unprovable, risk of duplicate side effects."
        )

    total = max(len(post.summary_text.split()), 1)
    id_ratio = len(post.identifiers) / total
    if id_ratio < min_id_ratio and pre.identifiers:
        raise CompactionStateLoss(
            f"Identifier density {id_ratio:.4f} below floor {min_id_ratio} "
            f"at turn {post.turn}; summary has paraphrased away referential state."
        )


def compact_and_verify(pre: ContextSnapshot,
                       summarize: "callable",
                       ledger: ConstraintLedger) -> ContextSnapshot:
    """Compact only narrative turns; externalize referential state to the ledger first."""
    ledger.absorb(pre)
    post = ContextSnapshot(
        turn=pre.turn + 1,
        identifiers=set(pre.identifiers),   # referential state is carried verbatim
        constraints=set(pre.constraints),
        action_ledger=list(pre.action_ledger),
        summary_text=summarize(pre),
    )
    verify_compaction(pre, post, ledger)
    return post
