|
| 1 | +"""Unified retrieval verdict — one honesty contract across the search tools. |
| 2 | +
|
| 3 | +An empty or weak retrieval result is positive, token-saving evidence: grounded |
| 4 | +symbolic retrieval can prove "this is not here" where nearest-neighbour search |
| 5 | +always returns its closest something. ``build_verdict`` centralises the logic |
| 6 | +that ``search_symbols`` and ``get_ranked_context`` previously duplicated, and |
| 7 | +extends it to ``search_text``. |
| 8 | +
|
| 9 | +The result carries two things: |
| 10 | +
|
| 11 | +* ``verdict`` — the unified ``_meta.verdict`` dict with a complete taxonomy |
| 12 | + (``ok`` / ``low_confidence`` / ``absent`` / ``degraded``), the scan counts that |
| 13 | + back an absence claim, per-channel status, and near-miss suggestions. |
| 14 | +* ``negative_evidence`` — the legacy dict (or ``None``) with the same trigger and |
| 15 | + shape as before, so existing consumers and the injected agent policy keep |
| 16 | + working unchanged. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +from typing import Optional, Sequence |
| 22 | + |
| 23 | +# Emitted as verdict["state"]. |
| 24 | +STATE_OK = "ok" |
| 25 | +STATE_LOW_CONFIDENCE = "low_confidence" |
| 26 | +STATE_ABSENT = "absent" |
| 27 | +STATE_DEGRADED = "degraded" |
| 28 | + |
| 29 | +_NOTES = { |
| 30 | + STATE_OK: "Confident matches returned.", |
| 31 | + STATE_LOW_CONFIDENCE: ( |
| 32 | + "Matches are below the confidence threshold; verify before relying on them." |
| 33 | + ), |
| 34 | + STATE_ABSENT: ( |
| 35 | + "No match found after scanning the index. Treat this as strong evidence the " |
| 36 | + "target is not present; do not reformulate the same query expecting a hit." |
| 37 | + ), |
| 38 | + STATE_DEGRADED: ( |
| 39 | + "A requested retrieval channel was unavailable or the scan was cut short. " |
| 40 | + "Results are partial and absence is NOT proven." |
| 41 | + ), |
| 42 | +} |
| 43 | + |
| 44 | + |
| 45 | +def _semantic_provider_available() -> bool: |
| 46 | + """Return True when an embedding provider is actually configured. |
| 47 | +
|
| 48 | + Reuses ``embed_repo``'s live detection so we do not drift from the encoder the |
| 49 | + semantic path would really use. Called only when semantic was requested. |
| 50 | + """ |
| 51 | + try: |
| 52 | + from ..tools.embed_repo import _detect_provider |
| 53 | + |
| 54 | + detected = _detect_provider() |
| 55 | + if isinstance(detected, tuple): |
| 56 | + return bool(detected and detected[0]) |
| 57 | + return bool(detected) |
| 58 | + except Exception: |
| 59 | + return False |
| 60 | + |
| 61 | + |
| 62 | +def _did_you_mean( |
| 63 | + source_files: Optional[Sequence[str]], |
| 64 | + query_terms: Optional[Sequence[str]], |
| 65 | + cap: int = 5, |
| 66 | +) -> list: |
| 67 | + """Files whose basename contains a query term (near-miss candidates).""" |
| 68 | + if not source_files or not query_terms: |
| 69 | + return [] |
| 70 | + out: list = [] |
| 71 | + seen: set = set() |
| 72 | + for f in source_files: |
| 73 | + base = f.lower().replace("\\", "/").rsplit("/", 1)[-1] |
| 74 | + if any(t in base for t in query_terms): |
| 75 | + if f not in seen: |
| 76 | + seen.add(f) |
| 77 | + out.append(f) |
| 78 | + if len(out) >= cap: |
| 79 | + break |
| 80 | + return out |
| 81 | + |
| 82 | + |
| 83 | +def build_verdict( |
| 84 | + *, |
| 85 | + result_count: int, |
| 86 | + scanned_symbols: int = 0, |
| 87 | + scanned_files: int = 0, |
| 88 | + best_score: Optional[float] = None, |
| 89 | + threshold: Optional[float] = None, |
| 90 | + query_terms: Optional[Sequence[str]] = None, |
| 91 | + source_files: Optional[Sequence[str]] = None, |
| 92 | + semantic_requested: bool = False, |
| 93 | + index_stale: bool = False, |
| 94 | + timed_out: bool = False, |
| 95 | +) -> dict: |
| 96 | + """Compute the unified verdict plus the legacy negative_evidence dict. |
| 97 | +
|
| 98 | + Returns ``{"verdict": <_meta.verdict>, "negative_evidence": <dict|None>}``. |
| 99 | +
|
| 100 | + Backward compatibility: ``negative_evidence`` fires on exactly the historical |
| 101 | + trigger (empty result, or best score below threshold) with the historical keys |
| 102 | + and verdict names, so existing tests and the agent policy are unaffected. The |
| 103 | + new ``verdict`` is purely additive. |
| 104 | + """ |
| 105 | + terms = [t for t in (query_terms or []) if t] |
| 106 | + did_you_mean = _did_you_mean(source_files, terms) |
| 107 | + |
| 108 | + semantic_available = _semantic_provider_available() if semantic_requested else True |
| 109 | + below_threshold = ( |
| 110 | + threshold is not None and best_score is not None and best_score < threshold |
| 111 | + ) |
| 112 | + |
| 113 | + # --- unified state (degraded takes precedence: partial scans can't prove absence) --- |
| 114 | + if timed_out: |
| 115 | + state = STATE_DEGRADED |
| 116 | + elif semantic_requested and not semantic_available: |
| 117 | + state = STATE_DEGRADED |
| 118 | + elif result_count == 0: |
| 119 | + state = STATE_ABSENT |
| 120 | + elif below_threshold: |
| 121 | + state = STATE_LOW_CONFIDENCE |
| 122 | + else: |
| 123 | + state = STATE_OK |
| 124 | + |
| 125 | + if semantic_requested and not semantic_available: |
| 126 | + semantic_channel = "unavailable" |
| 127 | + elif semantic_requested: |
| 128 | + semantic_channel = "ok" |
| 129 | + else: |
| 130 | + semantic_channel = "off" |
| 131 | + |
| 132 | + verdict = { |
| 133 | + "state": state, |
| 134 | + "scanned": {"symbols": int(scanned_symbols), "files": int(scanned_files)}, |
| 135 | + "best_score": round(best_score, 3) if best_score is not None else None, |
| 136 | + "channels": { |
| 137 | + "lexical": "ok", |
| 138 | + "semantic": semantic_channel, |
| 139 | + "index": "stale" if index_stale else "fresh", |
| 140 | + }, |
| 141 | + "note": _NOTES[state], |
| 142 | + } |
| 143 | + if did_you_mean: |
| 144 | + verdict["did_you_mean"] = did_you_mean |
| 145 | + |
| 146 | + # --- legacy negative_evidence: unchanged trigger + shape --- |
| 147 | + negative_evidence = None |
| 148 | + if result_count == 0 or below_threshold: |
| 149 | + negative_evidence = { |
| 150 | + "verdict": ( |
| 151 | + "no_implementation_found" if result_count == 0 else "low_confidence_matches" |
| 152 | + ), |
| 153 | + "scanned_symbols": int(scanned_symbols), |
| 154 | + "scanned_files": int(scanned_files), |
| 155 | + "best_match_score": round(best_score, 3) if best_score else 0.0, |
| 156 | + } |
| 157 | + if did_you_mean: |
| 158 | + negative_evidence["related_existing"] = did_you_mean |
| 159 | + |
| 160 | + return {"verdict": verdict, "negative_evidence": negative_evidence} |
0 commit comments