# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-authored-context-compaction-that-preserves-task-salience-but-destroys-audit-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-self-authored-context-compaction-that-preserves-task-salience-but-destroys-audit-lineage.warrant.json
# Markdown SHA-256:   18c41e6af615ad3c99ae41bd13c2f896c0744f90f71b5efa0b21062395b32edc
# Code AST SHA-256:   23743bc3bddb2b126209c130364442e6e21cdb56dbf4593269fd6443d911f7d7
# Verified Classes:   LineageDestructionError, Claim, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LineageDestructionError(RuntimeError):
    """Raised when a self-compaction would retain a load-bearing claim
    at full confidence while evicting its last reconstructible provenance."""
    pass


@dataclass
class Claim:
    text: str
    confidence: str                  # "verified" | "unverified"
    provenance: Optional[str]        # pointer to tool call + inputs, or None
    load_bearing: bool
    non_deterministic: bool
    downstream_verifier: bool


@dataclass
class CompactionPlan:
    claims: list = field(default_factory=list)
    budget_tokens: int = 0


def validate_compaction(plan: CompactionPlan, reserved_provenance_tokens: int) -> None:
    """Enforce the lineage-preservation invariant before allowing a rewrite.

    A claim may be retained at full confidence only if its provenance
    survives the budget. Otherwise it must be downgraded or evicted.
    """
    provenance_budget = reserved_provenance_tokens
    for claim in plan.claims:
        if not claim.load_bearing:
            continue

        # The dangerous conjunction: load-bearing, non-deterministic,
        # with a downstream verifier, and no surviving provenance.
        if (
            claim.provenance is None
            and claim.non_deterministic
            and claim.downstream_verifier
            and claim.confidence == "verified"
        ):
            raise LineageDestructionError(
                f"Refusing compaction: claim {claim.text!r} is load-bearing, "
                f"non-deterministic, and will be audited downstream, but its "
                f"provenance was evicted at full confidence. Downgrade to "
                f"'unverified' or reserve provenance tokens."
            )

        # Even with provenance present, the budget must actually hold it.
        if claim.provenance is not None:
            cost = len(claim.provenance.split())
            if cost > provenance_budget:
                raise LineageDestructionError(
                    f"Refusing compaction: provenance for {claim.text!r} "
                    f"requires {cost} tokens but only {provenance_budget} "
                    f"remain reserved. Salience/lineage budget conflict."
                )
            provenance_budget -= cost


def self_compact(plan: CompactionPlan, reserved_provenance_tokens: int) -> CompactionPlan:
    validate_compaction(plan, reserved_provenance_tokens)
    # Safe to proceed: every retained load-bearing claim is either
    # provenanced within budget or already downgraded.
    return plan
