# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-irreversibility-leakage-at-the-hierarchical-summarization-trigger-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-irreversibility-leakage-at-the-hierarchical-summarization-trigger-boundary.warrant.json
# Markdown SHA-256:   7153488a97eea675d56ea156a0793325198d0acc4c13aa067848258ace307220
# Code AST SHA-256:   530ba1370e3b3325860213ed3fd8c033e27a03e6be13f533c000f8d077e23bc3
# Verified Classes:   CompactionIrreversibilityError, Constraint, PendingTask, ContextBudget, FoldScope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CompactionIrreversibilityError(RuntimeError):
    """Raised when a capacity-triggered fold would destroy the only copy
    of a polarity-bearing constraint that a pending task depends on."""


@dataclass(frozen=True)
class Constraint:
    key: str
    polarity: str  # "positive" | "negative" | "ordering"
    detail: str


@dataclass
class PendingTask:
    name: str
    read_set: FrozenSet[str]  # constraint keys this task will read


@dataclass
class ContextBudget:
    own_tokens: int
    subagent_tokens: int = 0

    def resident_tokens(self) -> int:
        # sub-agent budgets are NOT resident in this instance's window
        return self.own_tokens


@dataclass
class FoldScope:
    constraint_keys: FrozenSet[str]
    checkpoint_available: bool


def should_compact(
    budget: ContextBudget,
    threshold: int,
    pending: list[PendingTask],
    constraints: dict[str, Constraint],
    scope: FoldScope,
) -> str:
    """Returns 'no-op', 'density-fold', 'checkpoint-then-fold', or raises."""
    if budget.resident_tokens() <= threshold:
        # density gate may still fire, but only if fold is read-set-lossless
        if not _intersects_pending(scope, pending):
            return "density-fold"
        return "no-op"

    # capacity gate fired
    if not _intersects_pending(scope, pending):
        return "density-fold"

    if not scope.checkpoint_available:
        raise CompactionIrreversibilityError(
            f"capacity fold at {budget.resident_tokens()} tokens would erase "
            f"unresolved constraints {sorted(_intersecting_keys(scope, pending))} "
            f"with no external checkpoint; refusing to fold"
        )
    return "checkpoint-then-fold"


def _intersecting_keys(scope: FoldScope, pending: list[PendingTask]) -> set[str]:
    needed: set[str] = set()
    for task in pending:
        needed |= task.read_set
    return set(scope.constraint_keys) & needed


def _intersects_pending(scope: FoldScope, pending: list[PendingTask]) -> bool:
    return bool(_intersecting_keys(scope, pending))


def compact(
    budget: ContextBudget,
    threshold: int,
    pending: list[PendingTask],
    constraints: dict[str, Constraint],
    scope: FoldScope,
) -> str:
    action = should_compact(budget, threshold, pending, constraints, scope)
    if action == "checkpoint-then-fold":
        # checkpoint must succeed before the lossy fold is permitted
        if not scope.checkpoint_available:
            raise CompactionIrreversibilityError("checkpoint vanished mid-flight")
        _write_checkpoint(constraints, _intersecting_keys(scope, pending))
    return action


def _write_checkpoint(constraints: dict[str, Constraint], keys: set[str]) -> None:
    for k in keys:
        c = constraints[k]
        # polarity is preserved verbatim; narrative compression is forbidden here
        assert c.polarity in ("positive", "negative", "ordering")
