| 1 | #!/usr/bin/env python3 |
| 2 | """Compare two last30days revisions on the v3 ranked candidate output.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import argparse |
| 7 | import hashlib |
| 8 | import json |
| 9 | import math |
| 10 | import os |
| 11 | import shutil |
| 12 | import subprocess |
| 13 | import sys |
| 14 | import tempfile |
| 15 | from datetime import datetime |
| 16 | from pathlib import Path |
| 17 | from typing import Any, Callable, Optional |
| 18 | from urllib.error import HTTPError, URLError |
| 19 | from urllib.request import Request, urlopen |
| 20 | |
| 21 | sys.path.insert(0, str(Path(__file__).parent)) |
| 22 | |
| 23 | from lib import env as envlib |
| 24 | from lib import schema |
| 25 | from lib.providers import GEMINI_FLASH_LITE |
| 26 | |
| 27 | |
| 28 | SKILL_ROOT = Path(__file__).resolve().parents[1] |
| 29 | REPO_ROOT = Path(__file__).resolve().parents[3] |
| 30 | EVAL_TOPICS_FILE = REPO_ROOT / "fixtures" / "eval_topics.json" |
| 31 | REDDIT_COVERAGE_TOPICS_FILE = REPO_ROOT / "fixtures" / "reddit_coverage_topics.json" |
| 32 | |
| 33 | |
| 34 | def _load_default_topics() -> list[tuple[str, str]]: |
| 35 | if EVAL_TOPICS_FILE.exists(): |
| 36 | rows = json.loads(EVAL_TOPICS_FILE.read_text()) |
| 37 | return [(row["topic"], row["query_type"]) for row in rows] |
| 38 | return [ |
| 39 | ("nano banana pro prompting", "product"), |
| 40 | ("codex vs claude code", "comparison"), |
| 41 | ("openclaw vs nanoclaw vs ironclaw", "comparison"), |
| 42 | ("anthropic odds", "prediction"), |
| 43 | ("kanye west", "breaking_news"), |
| 44 | ("remotion animations for Claude Code", "how_to"), |
| 45 | ] |
| 46 | |
| 47 | |
| 48 | DEFAULT_TOPICS = _load_default_topics() |
| 49 | DEFAULT_SEARCH = "" |
| 50 | DEFAULT_JUDGE_MODEL = GEMINI_FLASH_LITE |
| 51 | GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}" |
| 52 | EVAL_CREDENTIAL_ENV_KEYS = ( |
| 53 | "GOOGLE_API_KEY", |
| 54 | "GEMINI_API_KEY", |
| 55 | "GOOGLE_GENAI_API_KEY", |
| 56 | "OPENAI_API_KEY", |
| 57 | "XAI_API_KEY", |
| 58 | "SCRAPECREATORS_API_KEY", |
| 59 | "BSKY_HANDLE", |
| 60 | "BSKY_APP_PASSWORD", |
| 61 | "TRUTHSOCIAL_TOKEN", |
| 62 | "AUTH_TOKEN", |
| 63 | "CT0", |
| 64 | ) |
| 65 | |
| 66 | |
| 67 | def stable_item_key(item: dict[str, Any]) -> str: |
| 68 | return str(item.get("candidate_id") or item.get("url") or item.get("title") or "") |
| 69 | |
| 70 | |
| 71 | def row_sources(row: dict[str, Any]) -> list[str]: |
| 72 | candidate = schema.candidate_from_dict(row) |
| 73 | return schema.candidate_sources(candidate) |
| 74 | |
| 75 | |
| 76 | def row_best_date(row: dict[str, Any]) -> str | None: |
| 77 | candidate = schema.candidate_from_dict(row) |
| 78 | return schema.candidate_best_published_at(candidate) |
| 79 | |
| 80 | |
| 81 | V2_SOURCE_KEYS = [ |
| 82 | ("reddit", "title"), |
| 83 | ("x", "text"), |
| 84 | ("youtube", "title"), |
| 85 | ("tiktok", "text"), |
| 86 | ("instagram", "text"), |
| 87 | ("hackernews", "title"), |
| 88 | ("bluesky", "text"), |
| 89 | ("truthsocial", "text"), |
| 90 | ("polymarket", "question"), |
| 91 | ("web", "title"), |
| 92 | ] |
| 93 | |
| 94 | |
| 95 | def build_ranked_items(report: dict[str, Any], limit: int) -> list[dict[str, Any]]: |
| 96 | # v3 format: ranked_candidates list |
| 97 | if report.get("ranked_candidates"): |
| 98 | ranked = [] |
| 99 | for row in report["ranked_candidates"][:limit]: |
| 100 | candidate_sources = row_sources(row) |
| 101 | ranked.append({ |
| 102 | "key": stable_item_key(row), |
| 103 | "source": ", ".join(candidate_sources), |
| 104 | "sources": candidate_sources, |
| 105 | "url": str(row.get("url") or ""), |
| 106 | "text": str(row.get("title") or ""), |
| 107 | "date": row_best_date(row), |
| 108 | "score": float(row.get("final_score") or 0.0), |
| 109 | }) |
| 110 | return ranked |
| 111 | |
| 112 | # v2 format: per-source lists (reddit, x, youtube, etc.) |
| 113 | all_items = [] |
| 114 | for source_key, text_field in V2_SOURCE_KEYS: |
| 115 | for item in report.get(source_key) or []: |
| 116 | if not isinstance(item, dict): |
| 117 | continue |
| 118 | all_items.append({ |
| 119 | "key": str(item.get("url") or item.get("id") or item.get(text_field) or ""), |
| 120 | "source": source_key, |
| 121 | "sources": [source_key], |
| 122 | "url": str(item.get("url") or ""), |
| 123 | "text": str(item.get(text_field) or item.get("title") or ""), |
| 124 | "date": item.get("date"), |
| 125 | "score": float(item.get("score") or 0.0), |
| 126 | }) |
| 127 | all_items.sort(key=lambda x: x["score"], reverse=True) |
| 128 | return all_items[:limit] |
| 129 | |
| 130 | |
| 131 | def source_sets(report: dict[str, Any], limit: int) -> dict[str, set[str]]: |
| 132 | grouped: dict[str, set[str]] = {} |
| 133 | for item in build_ranked_items(report, limit): |
| 134 | for source in item["sources"]: |
| 135 | grouped.setdefault(source, set()).add(item["key"]) |
| 136 | return grouped |
| 137 | |
| 138 | |
| 139 | def jaccard(left: set[str], right: set[str]) -> float: |
| 140 | if not left and not right: |
| 141 | return 1.0 |
| 142 | union = left | right |
| 143 | if not union: |
| 144 | return 1.0 |
| 145 | return len(left & right) / len(union) |
| 146 | |
| 147 | |
| 148 | def retention(left: set[str], right: set[str]) -> float: |
| 149 | if not left: |
| 150 | return 1.0 |
| 151 | return len(left & right) / len(left) |
| 152 | |
| 153 | |
| 154 | def precision_at_k(ranking: list[dict[str, Any]], judgments: dict[str, int], k: int) -> float: |
| 155 | top = ranking[:k] |
| 156 | if not top: |
| 157 | return 0.0 |
| 158 | return sum(1 for item in top if judgments.get(item["key"], 0) >= 2) / len(top) |
| 159 | |
| 160 | |
| 161 | def ndcg_at_k(ranking: list[dict[str, Any]], judgments: dict[str, int], k: int, judged_pool: list[dict[str, Any]]) -> float: |
| 162 | top = ranking[:k] |
| 163 | if not top: |
| 164 | return 0.0 |
| 165 | |
| 166 | def dcg(grades: list[int]) -> float: |
| 167 | total = 0.0 |
| 168 | for index, grade in enumerate(grades, start=1): |
| 169 | total += (2**grade - 1) / math.log2(index + 1) |
| 170 | return total |
| 171 | |
| 172 | actual = [judgments.get(item["key"], 0) for item in top] |
| 173 | ideal = sorted((judgments.get(item["key"], 0) for item in judged_pool), reverse=True)[: len(top)] |
| 174 | ideal_score = dcg(ideal) |
| 175 | if ideal_score == 0: |
| 176 | return 0.0 |
| 177 | return dcg(actual) / ideal_score |
| 178 | |
| 179 | |
| 180 | def source_coverage_recall(ranking: list[dict[str, Any]], judged_pool: list[dict[str, Any]], judgments: dict[str, int]) -> float: |
| 181 | good_sources = { |
| 182 | source |
| 183 | for item in judged_pool |
| 184 | if judgments.get(item["key"], 0) >= 2 |
| 185 | for source in item["sources"] |
| 186 | } |
| 187 | if not good_sources: |
| 188 | return 1.0 |
| 189 | hit_sources = { |
| 190 | source |
| 191 | for item in ranking |
| 192 | if judgments.get(item["key"], 0) >= 2 |
| 193 | for source in item["sources"] |
| 194 | } |
| 195 | return len(hit_sources & good_sources) / len(good_sources) |
| 196 | |
| 197 | |
| 198 | def resolve_google_judge_api_key(config: dict[str, Any]) -> str | None: |
| 199 | return ( |
| 200 | os.environ.get("GOOGLE_API_KEY") |
| 201 | or config.get("GOOGLE_API_KEY") |
| 202 | or os.environ.get("GEMINI_API_KEY") |
| 203 | or config.get("GEMINI_API_KEY") |
| 204 | or os.environ.get("GOOGLE_GENAI_API_KEY") |
| 205 | or config.get("GOOGLE_GENAI_API_KEY") |
| 206 | ) |
| 207 | |
| 208 | |
| 209 | def extract_gemini_text(payload: dict[str, Any]) -> str: |
| 210 | for candidate in payload.get("candidates") or []: |
| 211 | content = candidate.get("content") or {} |
| 212 | for part in content.get("parts") or []: |
| 213 | if part.get("text"): |
| 214 | return part["text"] |
| 215 | raise ValueError("Gemini response did not contain text.") |
| 216 | |
| 217 | |
| 218 | def call_gemini_judge(api_key: str, model: str, prompt: str) -> dict[str, Any]: |
| 219 | body = { |
| 220 | "contents": [{"parts": [{"text": prompt}]}], |
| 221 | "generationConfig": {"temperature": 0, "responseMimeType": "application/json"}, |
| 222 | } |
| 223 | request = Request( |
| 224 | GEMINI_API_URL.format(model=model, api_key=api_key), |
| 225 | data=json.dumps(body).encode("utf-8"), |
| 226 | headers={"Content-Type": "application/json"}, |
| 227 | method="POST", |
| 228 | ) |
| 229 | try: |
| 230 | with urlopen(request, timeout=120) as response: |
| 231 | payload = json.loads(response.read().decode("utf-8")) |
| 232 | except HTTPError as exc: |
| 233 | detail = exc.read().decode("utf-8", errors="replace") |
| 234 | raise RuntimeError(f"Gemini HTTP {exc.code}: {detail}") from exc |
| 235 | except URLError as exc: |
| 236 | raise RuntimeError(f"Gemini request failed: {exc}") from exc |
| 237 | return json.loads(extract_gemini_text(payload)) |
| 238 | |
| 239 | |
| 240 | def build_judge_prompt(topic: str, query_type: str, items: list[dict[str, Any]]) -> str: |
| 241 | item_lines = [] |
| 242 | for item in items: |
| 243 | item_lines.append( |
| 244 | "\n".join([ |
| 245 | f"- id: {item['key']}", |
| 246 | f" source: {item['source']}", |
| 247 | f" title: {item['text'][:220]}", |
| 248 | f" url: {item['url']}", |
| 249 | f" date: {item.get('date') or 'unknown'}", |
| 250 | ]) |
| 251 | ) |
| 252 | return f""" |
| 253 | Judge search-result relevance for a last-30-days research tool. |
| 254 | |
| 255 | Topic: {topic} |
| 256 | Query type: {query_type} |
| 257 | |
| 258 | Score each item on this 0-3 scale: |
| 259 | - 0 = off-topic or clearly bad |
| 260 | - 1 = weak or tangential |
| 261 | - 2 = relevant and useful |
| 262 | - 3 = highly relevant, one of the best results |
| 263 | |
| 264 | Return JSON only: |
| 265 | {{ |
| 266 | "judgments": [ |
| 267 | {{"id": "ITEM_ID", "grade": 0}} |
| 268 | ] |
| 269 | }} |
| 270 | |
| 271 | Items: |
| 272 | {chr(10).join(item_lines)} |
| 273 | """.strip() |
| 274 | |
| 275 | |
| 276 | def get_judgments( |
| 277 | *, |
| 278 | output_dir: Path, |
| 279 | slug: str, |
| 280 | topic: str, |
| 281 | query_type: str, |
| 282 | items: list[dict[str, Any]], |
| 283 | judge_model: str, |
| 284 | gemini_api_key: str | None, |
| 285 | ) -> dict[str, int]: |
| 286 | cache_file = output_dir / "judgments" / f"{slug}.json" |
| 287 | cache_file.parent.mkdir(parents=True, exist_ok=True) |
| 288 | prompt = build_judge_prompt(topic, query_type, items) |
| 289 | input_sha256 = hashlib.sha256(json.dumps([judge_model, prompt]).encode("utf-8")).hexdigest() |
| 290 | stale_cache = False |
| 291 | if cache_file.exists(): |
| 292 | payload = json.loads(cache_file.read_text()) |
| 293 | if payload.get("input_sha256") == input_sha256: |
| 294 | return {row["id"]: int(row["grade"]) for row in payload.get("judgments") or []} |
| 295 | stale_cache = True |
| 296 | if not gemini_api_key or not items: |
| 297 | if stale_cache and not gemini_api_key: |
| 298 | sys.stderr.write( |
| 299 | f"[Eval] Cached judgments for {slug!r} have different or unverified " |
| 300 | f"judge inputs/model and no Gemini API key is set to re-judge; returning " |
| 301 | f"no grades (metrics for this topic will be zero).\n" |
| 302 | ) |
| 303 | return {} |
| 304 | payload = call_gemini_judge(gemini_api_key, judge_model, prompt) |
| 305 | payload["judge_model"] = judge_model |
| 306 | payload["input_sha256"] = input_sha256 |
| 307 | cache_file.write_text(json.dumps(payload, indent=2)) |
| 308 | return {row["id"]: int(row["grade"]) for row in payload.get("judgments") or []} |
| 309 | |
| 310 | |
| 311 | def create_eval_env(load_credentials: bool = True) -> dict[str, str]: |
| 312 | passthrough = { |
| 313 | "PATH": os.environ.get("PATH", ""), |
| 314 | "LANG": os.environ.get("LANG", "en_US.UTF-8"), |
| 315 | "LC_ALL": os.environ.get("LC_ALL", ""), |
| 316 | "TMPDIR": os.environ.get("TMPDIR", ""), |
| 317 | "PYTHONUTF8": "1", |
| 318 | "LAST30DAYS_CONFIG_DIR": "", |
| 319 | } |
| 320 | # Without load_credentials there is no config load at all, so no .env |
| 321 | # read and no Keychain lookup; only keys already in the process env pass. |
| 322 | config = envlib.get_config() if load_credentials else {} |
| 323 | for key in EVAL_CREDENTIAL_ENV_KEYS: |
| 324 | value = os.environ.get(key) or config.get(key) |
| 325 | if value: |
| 326 | passthrough[key] = value |
| 327 | return passthrough |
| 328 | |
| 329 | |
| 330 | # --reddit-coverage measures the keyless Reddit floor only, so runs stay |
| 331 | # comparable across machines and users: no ScrapeCreators key, no Keychain |
| 332 | # key, no logged-in Reddit session (its consent off and every browser read |
| 333 | # vetoed), and no host --reddit-threads envelope. |
| 334 | REDDIT_COVERAGE_DROPPED_ENV = ("SCRAPECREATORS_API_KEY", "REDDIT_SESSION_COOKIE") |
| 335 | REDDIT_COVERAGE_ENV = { |
| 336 | "REDDIT_BROWSER_CONSENT": "false", |
| 337 | "FROM_BROWSER": "off", |
| 338 | "LAST30DAYS_SKIP_KEYCHAIN": "1", |
| 339 | } |
| 340 | REDDIT_COVERAGE_SEARCH = "reddit" |
| 341 | NO_BASELINE = ("", "none") |
| 342 | |
| 343 | # Run inside the candidate tree's scripts dir: the same title check judges |
| 344 | # baseline and candidate output, so an engine without a topic bar is not |
| 345 | # credited for the threads it kept. Reads {"topic", "titles"} on stdin. |
| 346 | _TITLE_JUDGE_SNIPPET = ( |
| 347 | "import json, sys\n" |
| 348 | "from lib import rerank\n" |
| 349 | "payload = json.load(sys.stdin)\n" |
| 350 | "entity = rerank._primary_entity(payload['topic']).lower()\n" |
| 351 | "print(json.dumps([bool(rerank._entity_grounded(t, entity)) if entity else True" |
| 352 | " for t in payload['titles']]))\n" |
| 353 | ) |
| 354 | |
| 355 | TitleJudge = Callable[[str, list[str]], list[bool]] |
| 356 | |
| 357 | |
| 358 | def create_reddit_coverage_env() -> dict[str, str]: |
| 359 | """The eval env for --reddit-coverage: the floor only (see above).""" |
| 360 | run_env = create_eval_env(load_credentials=False) |
| 361 | for key in REDDIT_COVERAGE_DROPPED_ENV: |
| 362 | run_env.pop(key, None) |
| 363 | run_env.update(REDDIT_COVERAGE_ENV) |
| 364 | return run_env |
| 365 | |
| 366 | |
| 367 | def load_reddit_coverage_topics(path: Path) -> list[dict[str, Any]]: |
| 368 | rows = json.loads(path.read_text()) |
| 369 | return [ |
| 370 | { |
| 371 | "topic": str(row["topic"]), |
| 372 | "kind": str(row.get("kind") or "general"), |
| 373 | "expect_coverage": bool(row.get("expect_coverage", True)), |
| 374 | } |
| 375 | for row in rows |
| 376 | ] |
| 377 | |
| 378 | |
| 379 | def _scripts_dir(repo_dir: Path) -> Path: |
| 380 | scripts = repo_dir / "skills" / "last30days" / "scripts" |
| 381 | return scripts if scripts.exists() else repo_dir / "scripts" |
| 382 | |
| 383 | |
| 384 | def make_title_judge(repo_dir: Path) -> TitleJudge: |
| 385 | """On-topic verdicts for thread titles, from ``repo_dir``'s rerank check.""" |
| 386 | scripts = _scripts_dir(repo_dir) |
| 387 | |
| 388 | def judge(topic: str, titles: list[str]) -> list[bool]: |
| 389 | if not titles: |
| 390 | return [] |
| 391 | result = subprocess.run( |
| 392 | [sys.executable, "-c", _TITLE_JUDGE_SNIPPET], |
| 393 | cwd=scripts, |
| 394 | input=json.dumps({"topic": topic, "titles": titles}), |
| 395 | env={"PATH": os.environ.get("PATH", ""), "PYTHONUTF8": "1", "LAST30DAYS_CONFIG_DIR": ""}, |
| 396 | capture_output=True, |
| 397 | text=True, |
| 398 | timeout=60, |
| 399 | check=False, |
| 400 | ) |
| 401 | if result.returncode != 0: |
| 402 | raise RuntimeError(f"title judge failed in {scripts}: {result.stderr.strip()[-400:]}") |
| 403 | verdicts = json.loads(result.stdout) |
| 404 | if len(verdicts) != len(titles): |
| 405 | raise RuntimeError("title judge returned the wrong number of verdicts") |
| 406 | return [bool(v) for v in verdicts] |
| 407 | |
| 408 | return judge |
| 409 | |
| 410 | |
| 411 | def reddit_items(report: dict[str, Any]) -> list[dict[str, Any]]: |
| 412 | """The run's Reddit threads as ``{title, comments, pending}`` rows. |
| 413 | |
| 414 | Reads the raw report's ``items_by_source`` (current engines) or the v2 |
| 415 | top-level ``reddit`` list (older ones). |
| 416 | """ |
| 417 | raw = (report.get("items_by_source") or {}).get("reddit") |
| 418 | if raw is None: |
| 419 | raw = report.get("reddit") or [] |
| 420 | rows = [] |
| 421 | for item in raw: |
| 422 | if not isinstance(item, dict): |
| 423 | continue |
| 424 | meta = item.get("metadata") if isinstance(item.get("metadata"), dict) else {} |
| 425 | comments = meta.get("top_comments") or item.get("top_comments") or [] |
| 426 | source = meta.get("engagement_source") or item.get("engagement_source") |
| 427 | rows.append({ |
| 428 | "title": str(item.get("title") or ""), |
| 429 | "comments": len(comments) if isinstance(comments, list) else 0, |
| 430 | "pending": source == "arctic-pending", |
| 431 | }) |
| 432 | return rows |
| 433 | |
| 434 | |
| 435 | def reddit_served_path(report: dict[str, Any]) -> str: |
| 436 | """The Reddit outcome detail (served path), else its state, else ``-``.""" |
| 437 | outcome = (report.get("source_status") or {}).get("reddit") or {} |
| 438 | if not isinstance(outcome, dict): |
| 439 | return "-" |
| 440 | return str(outcome.get("detail") or outcome.get("state") or "-") |
| 441 | |
| 442 | |
| 443 | def summarize_reddit_coverage(report: dict[str, Any], topic: str, judge: TitleJudge) -> dict[str, Any]: |
| 444 | rows = reddit_items(report) |
| 445 | verdicts = judge(topic, [row["title"] for row in rows]) |
| 446 | on_topic = [row for row, keep in zip(rows, verdicts) if keep] |
| 447 | pending = sum(1 for row in on_topic if row["pending"]) |
| 448 | return { |
| 449 | "threads": len(rows), |
| 450 | "on_topic": len(on_topic), |
| 451 | "pending_share": (pending / len(on_topic)) if on_topic else 0.0, |
| 452 | "comments": sum(row["comments"] for row in on_topic), |
| 453 | "served_path": reddit_served_path(report), |
| 454 | } |
| 455 | |
| 456 | |
| 457 | def reddit_coverage_flag(row: dict[str, Any]) -> str: |
| 458 | """A note for a topic with no on-topic candidate thread; never a failure.""" |
| 459 | if row["candidate"]["on_topic"]: |
| 460 | return "" |
| 461 | return "no coverage (expected)" if not row["expect_coverage"] else "zero on-topic" |
| 462 | |
| 463 | |
| 464 | def write_reddit_coverage_summary( |
| 465 | output_dir: Path, |
| 466 | baseline_label: Optional[str], |
| 467 | candidate_label: str, |
| 468 | rows: list[dict[str, Any]], |
| 469 | failures: list[dict[str, Any]], |
| 470 | ) -> str: |
| 471 | output_dir.mkdir(parents=True, exist_ok=True) |
| 472 | generated = datetime.now().isoformat(timespec="seconds") |
| 473 | payload = { |
| 474 | "generated_at": generated, |
| 475 | "baseline": baseline_label, |
| 476 | "candidate": candidate_label, |
| 477 | "topics": rows, |
| 478 | "failures": failures, |
| 479 | } |
| 480 | (output_dir / "reddit-coverage.json").write_text(json.dumps(payload, indent=2)) |
| 481 | |
| 482 | def cell(summary: Optional[dict[str, Any]]) -> str: |
| 483 | if summary is None: |
| 484 | return "- | - | - | -" |
| 485 | return "{on_topic}/{threads} | {pending:.0%} | {comments} | {path}".format( |
| 486 | on_topic=summary["on_topic"], threads=summary["threads"], |
| 487 | pending=summary["pending_share"], comments=summary["comments"], |
| 488 | path=summary["served_path"].replace("|", "/"), |
| 489 | ) |
| 490 | |
| 491 | lines = [ |
| 492 | "# Reddit Coverage Evaluation", |
| 493 | "", |
| 494 | f"- Baseline: `{baseline_label or 'none'}`", |
| 495 | f"- Candidate: `{candidate_label}`", |
| 496 | f"- Generated: {generated}", |
| 497 | "- On-topic: thread titles that pass the candidate tree's rerank entity check.", |
| 498 | "", |
| 499 | "| Topic | Kind | Base on-topic | Base pending | Base comments | Base path" |
| 500 | " | Cand on-topic | Cand pending | Cand comments | Cand path | Note |", |
| 501 | "|---|---|---:|---:|---:|---|---:|---:|---:|---|---|", |
| 502 | ] |
| 503 | for row in rows: |
| 504 | lines.append( |
| 505 | f"| {row['topic']} | {row['kind']} | {cell(row['baseline'])} | {cell(row['candidate'])} | {row['flag']} |" |
| 506 | ) |
| 507 | if failures: |
| 508 | lines.extend(["", "## Failures", ""]) |
| 509 | lines.extend(f"- `{failure['topic']}`: {failure['error']}" for failure in failures) |
| 510 | text = "\n".join(lines) + "\n" |
| 511 | (output_dir / "reddit-coverage.md").write_text(text) |
| 512 | return text |
| 513 | |
| 514 | |
| 515 | def run_reddit_coverage(args: argparse.Namespace) -> int: |
| 516 | """--reddit-coverage: on-topic Reddit threads per topic, floor only.""" |
| 517 | topics = load_reddit_coverage_topics(Path(args.topics_file) if args.topics_file else REDDIT_COVERAGE_TOPICS_FILE) |
| 518 | if args.limit_topics: |
| 519 | topics = topics[: args.limit_topics] |
| 520 | output_dir = Path(args.output_dir).resolve() |
| 521 | run_env = create_reddit_coverage_env() |
| 522 | search = args.search or REDDIT_COVERAGE_SEARCH |
| 523 | baseline_label = None if str(args.baseline).strip().lower() in NO_BASELINE else args.baseline |
| 524 | |
| 525 | baseline_dir, baseline_temp = resolve_repo_dir(baseline_label) if baseline_label else (None, False) |
| 526 | candidate_dir, candidate_temp = resolve_repo_dir(args.candidate) |
| 527 | rows: list[dict[str, Any]] = [] |
| 528 | failures: list[dict[str, Any]] = [] |
| 529 | try: |
| 530 | judge = make_title_judge(candidate_dir) |
| 531 | for spec in topics: |
| 532 | topic = spec["topic"] |
| 533 | try: |
| 534 | runs = {} |
| 535 | for label, repo_dir in (("baseline", baseline_dir), ("candidate", candidate_dir)): |
| 536 | if repo_dir is None: |
| 537 | runs[label] = None |
| 538 | continue |
| 539 | report = run_last30days( |
| 540 | repo_dir, topic, search=search, timeout_seconds=args.timeout, |
| 541 | quick=args.quick, mock=args.mock, env=run_env, |
| 542 | ) |
| 543 | runs[label] = summarize_reddit_coverage(report, topic, judge) |
| 544 | row = {**spec, **runs} |
| 545 | row["flag"] = reddit_coverage_flag(row) |
| 546 | rows.append(row) |
| 547 | except Exception as exc: |
| 548 | failures.append({"topic": topic, "error": str(exc)}) |
| 549 | table = write_reddit_coverage_summary(output_dir, baseline_label, args.candidate, rows, failures) |
| 550 | finally: |
| 551 | if baseline_temp and baseline_dir is not None: |
| 552 | remove_worktree(baseline_dir) |
| 553 | if candidate_temp: |
| 554 | remove_worktree(candidate_dir) |
| 555 | sys.stderr.write(table) |
| 556 | print(json.dumps({"output_dir": str(output_dir), "topics": len(topics), "failures": len(failures)}, indent=2)) |
| 557 | return 1 if failures else 0 |
| 558 | |
| 559 | |
| 560 | # Top-level administrative/subcommand names dispatched by last30days.py when |
| 561 | # --research-only is unavailable on older checked-out revisions. |
| 562 | _RESERVED_ADMIN_COMMANDS = frozenset({ |
| 563 | "setup", |
| 564 | "doctor", |
| 565 | "library", |
| 566 | "queue", |
| 567 | "watchlist", |
| 568 | "watch", |
| 569 | "brief", |
| 570 | "briefing", |
| 571 | "briefs", |
| 572 | "diagnose", |
| 573 | "preflight", |
| 574 | "update", |
| 575 | "uninstall", |
| 576 | "help", |
| 577 | "version", |
| 578 | }) |
| 579 | |
| 580 | |
| 581 | def run_last30days(repo_dir: Path, topic: str, *, search: str, timeout_seconds: int, quick: bool, mock: bool, env: dict[str, str]) -> dict[str, Any]: |
| 582 | engine = repo_dir / "skills" / "last30days" / "scripts" / "last30days.py" |
| 583 | if not engine.exists(): |
| 584 | engine = repo_dir / "scripts" / "last30days.py" |
| 585 | engine_text = engine.read_text(encoding="utf-8") if engine.exists() else None |
| 586 | supports_research_only = engine_text is None or "--research-only" in engine_text |
| 587 | if not supports_research_only: |
| 588 | tokens = str(topic or "").strip().split() |
| 589 | if tokens and tokens[0].lower() in _RESERVED_ADMIN_COMMANDS: |
| 590 | raise ValueError( |
| 591 | f"Refusing to run reserved command topic {topic!r} against " |
| 592 | f"{repo_dir.name} without --research-only support." |
| 593 | ) |
| 594 | cmd = [sys.executable, str(engine), "--emit=json"] |
| 595 | # Prevent topics like "setup" or "library ..." from invoking administrative |
| 596 | # subcommands whenever the checked-out engine supports --research-only. |
| 597 | if supports_research_only: |
| 598 | cmd.append("--research-only") |
| 599 | # Current engines default to the stable agent export, while older revisions |
| 600 | # used by the evaluator implicitly emit the raw report and do not recognize |
| 601 | # --json-profile. Request raw explicitly whenever the checked-out engine |
| 602 | # supports the selector. |
| 603 | if engine_text is None or "--json-profile" in engine_text: |
| 604 | cmd.append("--json-profile=raw") |
| 605 | if search: |
| 606 | cmd.extend(["--search", search]) |
| 607 | if quick: |
| 608 | cmd.append("--quick") |
| 609 | if mock: |
| 610 | cmd.append("--mock") |
| 611 | cmd.extend(["--", topic]) |
| 612 | result = subprocess.run( |
| 613 | cmd, |
| 614 | cwd=repo_dir, |
| 615 | env=env, |
| 616 | capture_output=True, |
| 617 | text=True, |
| 618 | timeout=timeout_seconds, |
| 619 | check=False, |
| 620 | ) |
| 621 | if result.returncode != 0: |
| 622 | raise RuntimeError(f"{repo_dir.name} failed for '{topic}' with exit {result.returncode}\n{result.stderr.strip()}") |
| 623 | payload = json.loads(result.stdout) |
| 624 | # Shape guard: the evaluator compares raw Report fields. If the engine |
| 625 | # emitted the agent profile anyway (flag detection missed a future |
| 626 | # spelling), fail loudly instead of scoring empty ranked_candidates. |
| 627 | if "schema_version" in payload and "ranked_candidates" not in payload: |
| 628 | raise RuntimeError( |
| 629 | f"{repo_dir.name} emitted the agent JSON profile; the evaluator " |
| 630 | "requires the raw Report (--json-profile=raw)." |
| 631 | ) |
| 632 | return payload |
| 633 | |
| 634 | |
| 635 | def create_worktree(rev: str) -> Path: |
| 636 | if not isinstance(rev, str) or not rev.strip() or rev != rev.strip(): |
| 637 | raise ValueError(f"Invalid git revision: {rev!r}") |
| 638 | if rev.startswith("-") or any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in rev): |
| 639 | raise ValueError(f"Invalid git revision: {rev!r}") |
| 640 | resolved = subprocess.run( |
| 641 | ["git", "rev-parse", "--verify", "--end-of-options", f"{rev}^{{commit}}"], |
| 642 | cwd=REPO_ROOT, |
| 643 | check=True, |
| 644 | capture_output=True, |
| 645 | text=True, |
| 646 | ) |
| 647 | commit_sha = resolved.stdout.strip() |
| 648 | if not commit_sha or commit_sha.startswith("-"): |
| 649 | raise ValueError(f"Could not resolve git revision to a commit: {rev!r}") |
| 650 | worktree_dir = Path(tempfile.mkdtemp(prefix="last30days-eval-")) |
| 651 | try: |
| 652 | subprocess.run( |
| 653 | ["git", "worktree", "add", "--detach", str(worktree_dir), commit_sha], |
| 654 | cwd=REPO_ROOT, |
| 655 | check=True, |
| 656 | capture_output=True, |
| 657 | text=True, |
| 658 | ) |
| 659 | except BaseException: |
| 660 | remove_worktree(worktree_dir) |
| 661 | shutil.rmtree(worktree_dir, ignore_errors=True) |
| 662 | raise |
| 663 | return worktree_dir |
| 664 | |
| 665 | |
| 666 | def resolve_repo_dir(label: str) -> tuple[Path, bool]: |
| 667 | """Resolve a benchmark label into a repo directory and whether it is temporary.""" |
| 668 | if label == "WORKTREE": |
| 669 | return REPO_ROOT, False |
| 670 | return create_worktree(label), True |
| 671 | |
| 672 | |
| 673 | def remove_worktree(path: Path) -> None: |
| 674 | subprocess.run( |
| 675 | ["git", "worktree", "remove", "--force", str(path)], |
| 676 | cwd=REPO_ROOT, |
| 677 | check=False, |
| 678 | capture_output=True, |
| 679 | text=True, |
| 680 | ) |
| 681 | try: |
| 682 | os.rmdir(path) |
| 683 | except OSError: |
| 684 | pass |
| 685 | |
| 686 | |
| 687 | def summarize_topic(topic: str, query_type: str, baseline_report: dict[str, Any], candidate_report: dict[str, Any], judgments: dict[str, int], judged_pool: list[dict[str, Any]], limit: int) -> dict[str, Any]: |
| 688 | baseline_ranked = build_ranked_items(baseline_report, limit) |
| 689 | candidate_ranked = build_ranked_items(candidate_report, limit) |
| 690 | baseline_sets = source_sets(baseline_report, limit) |
| 691 | candidate_sets = source_sets(candidate_report, limit) |
| 692 | overall_left = set().union(*baseline_sets.values()) if baseline_sets else set() |
| 693 | overall_right = set().union(*candidate_sets.values()) if candidate_sets else set() |
| 694 | sources = sorted(set(baseline_sets) | set(candidate_sets)) |
| 695 | return { |
| 696 | "topic": topic, |
| 697 | "query_type": query_type, |
| 698 | "baseline": { |
| 699 | "precision_at_5": precision_at_k(baseline_ranked, judgments, 5), |
| 700 | "ndcg_at_5": ndcg_at_k(baseline_ranked, judgments, 5, judged_pool), |
| 701 | "source_coverage_recall": source_coverage_recall(baseline_ranked, judged_pool, judgments), |
| 702 | }, |
| 703 | "candidate": { |
| 704 | "precision_at_5": precision_at_k(candidate_ranked, judgments, 5), |
| 705 | "ndcg_at_5": ndcg_at_k(candidate_ranked, judgments, 5, judged_pool), |
| 706 | "source_coverage_recall": source_coverage_recall(candidate_ranked, judged_pool, judgments), |
| 707 | }, |
| 708 | "stability": { |
| 709 | "overall_jaccard": jaccard(overall_left, overall_right), |
| 710 | "overall_retention_vs_baseline": retention(overall_left, overall_right), |
| 711 | "per_source": { |
| 712 | source: { |
| 713 | "baseline_count": len(baseline_sets.get(source, set())), |
| 714 | "candidate_count": len(candidate_sets.get(source, set())), |
| 715 | "jaccard": jaccard(baseline_sets.get(source, set()), candidate_sets.get(source, set())), |
| 716 | "retention_vs_baseline": retention(baseline_sets.get(source, set()), candidate_sets.get(source, set())), |
| 717 | } |
| 718 | for source in sources |
| 719 | }, |
| 720 | }, |
| 721 | } |
| 722 | |
| 723 | |
| 724 | def write_summary(output_dir: Path, baseline_label: str, candidate_label: str, summaries: list[dict[str, Any]]) -> None: |
| 725 | output_dir.mkdir(parents=True, exist_ok=True) |
| 726 | payload = { |
| 727 | "generated_at": datetime.now().isoformat(timespec="seconds"), |
| 728 | "baseline": baseline_label, |
| 729 | "candidate": candidate_label, |
| 730 | "topics": summaries, |
| 731 | } |
| 732 | (output_dir / "metrics.json").write_text(json.dumps(payload, indent=2)) |
| 733 | |
| 734 | lines = [ |
| 735 | "# Search Quality Evaluation", |
| 736 | "", |
| 737 | f"- Baseline: `{baseline_label}`", |
| 738 | f"- Candidate: `{candidate_label}`", |
| 739 | f"- Generated: {payload['generated_at']}", |
| 740 | "", |
| 741 | "| Topic | Base P@5 | Cand P@5 | Base nDCG@5 | Cand nDCG@5 | Jaccard | Retention |", |
| 742 | "|---|---:|---:|---:|---:|---:|---:|", |
| 743 | ] |
| 744 | for row in summaries: |
| 745 | lines.append( |
| 746 | "| {topic} | {bp:.2f} | {cp:.2f} | {bn:.2f} | {cn:.2f} | {jac:.2f} | {ret:.2f} |".format( |
| 747 | topic=row["topic"], |
| 748 | bp=row["baseline"]["precision_at_5"], |
| 749 | cp=row["candidate"]["precision_at_5"], |
| 750 | bn=row["baseline"]["ndcg_at_5"], |
| 751 | cn=row["candidate"]["ndcg_at_5"], |
| 752 | jac=row["stability"]["overall_jaccard"], |
| 753 | ret=row["stability"]["overall_retention_vs_baseline"], |
| 754 | ) |
| 755 | ) |
| 756 | (output_dir / "summary.md").write_text("\n".join(lines) + "\n") |
| 757 | |
| 758 | |
| 759 | def write_failure_summary( |
| 760 | output_dir: Path, |
| 761 | baseline_label: str, |
| 762 | candidate_label: str, |
| 763 | summaries: list[dict[str, Any]], |
| 764 | failures: list[dict[str, Any]], |
| 765 | ) -> None: |
| 766 | write_summary(output_dir, baseline_label, candidate_label, summaries) |
| 767 | metrics_path = output_dir / "metrics.json" |
| 768 | payload = json.loads(metrics_path.read_text()) if metrics_path.exists() else { |
| 769 | "generated_at": datetime.now().isoformat(timespec="seconds"), |
| 770 | "baseline": baseline_label, |
| 771 | "candidate": candidate_label, |
| 772 | "topics": [], |
| 773 | } |
| 774 | payload["failures"] = failures |
| 775 | metrics_path.write_text(json.dumps(payload, indent=2)) |
| 776 | |
| 777 | summary_path = output_dir / "summary.md" |
| 778 | lines = summary_path.read_text().splitlines() if summary_path.exists() else ["# Search Quality Evaluation", ""] |
| 779 | if failures: |
| 780 | lines.extend([ |
| 781 | "", |
| 782 | "## Failures", |
| 783 | "", |
| 784 | ]) |
| 785 | for failure in failures: |
| 786 | lines.append(f"- `{failure['topic']}`: {failure['error']}") |
| 787 | summary_path.write_text("\n".join(lines).rstrip() + "\n") |
| 788 | |
| 789 | |
| 790 | def parse_topics_file(path: Path) -> list[tuple[str, str]]: |
| 791 | rows = json.loads(path.read_text()) |
| 792 | return [(str(row["topic"]), str(row.get("query_type") or "general")) for row in rows] |
| 793 | |
| 794 | |
| 795 | def build_parser() -> argparse.ArgumentParser: |
| 796 | parser = argparse.ArgumentParser(description="Compare two last30days revisions on ranked candidate quality") |
| 797 | parser.add_argument("--baseline", default="HEAD~1") |
| 798 | parser.add_argument("--candidate", default="WORKTREE") |
| 799 | parser.add_argument("--search", default=DEFAULT_SEARCH) |
| 800 | parser.add_argument("--output-dir", default="tmp/search-quality") |
| 801 | parser.add_argument("--judge-model", default=DEFAULT_JUDGE_MODEL) |
| 802 | parser.add_argument("--timeout", type=int, default=240) |
| 803 | parser.add_argument("--limit", type=int, default=20) |
| 804 | parser.add_argument("--mock", action="store_true") |
| 805 | parser.add_argument("--quick", action="store_true") |
| 806 | parser.add_argument("--topics-file") |
| 807 | parser.add_argument( |
| 808 | "--reddit-coverage", action="store_true", |
| 809 | help="count on-topic Reddit threads per topic (keyless floor only; " |
| 810 | "default topics fixtures/reddit_coverage_topics.json, default --search reddit; " |
| 811 | "--baseline none runs the candidate only)", |
| 812 | ) |
| 813 | parser.add_argument("--limit-topics", type=int, default=0, help="run only the first N topics") |
| 814 | return parser |
| 815 | |
| 816 | |
| 817 | def main() -> int: |
| 818 | args = build_parser().parse_args() |
| 819 | if args.reddit_coverage: |
| 820 | return run_reddit_coverage(args) |
| 821 | topics = parse_topics_file(Path(args.topics_file)) if args.topics_file else DEFAULT_TOPICS |
| 822 | output_dir = Path(args.output_dir).resolve() |
| 823 | config = envlib.get_config() |
| 824 | gemini_api_key = resolve_google_judge_api_key(config) |
| 825 | run_env = create_eval_env() |
| 826 | |
| 827 | baseline_dir, baseline_temp = resolve_repo_dir(args.baseline) |
| 828 | candidate_dir, candidate_temp = resolve_repo_dir(args.candidate) |
| 829 | try: |
| 830 | summaries = [] |
| 831 | failures = [] |
| 832 | for topic, query_type in topics: |
| 833 | try: |
| 834 | baseline_report = run_last30days( |
| 835 | baseline_dir, |
| 836 | topic, |
| 837 | search=args.search, |
| 838 | timeout_seconds=args.timeout, |
| 839 | quick=args.quick, |
| 840 | mock=args.mock, |
| 841 | env=run_env, |
| 842 | ) |
| 843 | candidate_report = run_last30days( |
| 844 | candidate_dir, |
| 845 | topic, |
| 846 | search=args.search, |
| 847 | timeout_seconds=args.timeout, |
| 848 | quick=args.quick, |
| 849 | mock=args.mock, |
| 850 | env=run_env, |
| 851 | ) |
| 852 | judged_pool_map = { |
| 853 | item["key"]: item |
| 854 | for item in build_ranked_items(baseline_report, args.limit) + build_ranked_items(candidate_report, args.limit) |
| 855 | } |
| 856 | judged_pool = list(judged_pool_map.values()) |
| 857 | judgments = get_judgments( |
| 858 | output_dir=output_dir, |
| 859 | slug="".join(char.lower() if char.isalnum() else "-" for char in topic).strip("-"), |
| 860 | topic=topic, |
| 861 | query_type=query_type, |
| 862 | items=judged_pool, |
| 863 | judge_model=args.judge_model, |
| 864 | gemini_api_key=gemini_api_key, |
| 865 | ) |
| 866 | summaries.append(summarize_topic(topic, query_type, baseline_report, candidate_report, judgments, judged_pool, args.limit)) |
| 867 | except Exception as exc: |
| 868 | failures.append({"topic": topic, "query_type": query_type, "error": str(exc)}) |
| 869 | write_failure_summary(output_dir, args.baseline, args.candidate, summaries, failures) |
| 870 | finally: |
| 871 | if baseline_temp: |
| 872 | remove_worktree(baseline_dir) |
| 873 | if candidate_temp: |
| 874 | remove_worktree(candidate_dir) |
| 875 | result = {"output_dir": str(output_dir), "topics": len(topics), "failures": len(failures)} |
| 876 | print(json.dumps(result, indent=2)) |
| 877 | return 1 if failures else 0 |
| 878 | |
| 879 | |
| 880 | if __name__ == "__main__": |
| 881 | raise SystemExit(main()) |
| 882 |