# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-state-when-automatic-context-compaction-drops-resolved-sub-goals-from-the-working-set.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-state-when-automatic-context-compaction-drops-resolved-sub-goals-from-the-working-set.warrant.json
# Markdown SHA-256:   00c3c898cd2579c98bc383f8061122a01d272670c7ab6166a3324f04d9a9efe6
# Code AST SHA-256:   be102f782a72e7d4f3157096af53302a61295a2e71a4dc3bacea4751cccd8144
# Verified Classes:   CompactionScopeViolation, Predicate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionScopeViolation(RuntimeError):
    """Raised when a scope-dependent predicate would enter the working set
    without its binding set (silent scope widening)."""


@dataclass
class Predicate:
    text: str
    scope_dependent: bool
    binding_set: dict = field(default_factory=dict)
    negative_assertion: bool = False


def compact(candidates: list[Predicate], token_budget: int) -> list[Predicate]:
    """Fail-closed compaction: scope-dependent predicates must carry bindings;
    negative assertions are always retained verbatim."""
    retained: list[Predicate] = []
    used = 0
    for p in candidates:
        # Negative assertions are non-compressible and always kept.
        if p.negative_assertion:
            retained.append(p)
            used += len(p.text)
            continue
        if p.scope_dependent and not p.binding_set:
            raise CompactionScopeViolation(
                f"Predicate {p.text!r} is scope-dependent but has no binding set; "
                "refusing to emit a scope-free predicate (would silently widen scope)."
            )
        cost = len(p.text) + sum(len(k) + len(str(v)) for k, v in p.binding_set.items())
        if used + cost > token_budget:
            raise CompactionScopeViolation(
                f"Budget exhausted while retaining bound predicate {p.text!r}; "
                "abort compaction rather than drop the binding set."
            )
        retained.append(p)
        used += cost
    return retained


def resume_from_summary(summary_predicates: list[Predicate]) -> list[Predicate]:
    """A resumed instance must not act on scope-free predicates; downgrade to
    SCOPE_UNKNOWN and force targeted re-verification."""
    out = []
    for p in summary_predicates:
        if p.scope_dependent and not p.binding_set:
            p.binding_set = {"__scope__": "UNKNOWN"}
        out.append(p)
    return out
