# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-prune-the-self-editing-policy-loop-and-the-evidence-destruction-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-prune-the-self-editing-policy-loop-and-the-evidence-destruction-invariant.warrant.json
# Markdown SHA-256:   b457cd65ac3a9452a3a2dcb8d8fb418c43ea134911481e99097daa74dd02c2a1
# Code AST SHA-256:   50246fdcc16f0972bd533ba40caabd65ace1ea5cec434674c5478c1c091ecd3e
# Verified Classes:   UnreconstructiblePruneError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconstructiblePruneError(RuntimeError):
    """Raised when a self-editing prune would delete the sole carrier of a protected fact."""
    pass


PROTECTED_PATTERNS = ("res_", "max_retries", "do not", "version", "scope")


def is_sole_carrier(token: str, retained_state: str, external_store: str) -> bool:
    """A token is a sole carrier if no retained segment or external store already holds it."""
    return token not in retained_state and token not in external_store


def guarded_prune(segment: str, score: float, threshold: float,
                  retained_state: str, external_store: str) -> dict:
    """
    Returns an action dict. Refuses destructive prune of sole-carrier protected tokens;
    instead emits an extract-then-prune plan that lifts tokens to a durable scratchpad.
    """
    if score >= threshold:
        return {"action": "retain", "segment": segment}

    protected = [tok for tok in PROTECTED_PATTERNS if tok in segment]
    sole = [tok for tok in protected
            if is_sole_carrier(tok, retained_state, external_store)]

    if sole:
        # Refuse the raw prune; the segment is the only carrier of load-bearing facts.
        # Emit extract-then-prune so the facts survive in a non-prunable scratchpad.
        return {
            "action": "extract_then_prune",
            "extract": sole,
            "scratchpad_write": {tok: tok for tok in sole},
            "drop_segment": True,
            "reason": "sole_carrier_protected_tokens",
        }

    return {"action": "prune", "segment": segment}


def apply_prune(segment: str, score: float, threshold: float,
                retained_state: str, external_store: str) -> dict:
    """
    Enforces the reconstructibility invariant. Raises if a destructive prune
    would violate C1 (reconstructibility) and no extract path is available.
    """
    plan = guarded_prune(segment, score, threshold, retained_state, external_store)

    if plan["action"] == "extract_then_prune":
        # Verify the scratchpad write is non-empty and covers every sole-carrier token.
        missing = [tok for tok in plan["extract"]
                   if tok not in plan["scratchpad_write"]]
        if missing:
            raise UnreconstructiblePruneError(
                f"prune of segment would destroy sole-carrier facts {missing} "
                f"with no extract path; refusing destructive write"
            )

    if plan["action"] == "prune" and any(
        is_sole_carrier(tok, retained_state, external_store)
        for tok in PROTECTED_PATTERNS if tok in segment
    ):
        # Defensive: should be unreachable via guarded_prune, but the invariant is
        # load-bearing enough to assert twice.
        raise UnreconstructiblePruneError(
            "reconstructibility invariant violated: prune would delete sole-carrier fact"
        )

    return plan
