scoutrag 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scoutrag/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """ScoutRAG — active-exploration RAG agent."""
2
+
3
+ __version__ = "0.1.0"
scoutrag/answerer.py ADDED
@@ -0,0 +1,186 @@
1
+ """Grounded answer synthesis and strict programmatic citation verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+
9
+ from scoutrag.config import Settings, get_settings
10
+ from scoutrag.indexer import RetrievedChunk, VectorIndex
11
+ from scoutrag.llm import LLMClient
12
+ from scoutrag.logging_utils import logger
13
+
14
+ NOT_FOUND_ANSWER = "I could not find that in the sources I fetched."
15
+
16
+ ANSWERER_SYSTEM_PROMPT = """You are ScoutRAG's strictly grounded RAG answerer.
17
+ Given numbered source excerpts [1]..[N] and a question, determine whether ANY excerpt directly states the answer.
18
+
19
+ Return a single JSON object with EXACTLY these keys:
20
+ {
21
+ "found": true or false,
22
+ "supporting_excerpt_number": integer 1..N or null,
23
+ "answer": "Concise complete sentence answering the question using ONLY facts in the excerpts, with inline [n] citations (e.g. 'The default timeout is 5 seconds [2].'). Empty string if found is false."
24
+ }
25
+
26
+ Rules:
27
+ - Read ALL excerpts [1] through [N] carefully, including code snippets, function/class parameter defaults, and short notes.
28
+ - Set "found": true whenever ANY excerpt directly contains the answer.
29
+ - Set "found": false if the answer is NOT present in the excerpts (never guess or use outside memory).
30
+ - Every factual claim in "answer" MUST include an inline [n] citation matching the excerpt number.
31
+ - Do NOT write external citation URLs; cite only with [n]."""
32
+
33
+ _CITATION_GROUP_RE = re.compile(r"\[(\d+(?:\s*,\s*\d+)*)\]")
34
+ _RAW_URL_RE = re.compile(r"https?://[^\s\)\]>\"']+")
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class AnswerResult:
39
+ answer: str
40
+ citations: list[dict[str, object]]
41
+ route: str # "answered" | "not_found"
42
+
43
+
44
+ def _normalize_citation_groups(text: str) -> str:
45
+ """Convert '[1, 2]' into '[1][2]' so every marker holds a single index."""
46
+
47
+ def _repl(match: re.Match[str]) -> str:
48
+ nums = [part.strip() for part in match.group(1).split(",") if part.strip().isdigit()]
49
+ return "".join(f"[{n}]" for n in nums)
50
+
51
+ return _CITATION_GROUP_RE.sub(_repl, text)
52
+
53
+
54
+ def _extract_json_dict(raw: str) -> dict[str, object] | None:
55
+ text = raw.strip()
56
+ if text.startswith("```"):
57
+ text = re.sub(r"^```(?:json)?\s*", "", text)
58
+ text = re.sub(r"\s*```$", "", text)
59
+ try:
60
+ obj = json.loads(text)
61
+ if isinstance(obj, dict):
62
+ return obj
63
+ except json.JSONDecodeError:
64
+ pass
65
+ start = text.find("{")
66
+ end = text.rfind("}")
67
+ if start != -1 and end > start:
68
+ try:
69
+ obj = json.loads(text[start : end + 1])
70
+ if isinstance(obj, dict):
71
+ return obj
72
+ except json.JSONDecodeError:
73
+ return None
74
+ return None
75
+
76
+
77
+ def verify_and_format_answer(
78
+ raw_answer: str,
79
+ chunks: list[RetrievedChunk],
80
+ known_source_urls: set[str],
81
+ ) -> AnswerResult:
82
+ """Enforce exact refusal and programmatically verify all [n] citations against DB URLs."""
83
+ text = raw_answer.strip()
84
+ if not text:
85
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
86
+
87
+ text = re.sub(r"^(?:Answer|Response)\s*:\s*", "", text, flags=re.IGNORECASE).strip()
88
+
89
+ normalized_refusal = text.lower().rstrip(".! ")
90
+ if "i could not find that in the sources i fetched" in normalized_refusal:
91
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
92
+
93
+ # Reject invented raw URLs not present in the fetched index or verbatim inside retrieved chunks
94
+ # (preserving example URLs like http://127.0.0.1:5000 quoted directly from fetched code snippets).
95
+ chunk_corpus = "\n".join(c.content for c in chunks)
96
+ for raw_url in _RAW_URL_RE.findall(text):
97
+ cleaned_url = raw_url.rstrip(".,;:)")
98
+ if cleaned_url not in known_source_urls and cleaned_url not in chunk_corpus:
99
+ logger.warning("Stripping unverified raw URL emitted by LLM: %s", cleaned_url)
100
+ text = text.replace(raw_url, "")
101
+
102
+ text = _normalize_citation_groups(text)
103
+
104
+ url_to_new_n: dict[str, int] = {}
105
+ citations: list[dict[str, object]] = []
106
+
107
+ def _rewrite_marker(match: re.Match[str]) -> str:
108
+ raw_num = int(match.group(1))
109
+ if 1 <= raw_num <= len(chunks):
110
+ chunk = chunks[raw_num - 1]
111
+ if chunk.url in known_source_urls:
112
+ if chunk.url not in url_to_new_n:
113
+ new_n = len(citations) + 1
114
+ url_to_new_n[chunk.url] = new_n
115
+ citations.append({"n": new_n, "url": chunk.url})
116
+ else:
117
+ new_n = url_to_new_n[chunk.url]
118
+ return f"[{new_n}]"
119
+ logger.warning("Stripping out-of-range or unindexed citation [%d]", raw_num)
120
+ return ""
121
+
122
+ verified_text = re.sub(r"\[(\d+)\]", _rewrite_marker, text)
123
+ verified_text = re.sub(r"(\[\d+\])(?:\s*\1)+", r"\1", verified_text)
124
+ verified_text = re.sub(r"[ \t]+([.,;:])", r"\1", verified_text)
125
+ verified_text = re.sub(r" {2,}", " ", verified_text).strip()
126
+
127
+ # Invariant: never return factual prose with zero verified citations.
128
+ if not citations or not verified_text:
129
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
130
+
131
+ return AnswerResult(
132
+ answer=verified_text,
133
+ citations=citations,
134
+ route="answered",
135
+ )
136
+
137
+
138
+ async def synthesize_answer(
139
+ question: str,
140
+ index: VectorIndex,
141
+ llm: LLMClient,
142
+ settings: Settings | None = None,
143
+ ) -> AnswerResult:
144
+ """Retrieve top-5 non-stale chunks, run 1 grounded LLM call, and verify citations."""
145
+ cfg = settings or get_settings()
146
+ chunks = index.search(question, top_k=cfg.answer_top_k, hybrid_rerank=True)
147
+ if not chunks:
148
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
149
+
150
+ excerpts: list[str] = []
151
+ for i, ch in enumerate(chunks, start=1):
152
+ title_part = f" | Title: {ch.title}" if ch.title else ""
153
+ excerpts.append(f"[{i}] URL: {ch.url}{title_part}\n{ch.content}")
154
+ context_block = "\n\n---\n\n".join(excerpts)
155
+
156
+ user_prompt = (
157
+ f"Excerpts:\n{context_block}\n\n"
158
+ f"Question: {question}"
159
+ )
160
+
161
+ raw = await llm.chat(
162
+ ANSWERER_SYSTEM_PROMPT,
163
+ user_prompt,
164
+ json_mode=True,
165
+ temperature=0.0,
166
+ )
167
+ known_urls = index.get_source_urls()
168
+
169
+ parsed = _extract_json_dict(raw)
170
+ if parsed is not None:
171
+ if not parsed.get("found"):
172
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
173
+ ans_text = str(parsed.get("answer") or "").strip()
174
+ if not ans_text:
175
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
176
+ supp = parsed.get("supporting_excerpt_number")
177
+ if (
178
+ not re.search(r"\[\d+(?:\s*,\s*\d+)*\]", ans_text)
179
+ and isinstance(supp, int)
180
+ and not isinstance(supp, bool)
181
+ and 1 <= supp <= len(chunks)
182
+ ):
183
+ ans_text = f"{ans_text} [{supp}]"
184
+ return verify_and_format_answer(ans_text, chunks, known_urls)
185
+
186
+ return verify_and_format_answer(raw, chunks, known_urls)
scoutrag/api.py ADDED
@@ -0,0 +1,89 @@
1
+ """FastAPI server and static UI mount for ScoutRAG."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from fastapi import FastAPI, HTTPException
10
+ from fastapi.responses import FileResponse
11
+ from pydantic import BaseModel, Field
12
+
13
+ from scoutrag.config import Settings, get_settings
14
+ from scoutrag.llm import LLMConfigError, LLMRequestError
15
+ from scoutrag.pipeline import ScoutRAGAgent
16
+ from scoutrag.planner import SearchUnavailableError
17
+
18
+ UI_PATH = Path(__file__).resolve().parent.parent / "ui" / "index.html"
19
+
20
+
21
+ class AskRequest(BaseModel):
22
+ question: str = Field(..., min_length=1)
23
+
24
+
25
+ def create_app(settings: Settings | None = None) -> FastAPI:
26
+ @asynccontextmanager
27
+ async def lifespan(app_instance: FastAPI):
28
+ agent = ScoutRAGAgent(settings or get_settings())
29
+ app_instance.state.agent = agent
30
+ try:
31
+ yield
32
+ finally:
33
+ await agent.close()
34
+
35
+ app_instance = FastAPI(
36
+ title="ScoutRAG",
37
+ description="Active-exploration RAG agent that fetches live sources when coverage is thin.",
38
+ version="0.1.0",
39
+ lifespan=lifespan,
40
+ )
41
+
42
+ def _get_agent() -> ScoutRAGAgent:
43
+ agent = getattr(app_instance.state, "agent", None)
44
+ if agent is None:
45
+ agent = ScoutRAGAgent(settings or get_settings())
46
+ app_instance.state.agent = agent
47
+ return agent
48
+
49
+ @app_instance.get("/")
50
+ @app_instance.get("/ui")
51
+ @app_instance.get("/ui/index.html")
52
+ async def serve_ui() -> FileResponse:
53
+ if not UI_PATH.exists():
54
+ raise HTTPException(status_code=404, detail="ui/index.html not found")
55
+ return FileResponse(UI_PATH, media_type="text/html")
56
+
57
+ @app_instance.get("/health")
58
+ async def health() -> dict[str, str]:
59
+ return {"status": "ok"}
60
+
61
+ @app_instance.post("/ask")
62
+ async def ask(req: AskRequest) -> dict[str, Any]:
63
+ agent = _get_agent()
64
+ try:
65
+ return await agent.ask(req.question)
66
+ except ValueError as exc:
67
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
68
+ except LLMConfigError as exc:
69
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
70
+ except SearchUnavailableError as exc:
71
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
72
+ except LLMRequestError as exc:
73
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
74
+
75
+ @app_instance.get("/index")
76
+ async def get_index() -> dict[str, Any]:
77
+ agent = _get_agent()
78
+ return agent.index.list_sources()
79
+
80
+ @app_instance.delete("/index")
81
+ async def delete_index() -> dict[str, Any]:
82
+ agent = _get_agent()
83
+ counts = agent.index.clear()
84
+ return {"cleared": True, **counts}
85
+
86
+ return app_instance
87
+
88
+
89
+ app = create_app()
scoutrag/cli.py ADDED
@@ -0,0 +1,136 @@
1
+ """CLI entry point for ScoutRAG."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ import logging
9
+ import sys
10
+
11
+ import uvicorn
12
+
13
+ from scoutrag.indexer import VectorIndex
14
+ from scoutrag.llm import LLMConfigError, LLMRequestError
15
+ from scoutrag.pipeline import ScoutRAGAgent
16
+ from scoutrag.planner import SearchUnavailableError
17
+
18
+
19
+ async def _run_ask(question: str) -> dict:
20
+ agent = ScoutRAGAgent()
21
+ try:
22
+ return await agent.ask(question)
23
+ finally:
24
+ await agent.close()
25
+
26
+
27
+ def _print_ask_result(result: dict) -> None:
28
+ cov = result["coverage"]
29
+ route_label = str(result["route"]).upper().replace("_", " ")
30
+ print(f"\n[{route_label}] hits={cov['hits']} best_similarity={cov['best_similarity']:.4f} latency={result['latency_ms']}ms")
31
+
32
+ queries = result.get("queries") or []
33
+ if queries:
34
+ print("\nPlanner queries:")
35
+ for q in queries:
36
+ print(f" - {q}")
37
+
38
+ pages = result.get("fetched_pages") or []
39
+ if pages:
40
+ print(f"\nFetched pages ({len(pages)}):")
41
+ for p in pages:
42
+ print(f" - [{p['status']}] {p['url']}")
43
+
44
+ print("\nAnswer:")
45
+ print(result["answer"])
46
+
47
+ citations = result.get("citations") or []
48
+ if citations:
49
+ print("\nCitations:")
50
+ for c in citations:
51
+ print(f" [{c['n']}] {c['url']}")
52
+ print()
53
+
54
+
55
+ def main(argv: list[str] | None = None) -> int:
56
+ logging.basicConfig(
57
+ level=logging.INFO,
58
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
59
+ )
60
+
61
+ parser = argparse.ArgumentParser(
62
+ prog="scoutrag",
63
+ description="ScoutRAG — active-exploration RAG agent",
64
+ )
65
+ sub = parser.add_subparsers(dest="command")
66
+
67
+ ask_p = sub.add_parser("ask", help="Ask a question (explores live web if index coverage is thin)")
68
+ ask_p.add_argument("question", help="Question to answer")
69
+ ask_p.add_argument("--json", action="store_true", help="Print full JSON response")
70
+
71
+ idx_p = sub.add_parser("index", help="Inspect or clear the local vector index")
72
+ idx_p.add_argument("--list", action="store_true", help="List indexed sources")
73
+ idx_p.add_argument("--clear", action="store_true", help="Clear the index")
74
+ idx_p.add_argument("--json", action="store_true", help="Print JSON output")
75
+
76
+ serve_p = sub.add_parser("serve", help="Start the FastAPI server and web UI")
77
+ serve_p.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
78
+ serve_p.add_argument("--port", type=int, default=8000, help="Bind port (default: 8000)")
79
+
80
+ args = parser.parse_args(argv)
81
+ if not args.command:
82
+ parser.print_help()
83
+ return 0
84
+
85
+ if args.command == "ask":
86
+ try:
87
+ result = asyncio.run(_run_ask(args.question))
88
+ except (LLMConfigError, LLMRequestError, SearchUnavailableError, ValueError) as exc:
89
+ print(f"Error: {exc}", file=sys.stderr)
90
+ return 1
91
+ if args.json:
92
+ print(json.dumps(result, indent=2, ensure_ascii=False))
93
+ else:
94
+ _print_ask_result(result)
95
+ return 0
96
+
97
+ if args.command == "index":
98
+ idx = VectorIndex()
99
+ if args.clear:
100
+ counts = idx.clear()
101
+ if args.json:
102
+ print(json.dumps({"cleared": True, **counts}, indent=2))
103
+ else:
104
+ print(
105
+ f"Cleared index: {counts['deleted_sources']} sources, "
106
+ f"{counts['deleted_chunks']} chunks."
107
+ )
108
+ return 0
109
+
110
+ # Default to --list if neither flag was given or --list was passed.
111
+ data = idx.list_sources()
112
+ if args.json:
113
+ print(json.dumps(data, indent=2, ensure_ascii=False))
114
+ else:
115
+ print(
116
+ f"Sources: {data['total_sources']} | "
117
+ f"Chunks: {data['total_chunks']} | "
118
+ f"Stale (>7d): {data['stale_count']}"
119
+ )
120
+ for s in data["sources"]:
121
+ stale_tag = " [STALE]" if s["stale"] else ""
122
+ print(
123
+ f" - {s['url']} chunks={s['chunk_count']} "
124
+ f"status={s['status']} fetched_at={s['fetched_at']}{stale_tag}"
125
+ )
126
+ return 0
127
+
128
+ if args.command == "serve":
129
+ uvicorn.run("scoutrag.api:app", host=args.host, port=args.port)
130
+ return 0
131
+
132
+ return 0
133
+
134
+
135
+ if __name__ == "__main__":
136
+ sys.exit(main())
scoutrag/config.py ADDED
@@ -0,0 +1,87 @@
1
+ """Runtime configuration for ScoutRAG.
2
+
3
+ Settings are loaded on demand from environment variables so tests and CLI callers
4
+ can override paths or toggle the opt-in Gemini backend cleanly without module reload hacks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Settings:
16
+ data_dir: Path
17
+ db_path: Path
18
+ log_path: Path
19
+ llm_provider: str
20
+ ollama_base_url: str
21
+ ollama_model: str
22
+ gemini_api_key: str
23
+ gemini_model: str
24
+ search_backend: str = ""
25
+ search_api_key: str = ""
26
+ ddg_html_url: str = "https://html.duckduckgo.com/html/"
27
+ brave_search_url: str = "https://api.search.brave.com/res/v1/web/search"
28
+ cc_collinfo_url: str = "https://index.commoncrawl.org/collinfo.json"
29
+ embed_model: str = "all-MiniLM-L6-v2"
30
+ # Deliberate deviation from ~500 tokens: all-MiniLM-L6-v2 silently truncates inputs
31
+ # past 256 wordpiece tokens, so chunking at ~256 tokens (with 50-token overlap) keeps
32
+ # 100% of every chunk represented in its embedding while top-5 retrieval still feeds
33
+ # ~1,280 tokens of context to the synthesis model.
34
+ chunk_size_tokens: int = 256
35
+ chunk_overlap_tokens: int = 50
36
+ hit_similarity_threshold: float = 0.35
37
+ best_similarity_threshold: float = 0.45
38
+ min_hits: int = 3
39
+ coverage_top_k: int = 10
40
+ answer_top_k: int = 5
41
+ stale_after_days: int = 7
42
+ max_pages_per_question: int = 8
43
+ page_timeout_ms: int = 15_000
44
+ per_host_delay_s: float = 1.0
45
+ ddg_pause_s: float = 1.0
46
+
47
+
48
+ def get_settings() -> Settings:
49
+ data_dir = Path(os.environ.get("SCOUTRAG_DATA_DIR", str(Path.home() / ".scoutrag"))).expanduser()
50
+ db_path = Path(os.environ.get("SCOUTRAG_DB_PATH", str(data_dir / "scoutrag.db"))).expanduser()
51
+ log_path = Path(os.environ.get("SCOUTRAG_LOG_PATH", str(data_dir / "queries.jsonl"))).expanduser()
52
+
53
+ llm_provider = os.environ.get("SCOUTRAG_LLM", "").strip().lower()
54
+ ollama_base_url = os.environ.get("SCOUTRAG_OLLAMA_URL", "http://localhost:11434").strip().rstrip("/")
55
+ ollama_model = os.environ.get("SCOUTRAG_OLLAMA_MODEL", "qwen2.5:7b").strip() or "qwen2.5:7b"
56
+ gemini_api_key = os.environ.get("GEMINI_API_KEY", "").strip()
57
+ gemini_model = os.environ.get("SCOUTRAG_GEMINI_MODEL", "gemini-2.5-flash").strip() or "gemini-2.5-flash"
58
+ search_backend = os.environ.get("SCOUTRAG_SEARCH", "").strip().lower()
59
+ search_api_key = os.environ.get("SCOUTRAG_SEARCH_API_KEY", "").strip()
60
+ ddg_html_url = (
61
+ os.environ.get("SCOUTRAG_DDG_URL", "https://html.duckduckgo.com/html/").strip()
62
+ or "https://html.duckduckgo.com/html/"
63
+ )
64
+ brave_search_url = (
65
+ os.environ.get("SCOUTRAG_BRAVE_URL", "https://api.search.brave.com/res/v1/web/search").strip()
66
+ or "https://api.search.brave.com/res/v1/web/search"
67
+ )
68
+ cc_collinfo_url = (
69
+ os.environ.get("SCOUTRAG_CC_COLLINFO_URL", "https://index.commoncrawl.org/collinfo.json").strip()
70
+ or "https://index.commoncrawl.org/collinfo.json"
71
+ )
72
+
73
+ return Settings(
74
+ data_dir=data_dir,
75
+ db_path=db_path,
76
+ log_path=log_path,
77
+ llm_provider=llm_provider,
78
+ ollama_base_url=ollama_base_url,
79
+ ollama_model=ollama_model,
80
+ gemini_api_key=gemini_api_key,
81
+ gemini_model=gemini_model,
82
+ search_backend=search_backend,
83
+ search_api_key=search_api_key,
84
+ ddg_html_url=ddg_html_url,
85
+ brave_search_url=brave_search_url,
86
+ cc_collinfo_url=cc_collinfo_url,
87
+ )
scoutrag/coverage.py ADDED
@@ -0,0 +1,81 @@
1
+ """Inspectable coverage gate for ScoutRAG.
2
+
3
+ Before answering or searching, ScoutRAG checks what its local index actually covers
4
+ using two explicit metrics:
5
+ 1. `hits`: number of non-stale retrieved chunks >= hit_similarity_threshold (0.35)
6
+ 2. `best_similarity`: peak cosine similarity among non-stale retrieved chunks (>= 0.45)
7
+
8
+ If hits >= 3 and best_similarity >= 0.45 -> verdict INDEX (answer from index).
9
+ Otherwise -> verdict EXPLORE (trigger live web exploration).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+
16
+ from scoutrag.config import Settings, get_settings
17
+ from scoutrag.indexer import RetrievedChunk, VectorIndex
18
+ from scoutrag.logging_utils import logger
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class CoverageResult:
23
+ verdict: str # "INDEX" | "EXPLORE"
24
+ hits: int
25
+ best_similarity: float
26
+ chunks: list[RetrievedChunk]
27
+
28
+ def to_dict(self) -> dict[str, float | int]:
29
+ return {
30
+ "hits": self.hits,
31
+ "best_similarity": round(self.best_similarity, 4),
32
+ }
33
+
34
+ def thin_summary(self, max_items: int = 3) -> str:
35
+ if not self.chunks:
36
+ return "Index is empty (0 non-stale chunks)."
37
+ lines = [
38
+ f"Retrieved {len(self.chunks)} chunks; hits>={0.35:.2f}: {self.hits}; "
39
+ f"best_similarity={self.best_similarity:.3f}."
40
+ ]
41
+ for ch in self.chunks[:max_items]:
42
+ snippet = " ".join(ch.content.split())[:140]
43
+ lines.append(f"- ({ch.similarity:.3f}) {ch.url} :: {snippet}")
44
+ return "\n".join(lines)
45
+
46
+
47
+ def evaluate_coverage(
48
+ question: str,
49
+ index: VectorIndex,
50
+ settings: Settings | None = None,
51
+ ) -> CoverageResult:
52
+ """Compute and log the inspectable coverage verdict for a question."""
53
+ cfg = settings or get_settings()
54
+ chunks = index.search(question, top_k=cfg.coverage_top_k)
55
+
56
+ best_similarity = max((c.similarity for c in chunks), default=0.0)
57
+ hits = sum(1 for c in chunks if c.similarity >= cfg.hit_similarity_threshold)
58
+
59
+ verdict = (
60
+ "INDEX"
61
+ if (hits >= cfg.min_hits and best_similarity >= cfg.best_similarity_threshold)
62
+ else "EXPLORE"
63
+ )
64
+
65
+ logger.info(
66
+ "coverage verdict=%s hits=%d best_similarity=%.4f "
67
+ "(thresholds: min_hits=%d hit_sim>=%.2f best_sim>=%.2f)",
68
+ verdict,
69
+ hits,
70
+ best_similarity,
71
+ cfg.min_hits,
72
+ cfg.hit_similarity_threshold,
73
+ cfg.best_similarity_threshold,
74
+ )
75
+
76
+ return CoverageResult(
77
+ verdict=verdict,
78
+ hits=hits,
79
+ best_similarity=best_similarity,
80
+ chunks=chunks,
81
+ )