# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-salience-rewrite-invariant-and-the-self-erasure-cascade-in-model-driven-context-editing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-salience-rewrite-invariant-and-the-self-erasure-cascade-in-model-driven-context-editing.warrant.json
# Markdown SHA-256:   9bbde45d7f2e0122896f09f3fd511eb78f644222894e35464a7ca50a17b2e916
# Code AST SHA-256:   344762d29f04165b9005f2348a2d465394c1a32a3486344022656673fb6cb04b
# Verified Classes:   SelfEraseCascadeError, Block
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SelfEraseCascadeError(RuntimeError):
    """Raised when a self-edit would remove the last anchored representation
    of a load-bearing fact, or when a derived block is rescored as primary."""


@dataclass
class Block:
    text: str
    derived: bool = False
    provenance: list[str] = field(default_factory=list)
    load_bearing: bool = False
    anchored_externally: bool = False


def consolidate(blocks: list[Block], scores: dict[int, float],
                threshold: float = 0.3) -> list[Block]:
    """Model-driven pruning pass with the salience-rewrite invariant enforced."""
    out: list[Block] = []
    for i, b in enumerate(blocks):
        s = scores.get(i, 1.0)

        # Invariant 1: never rescore a derived (already-lossy) block.
        if b.derived and s < threshold:
            raise SelfEraseCascadeError(
                f"block {i} is derived; rescoring it compounds loss. "
                f"Re-expand from provenance {b.provenance} before deciding."
            )

        if s < threshold:
            # Invariant 2: never prune the last unanchored copy of a load-bearing fact.
            if b.load_bearing and not b.anchored_externally:
                raise SelfEraseCascadeError(
                    f"block {i} is load-bearing and has no external anchor; "
                    f"pinning to ledger is required before pruning."
                )
            out.append(Block(
                text=f"[digest of {i}]",
                derived=True,
                provenance=[str(i)],
                load_bearing=False,
            ))
        else:
            out.append(b)
    return out


def handle_tool_error(status: int, constraint_located: bool) -> str:
    if status == 413 and not constraint_located:
        raise SelfEraseCascadeError(
            "413 against a constraint not present in context: treat as "
            "self-erasure evidence, halt and request the missing constraint; "
            "do not retry with backoff."
        )
    return "retryable"
