# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-pruning-of-low-salience-reasoning-traces-without-losing-the-justification-chain-required-for-audit-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-pruning-of-low-salience-reasoning-traces-without-losing-the-justification-chain-required-for-audit-replay.warrant.json
# Markdown SHA-256:   4fdf79ac9a5ef32e904b15ca4c02a7cdd4b8891188b09b959b20d7693db94e8d
# Code AST SHA-256:   f80ad8d96f712cbd5a0dcaccc095a0139ef1651942c63b986f67146d54d95138
# Verified Classes:   JustificationChainSevered
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class JustificationChainSevered(RuntimeError):
    """Raised when a prune would evict the sole support for a live conclusion."""
    pass


def prune_traces(spans, live_conclusions, salience_scores, evict_threshold=0.3):
    """
    spans: dict[id -> {"text", "supports": set[conclusion_id], "tombstone": bool}]
    live_conclusions: set of conclusion ids currently held
    salience_scores: dict[id -> float], model-provided, advisory only
    Returns (retained, tombstoned, evicted).
    """
    retained, tombstoned, evicted = {}, {}, {}

    # Index: which spans are the *only* support for a live conclusion?
    support_index = {}
    for sid, span in spans.items():
        for c in span["supports"]:
            if c in live_conclusions:
                support_index.setdefault(c, []).append(sid)

    for sid, span in spans.items():
        score = salience_scores.get(sid, 1.0)
        if score >= evict_threshold:
            retained[sid] = span
            continue

        # Low salience: candidate for eviction. Check dependency guard.
        for c in span["supports"]:
            if c not in live_conclusions:
                continue
            sole_support = support_index.get(c, []) == [sid]
            if sole_support and not span.get("tombstone", False):
                raise JustificationChainSevered(
                    f"prune of span {sid!r} would sever sole support for "
                    f"live conclusion {c!r}; retain or tombstone instead"
                )

        # Rejected-branch spans must survive as tombstones, not vanish.
        if span.get("rejected_branch", False):
            tombstoned[sid] = _to_tombstone(span)
        else:
            evicted[sid] = span

    return retained, tombstoned, evicted


def _to_tombstone(span):
    # Compress to minimal invariant-preserving residue: the falsified
    # alternative and the reason, stripped of exploration verbosity.
    return {"text": span["tombstone_text"], "supports": span["supports"],
            "tombstone": True}
