# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-prune-speculative-agent-branches-without-destroying-the-survivor-it-will-later-need.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-prune-speculative-agent-branches-without-destroying-the-survivor-it-will-later-need.warrant.json
# Markdown SHA-256:   b73472981d6c040207be878c9b14508e0ae035395f3b7632a8a899b7bcdf3535
# Code AST SHA-256:   075454c1fb1d3b3b34fddc974cf9b916adefb86069a84f99c9241f9edeb0935e
# Verified Classes:   PrunedArtifactLeakError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PrunedArtifactLeakError(RuntimeError):
    """Raised when a branch is terminated while holding artifacts a survivor may read."""
    pass


def terminate_branch(branch, plan_confidence, threshold, artifact_durability, ledger):
    """
    Two-axis early-termination gate.
    plan_confidence: calibrated viability of the branch's forward plan.
    artifact_durability: 0..1, how non-re-derivable the branch's side effects are.
    """
    if plan_confidence >= threshold:
        return "keep"

    # Plan is weak. Before severing, check whether effects are disposable.
    if artifact_durability > 0.0:
        # Non-re-derivable effects exist: must inherit, not sever.
        if not branch.effects_journaled:
            raise PrunedArtifactLeakError(
                f"branch {branch.id} has durability {artifact_durability:.2f} "
                f"but no journaled effects; severing would corrupt survivors"
            )
        ledger.promote(
            branch_id=branch.id,
            artifacts=branch.effects,
            trust_floor=plan_confidence,  # record low provenance explicitly
        )
        return "prune-and-inherit"

    # Effects are re-derivable at zero cost: safe to sever and free context.
    branch.release_context()
    return "prune-and-sever"


def prune_round(branches, threshold, ledger):
    for b in branches:
        outcome = terminate_branch(
            b, b.plan_confidence, threshold, b.artifact_durability, ledger
        )
        if outcome == "prune-and-inherit" and not ledger.has(b.id):
            raise PrunedArtifactLeakError(
                f"inherited branch {b.id} missing from ledger after promotion"
            )
