from dataclasses import replace from lyra_worker.confidence import score_confidence from lyra_worker.quality import rank_key from lyra_worker.types import Candidate, MBTarget def rank_candidates( target: MBTarget, candidates: list[Candidate], min_confidence: float = 0.7 ) -> list[Candidate]: """Score, gate by confidence, and sort best-first (quality, then confidence).""" scored = [replace(c, confidence=score_confidence(target, c)) for c in candidates] kept = [c for c in scored if c.confidence >= min_confidence] kept.sort(key=lambda c: (rank_key(c), c.confidence), reverse=True) return kept