# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-prune-decision-and-the-memory-it-is-about-to-discard.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-prune-decision-and-the-memory-it-is-about-to-discard.warrant.json
# Markdown SHA-256:   032ce982ad8a2d430984dec0e7b1a04d0f90ab1c2f73ca5aec2fe240c146ae3f
# Code AST SHA-256:   ffe637e46d5308155f98c9eb7d2fb38e5d0efadcd1565e4ea4f0f97bcc5293a1
# Verified Classes:   PruneBoundaryViolation, PendingAction, ContextItem
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PruneBoundaryViolation(RuntimeError):
    """Raised when a self-edit would discard a token required by a pending precondition."""
    pass


@dataclass
class PendingAction:
    name: str
    precondition_tokens: set[str]


@dataclass
class ContextItem:
    item_id: str
    text: str
    salience: float  # model-generated, in [0,1]


def tokens_of(text: str) -> set[str]:
    return {t.strip(".,;:\"'()").lower() for t in text.split() if t.strip()}


def guard_prune(
    items: list[ContextItem],
    pending: list[PendingAction],
    salience_cutoff: float,
    external_store: dict[str, str],
) -> list[str]:
    """
    Return the item_ids safe to prune. Refuses to prune any item whose
    post-prune text would drop a token required by a pending precondition.
    Salience is consulted only within the precondition-safe set.
    """
    required: set[str] = set()
    for action in pending:
        required |= {t.lower() for t in action.precondition_tokens}

    candidates = [i for i in items if i.salience < salience_cutoff]
    safe: list[str] = []

    for item in candidates:
        surviving_text = external_store.get(item.item_id, "")
        surviving = tokens_of(surviving_text)
        lost = required - surviving
        if lost:
            raise PruneBoundaryViolation(
                f"Prune of item {item.item_id!r} (salience={item.salience:.2f}) "
                f"would discard precondition tokens {sorted(lost)} required by "
                f"pending actions {[a.name for a in pending]}. "
                f"Salience score is not authoritative here; spill to store and "
                f"retain a pointer instead of summarizing."
            )
        safe.append(item.item_id)

    return safe


def run_self_edit(
    items: list[ContextItem],
    pending: list[PendingAction],
    salience_cutoff: float,
    external_store: dict[str, str],
) -> list[str]:
    if not pending:
        # No enumerated plan => precondition coverage cannot be established.
        # Destructive prune is forbidden; spill only.
        raise PruneBoundaryViolation(
            "Plan is not enumerable; destructive prune unsafe. "
            "Use external spill with retained pointers."
        )
    return guard_prune(items, pending, salience_cutoff, external_store)
