# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-rewrite-its-own-scratchpad-the-self-pruning-amnesia-boundary-in-model-driven-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-rewrite-its-own-scratchpad-the-self-pruning-amnesia-boundary-in-model-driven-context-compaction.warrant.json
# Markdown SHA-256:   fa30fd26e967815e8ae528534b7904e9ff1c6d99c9e0215be462398aac4b9d0b
# Code AST SHA-256:   62ba945658e77cf28c4c27a7a197bc9eead3220b773cbb413ab18237d733fd05
# Verified Classes:   UnsafeSelfPruneError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeSelfPruneError(RuntimeError):
    """Raised when a destructive scratchpad rewrite would drop tokens that are
    load-bearing for a negative constraint or an unrecoverable branch premise."""


PINNED_SLOT = "constraint_surface"  # never included in the prunable range


def guard_self_prune(
    objective: str,
    prohibitions: list[str],
    prunable_tokens: list[str],
    pruner_scores: dict[int, float],
    recoverable_without_side_effects: bool,
    independent_verifier_passed: bool,
    open_branches: int,
) -> list[str]:
    """Return the tokens safe to drop. Refuse (raise) on any C1–C4 violation.

    The pruner_scores map is the model's own relevance judgment over the
    prunable range. We do NOT trust it for tokens adjacent to a prohibition.
    """
    if open_branches > 0 and not recoverable_without_side_effects:
        raise UnsafeSelfPruneError(
            f"{open_branches} open branch(es) and pruned tokens are not "
            "recoverable without a side-effecting action; refusing destructive "
            "prune (violates C1)."
        )

    # C3: anti-relevance guard. Any token mentioning a prohibited entity is
    # pinned regardless of its relevance score.
    constrained = [p.lower() for p in prohibitions]
    drop, pinned = [], []
    for i, tok in enumerate(prunable_tokens):
        if any(c in tok.lower() for c in constrained):
            pinned.append(tok)  # anti-relevant: keep it
        elif pruner_scores.get(i, 0.0) < 0.2:
            drop.append(tok)

    if pinned and not independent_verifier_passed:
        raise UnsafeSelfPruneError(
            f"{len(pinned)} anti-relevant token(s) reference prohibited "
            "entities; a same-pass pruner cannot certify their removal "
            "(violates C2/C3/C4). Pin them to "
            f"{PINNED_SLOT!r} and re-run with an independent verifier."
        )

    if not recoverable_without_side_effects and not independent_verifier_passed:
        raise UnsafeSelfPruneError(
            "Destructive prune with no witness and no independent sufficiency "
            "check; refusing (violates C1/C4)."
        )

    return drop
