| 1 | """Offline research-quality eval harness built on recorded source responses.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import argparse |
| 6 | import contextlib |
| 7 | import itertools |
| 8 | import json |
| 9 | import socket |
| 10 | import sys |
| 11 | from dataclasses import dataclass |
| 12 | from datetime import datetime, timezone |
| 13 | from pathlib import Path |
| 14 | from typing import Any |
| 15 | from unittest import mock |
| 16 | |
| 17 | ROOT = Path(__file__).resolve().parents[2] |
| 18 | SCRIPTS = ROOT / "skills" / "last30days" / "scripts" |
| 19 | if str(SCRIPTS) not in sys.path: |
| 20 | sys.path.insert(0, str(SCRIPTS)) |
| 21 | |
| 22 | from lib import entity_extract, fetch_memo, http, pipeline, public_host, schema # noqa: E402 |
| 23 | |
| 24 | FIXTURES_DIR = Path(__file__).with_name("fixtures") |
| 25 | BASELINE_PATH = Path(__file__).with_name("baseline.json") |
| 26 | METRIC_NAMES = ( |
| 27 | "citation_grounding", |
| 28 | "recency_compliance", |
| 29 | "cluster_coherence", |
| 30 | "coverage", |
| 31 | "determinism", |
| 32 | ) |
| 33 | ENTITY_OVERLAP_FLOOR = 0.45 |
| 34 | # The address a fixture's listed public host resolves to during replay. |
| 35 | FIXTURE_PUBLIC_ADDRESS = "93.184.216.34" |
| 36 | |
| 37 | |
| 38 | class _FrozenDateTime(datetime): |
| 39 | @classmethod |
| 40 | def now(cls, tz=None): |
| 41 | fixed = cls(2026, 7, 10, 12, 0, 0, tzinfo=timezone.utc) |
| 42 | return fixed if tz is not None else fixed.replace(tzinfo=None) |
| 43 | |
| 44 | |
| 45 | @dataclass(frozen=True) |
| 46 | class EvalFixture: |
| 47 | name: str |
| 48 | path: Path |
| 49 | manifest: dict[str, Any] |
| 50 | input_urls: frozenset[str] |
| 51 | |
| 52 | |
| 53 | @dataclass |
| 54 | class EvalResult: |
| 55 | fixture: EvalFixture |
| 56 | report: schema.Report |
| 57 | scores: dict[str, float] |
| 58 | |
| 59 | |
| 60 | def _http_urls(value: Any) -> set[str]: |
| 61 | urls: set[str] = set() |
| 62 | if isinstance(value, dict): |
| 63 | for child in value.values(): |
| 64 | urls.update(_http_urls(child)) |
| 65 | elif isinstance(value, list): |
| 66 | for child in value: |
| 67 | urls.update(_http_urls(child)) |
| 68 | elif isinstance(value, str) and value.startswith(("https://", "http://")): |
| 69 | urls.add(value) |
| 70 | return urls |
| 71 | |
| 72 | |
| 73 | def _polymarket_event_urls(request: dict[str, Any], value: Any) -> set[str]: |
| 74 | """Polymarket event URLs a Gamma response grounds. Gamma returns each |
| 75 | event's slug, not its page URL; the parser builds the URL from the slug.""" |
| 76 | if not str(request.get("url") or "").startswith("https://gamma-api.polymarket.com/"): |
| 77 | return set() |
| 78 | events = value.get("events") if isinstance(value, dict) else value |
| 79 | return { |
| 80 | f"https://polymarket.com/event/{event['slug']}" |
| 81 | for event in events or [] |
| 82 | if isinstance(event, dict) and event.get("slug") |
| 83 | } |
| 84 | |
| 85 | |
| 86 | def load_fixtures(root: Path = FIXTURES_DIR) -> list[EvalFixture]: |
| 87 | fixtures: list[EvalFixture] = [] |
| 88 | for manifest_path in sorted(root.glob("*/manifest.json")): |
| 89 | manifest = json.loads(manifest_path.read_text(encoding="utf-8")) |
| 90 | http_payload = json.loads((manifest_path.parent / "http.json").read_text(encoding="utf-8")) |
| 91 | input_urls: set[str] = set() |
| 92 | for exchange in http_payload.get("exchanges") or []: |
| 93 | value = (exchange.get("response") or {}).get("value") |
| 94 | input_urls.update(_http_urls(value)) |
| 95 | input_urls.update(_polymarket_event_urls(exchange.get("request") or {}, value)) |
| 96 | for exchange in http_payload.get("source_exchanges") or []: |
| 97 | input_urls.update(_http_urls(exchange.get("value"))) |
| 98 | fixtures.append( |
| 99 | EvalFixture( |
| 100 | name=manifest.get("name") or manifest_path.parent.name, |
| 101 | path=manifest_path.parent, |
| 102 | manifest=manifest, |
| 103 | input_urls=frozenset(input_urls), |
| 104 | ) |
| 105 | ) |
| 106 | return fixtures |
| 107 | |
| 108 | |
| 109 | @contextlib.contextmanager |
| 110 | def _fixture_dns(public_hosts: list[str]): |
| 111 | """Resolve only the fixture's listed hosts, each to one public address. |
| 112 | |
| 113 | Lanes that fetch from a site named in remote content check that the name |
| 114 | resolves to public addresses before fetching. Replay never reaches the |
| 115 | network, so the fixture names which hosts are public; every other name |
| 116 | fails to resolve and the check still refuses it. |
| 117 | """ |
| 118 | if not public_hosts: |
| 119 | yield |
| 120 | return |
| 121 | known = {host.lower() for host in public_hosts} |
| 122 | |
| 123 | def getaddrinfo(name, *_args, **_kwargs): |
| 124 | if str(name).lower() not in known: |
| 125 | raise socket.gaierror(f"{name} is not a fixture host") |
| 126 | return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (FIXTURE_PUBLIC_ADDRESS, 0))] |
| 127 | |
| 128 | public_host.resolves_public.cache_clear() |
| 129 | try: |
| 130 | with mock.patch.object(public_host.socket, "getaddrinfo", getaddrinfo): |
| 131 | yield |
| 132 | finally: |
| 133 | public_host.resolves_public.cache_clear() |
| 134 | |
| 135 | |
| 136 | def _resolve_person( |
| 137 | fixture: EvalFixture, config: dict[str, Any], |
| 138 | ) -> tuple[str | None, str | None]: |
| 139 | """Run the CLI's person resolve step for a person-run fixture. |
| 140 | |
| 141 | The manifest's ``person`` object carries the person flags (``employer``, |
| 142 | ``linkedin``, ``email``). The resolved context joins ``config`` as the |
| 143 | CLI's does; the returned (x_handle, github_user) are the handles the step |
| 144 | derived from the person's own links. A fixture without ``person`` is not |
| 145 | a person run: nothing changes and both handles are None. |
| 146 | """ |
| 147 | flags = fixture.manifest.get("person") |
| 148 | if not flags: |
| 149 | return None, None |
| 150 | import last30days as cli |
| 151 | |
| 152 | args = argparse.Namespace( |
| 153 | employer=flags.get("employer"), |
| 154 | linkedin=flags.get("linkedin"), |
| 155 | email=flags.get("email"), |
| 156 | mock=False, |
| 157 | x_handle=None, |
| 158 | github_user=None, |
| 159 | no_x_handle=None, |
| 160 | ) |
| 161 | ctx = cli._person_resolve_step( |
| 162 | args, fixture.manifest["topic"], config, list(fixture.manifest["fixture_sources"]), |
| 163 | ) |
| 164 | if ctx is not None: |
| 165 | config["_person"] = ctx |
| 166 | return args.x_handle, args.github_user |
| 167 | |
| 168 | |
| 169 | def _run_once(fixture: EvalFixture) -> schema.Report: |
| 170 | manifest = fixture.manifest |
| 171 | config = dict(manifest.get("config") or {}) |
| 172 | network_error = AssertionError(f"Network attempted while replaying {fixture.name}") |
| 173 | # Each replay is one command: a fetch memoized by an earlier run in this |
| 174 | # process would leave its recorded exchanges unused. |
| 175 | fetch_memo.reset() |
| 176 | with mock.patch.object(pipeline, "datetime", _FrozenDateTime), \ |
| 177 | mock.patch.object(schema, "datetime", _FrozenDateTime), \ |
| 178 | mock.patch.object( |
| 179 | pipeline, |
| 180 | "available_sources", |
| 181 | return_value=list(manifest["fixture_sources"]), |
| 182 | ), \ |
| 183 | mock.patch.object(http.urllib.request, "urlopen", side_effect=network_error), \ |
| 184 | _fixture_dns(list(manifest.get("public_hosts") or [])), \ |
| 185 | http.replaying_requests(fixture.path): |
| 186 | x_handle, github_user = _resolve_person(fixture, config) |
| 187 | return pipeline.run( |
| 188 | topic=manifest["topic"], |
| 189 | config=config, |
| 190 | depth=manifest.get("depth", "quick"), |
| 191 | requested_sources=list(manifest["fixture_sources"]), |
| 192 | mock=False, |
| 193 | x_handle=x_handle, |
| 194 | github_user=github_user, |
| 195 | web_backend=manifest.get("web_backend", "none"), |
| 196 | external_plan=manifest["plan"], |
| 197 | lookback_days=int(manifest.get("lookback_days", 30)), |
| 198 | as_of_date=manifest["as_of_date"], |
| 199 | ) |
| 200 | |
| 201 | |
| 202 | def _citation_grounding(report: schema.Report, fixture: EvalFixture) -> float: |
| 203 | results = schema.to_agent_export(report)["results"] |
| 204 | if not results: |
| 205 | return 0.0 |
| 206 | grounded = sum(bool(result.get("url")) and result["url"] in fixture.input_urls for result in results) |
| 207 | return grounded / len(results) |
| 208 | |
| 209 | |
| 210 | def _recency_compliance(report: schema.Report) -> float: |
| 211 | ranked_items = [ |
| 212 | item |
| 213 | for candidate in report.ranked_candidates |
| 214 | for item in candidate.source_items |
| 215 | ] |
| 216 | if not ranked_items: |
| 217 | return 0.0 |
| 218 | compliant = sum( |
| 219 | not item.published_at |
| 220 | or report.range_from <= item.published_at[:10] <= report.range_to |
| 221 | for item in ranked_items |
| 222 | ) |
| 223 | return compliant / len(ranked_items) |
| 224 | |
| 225 | |
| 226 | def _cluster_coherence(report: schema.Report, fixture: EvalFixture) -> float: |
| 227 | candidates = {candidate.candidate_id: candidate for candidate in report.ranked_candidates} |
| 228 | pair_scores: list[float] = [] |
| 229 | for report_cluster in report.clusters: |
| 230 | members = [candidates[candidate_id] for candidate_id in report_cluster.candidate_ids if candidate_id in candidates] |
| 231 | for left, right in itertools.combinations(members, 2): |
| 232 | left_entities = entity_extract.extract_text_entities(f"{left.title} {left.snippet}") |
| 233 | right_entities = entity_extract.extract_text_entities(f"{right.title} {right.snippet}") |
| 234 | overlap = entity_extract.entity_overlap(left_entities, right_entities) |
| 235 | pair_scores.append(1.0 if overlap >= ENTITY_OVERLAP_FLOOR else 0.0) |
| 236 | if pair_scores: |
| 237 | return sum(pair_scores) / len(pair_scores) |
| 238 | # No multi-member clusters formed. For fixtures that historically cluster |
| 239 | # (expects_clusters: true in the manifest), that means cluster formation |
| 240 | # regressed and must fail rather than score a vacuous 1.0. Sparse topics |
| 241 | # that legitimately produce singletons declare expects_clusters: false. |
| 242 | return 0.0 if fixture.manifest.get("expects_clusters") else 1.0 |
| 243 | |
| 244 | |
| 245 | def _coverage(report: schema.Report, fixture: EvalFixture) -> float: |
| 246 | sources = list(fixture.manifest["fixture_sources"]) |
| 247 | if not sources: |
| 248 | return 0.0 |
| 249 | covered = sum( |
| 250 | bool(report.items_by_source.get(source)) or source in report.source_status |
| 251 | for source in sources |
| 252 | ) |
| 253 | return covered / len(sources) |
| 254 | |
| 255 | |
| 256 | def score_report( |
| 257 | report: schema.Report, |
| 258 | fixture: EvalFixture, |
| 259 | *, |
| 260 | deterministic: bool, |
| 261 | ) -> dict[str, float]: |
| 262 | return { |
| 263 | "citation_grounding": _citation_grounding(report, fixture), |
| 264 | "recency_compliance": _recency_compliance(report), |
| 265 | "cluster_coherence": _cluster_coherence(report, fixture), |
| 266 | "coverage": _coverage(report, fixture), |
| 267 | "determinism": 1.0 if deterministic else 0.0, |
| 268 | } |
| 269 | |
| 270 | |
| 271 | def evaluate_fixture(fixture: EvalFixture) -> EvalResult: |
| 272 | first = _run_once(fixture) |
| 273 | second = _run_once(fixture) |
| 274 | deterministic = schema.to_dict(first) == schema.to_dict(second) |
| 275 | return EvalResult( |
| 276 | fixture=fixture, |
| 277 | report=first, |
| 278 | scores=score_report(first, fixture, deterministic=deterministic), |
| 279 | ) |
| 280 | |
| 281 | |
| 282 | def evaluate_all(fixtures: list[EvalFixture] | None = None) -> list[EvalResult]: |
| 283 | selected = fixtures if fixtures is not None else load_fixtures() |
| 284 | if not selected: |
| 285 | raise AssertionError(f"No eval fixtures found under {FIXTURES_DIR}") |
| 286 | return [evaluate_fixture(fixture) for fixture in selected] |
| 287 | |
| 288 | |
| 289 | def aggregate_scores(results: list[EvalResult]) -> dict[str, float]: |
| 290 | return { |
| 291 | metric: sum(result.scores[metric] for result in results) / len(results) |
| 292 | for metric in METRIC_NAMES |
| 293 | } |
| 294 | |
| 295 | |
| 296 | def load_baseline(path: Path = BASELINE_PATH) -> dict[str, float]: |
| 297 | payload = json.loads(path.read_text(encoding="utf-8")) |
| 298 | return {metric: float(payload["metrics"][metric]) for metric in METRIC_NAMES} |
| 299 | |
| 300 | |
| 301 | def baseline_failures( |
| 302 | scores: dict[str, float], |
| 303 | baseline: dict[str, float] | None = None, |
| 304 | ) -> list[str]: |
| 305 | floors = baseline if baseline is not None else load_baseline() |
| 306 | return [ |
| 307 | f"{metric}: {scores[metric]:.3f} < {floors[metric]:.3f}" |
| 308 | for metric in METRIC_NAMES |
| 309 | if scores[metric] + 1e-12 < floors[metric] |
| 310 | ] |
| 311 | |
| 312 | |
| 313 | def per_fixture_failures(results: list["EvalResult"]) -> list[str]: |
| 314 | """Enforce per-fixture floors so one broken archetype cannot hide in the |
| 315 | cross-fixture average (a total clustering failure on breaking-event scores |
| 316 | 0.0 but averages to 0.857 across seven fixtures).""" |
| 317 | raw = json.loads(BASELINE_PATH.read_text()) |
| 318 | floors = raw.get("per_fixture_floors") or {} |
| 319 | failures: list[str] = [] |
| 320 | for result in results: |
| 321 | for metric, floor in floors.items(): |
| 322 | value = result.scores.get(metric) |
| 323 | if value is not None and value + 1e-12 < float(floor): |
| 324 | failures.append( |
| 325 | f"{result.fixture.name}/{metric}: {value:.3f} < {float(floor):.3f}" |
| 326 | ) |
| 327 | return failures |
| 328 | |
| 329 | |
| 330 | def format_score_table(results: list[EvalResult]) -> str: |
| 331 | aggregate = aggregate_scores(results) |
| 332 | headers = ["fixture", *METRIC_NAMES] |
| 333 | rows = [ |
| 334 | [result.fixture.name, *(f"{result.scores[name]:.3f}" for name in METRIC_NAMES)] |
| 335 | for result in results |
| 336 | ] |
| 337 | rows.append(["AVERAGE", *(f"{aggregate[name]:.3f}" for name in METRIC_NAMES)]) |
| 338 | widths = [max(len(str(row[index])) for row in [headers, *rows]) for index in range(len(headers))] |
| 339 | rendered = [" | ".join(str(value).ljust(widths[index]) for index, value in enumerate(headers))] |
| 340 | rendered.append("-+-".join("-" * width for width in widths)) |
| 341 | rendered.extend( |
| 342 | " | ".join(str(value).ljust(widths[index]) for index, value in enumerate(row)) |
| 343 | for row in rows |
| 344 | ) |
| 345 | return "\n".join(rendered) |
| 346 | |
| 347 | |
| 348 | def main() -> int: |
| 349 | results = evaluate_all() |
| 350 | print(format_score_table(results)) |
| 351 | failures = baseline_failures(aggregate_scores(results)) |
| 352 | if failures: |
| 353 | print("\nBaseline failures:", file=sys.stderr) |
| 354 | for failure in failures: |
| 355 | print(f"- {failure}", file=sys.stderr) |
| 356 | return 1 |
| 357 | return 0 |
| 358 | |
| 359 | |
| 360 | if __name__ == "__main__": |
| 361 | raise SystemExit(main()) |
| 362 |