# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-task-and-the-summary-drops-the-active-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-task-and-the-summary-drops-the-active-constraint.warrant.json
# Markdown SHA-256:   7fa6e404c75bd5bec441a5f4b25e1355f25a06510d5f7f3e999885ee1665f5ed
# Code AST SHA-256:   7e8e09837b8be93cbf35f911d5478358087516ec8b8db2767dfa315947a6641c
# Verified Classes:   InvariantDroppedError, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class InvariantDroppedError(RuntimeError):
    """Raised when a compaction pass would discard a binding constraint
    that is still applicable to the in-flight task."""
    pass


@dataclass
class CompactionPlan:
    transcript_tokens: int
    budget_tokens: int
    trigger_ratio: float = 0.75
    pinned_invariants: list[str] = field(default_factory=list)


def compact(plan: CompactionPlan, extracted_invariants: list[str],
            summarized_tokens: int) -> CompactionPlan:
    # Refuse to compact so late that the extraction pass has no headroom.
    if plan.transcript_tokens > plan.budget_tokens:
        raise InvariantDroppedError(
            f"transcript {plan.transcript_tokens} already exceeds budget "
            f"{plan.budget_tokens}; extraction cannot run before truncation"
        )

    # Every extracted binding constraint must survive into the pinned set.
    missing = [inv for inv in extracted_invariants
               if inv not in plan.pinned_invariants]
    if missing:
        raise InvariantDroppedError(
            "compaction would drop still-applicable invariants: "
            + "; ".join(missing)
        )

    # Pinned invariants live outside the summarized region; they are not
    # subject to salience ranking and are re-injected every step.
    return CompactionPlan(
        transcript_tokens=summarized_tokens,
        budget_tokens=plan.budget_tokens,
        trigger_ratio=plan.trigger_ratio,
        pinned_invariants=list(plan.pinned_invariants),
    )
