AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(eval): research-quality regression harness with scored fixtures in CI (#799)
Matt Van Horn0270c1235240
diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.ymlindex 4171d66a..f230b6fa 100644--- a/.github/workflows/validate.yml+++ b/.github/workflows/validate.yml@@ -28,6 +28,25 @@ jobs:- name: Run test suiterun: uv run pytest --cov --cov-report=term-missing+ eval:+ runs-on: ubuntu-latest+ permissions:+ contents: read+ steps:+ - name: Checkout+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0+ with:+ persist-credentials: false++ - name: Install uv+ uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0++ - name: Set up Python+ run: uv python install 3.12++ - name: Score research quality+ run: uv run pytest tests/eval -x -s+mcp-tests:runs-on: ubuntu-latestpermissions:diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex c7683908..a7604cb0 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -50,6 +50,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--publish-password <password>` - optional shared password for `--publish-html`. Prefer `LAST30DAYS_PUBLISH_PASSWORD=<password>` instead so the password is not visible in the process list or shell history. Use a unique non-personal password; never reuse the user's own password. The provider's update key is treated as secret and is not written to stdout, HTML, raw output, or `.publish.json` metadata.- `--preflight` - print a human-readable permission preflight. It reports config source, project config trust/ignore state, browser-cookie plan, planned writes, optional commands, source availability, and endpoint overrides without reading browser cookies, writing setup/config/report files, or running research. Add `--emit=json` for the separate machine-readable preflight contract (`--json-profile` does not change it); use `--diagnose` when you need the full source diagnostic JSON.- `--welcome` - print the first-run welcome text (engine-owned; the skill relays it verbatim on first run). Safe: prints and exits, no reads or writes.+- `--record-fixtures <dir>` - developer-only, hidden flag that records scrubbed source responses for the offline research-quality eval harness. It writes `<dir>/http.json`; see the [eval reference](docs/reference/eval.md) before recording or committing fixtures.- `setup --github-start` / `setup --github-poll` - the two-command ScrapeCreators GitHub device-auth split. `--github-start` submits the device flow, copies the code to the clipboard, opens the browser, and returns the code immediately (foreground); `--github-poll` waits for you to authorize and persists the key. `setup --github` still runs both in one shot for back-compat.The footer line `📎 Raw results saved to ${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}/<slug>-raw.md` is the canonical pointer; if it shows backslashes on Windows update past v3.1.1.diff --git a/docs/reference/eval.md b/docs/reference/eval.mdnew file mode 100644index 00000000..3b7c0b06--- /dev/null+++ b/docs/reference/eval.md@@ -0,0 +1,87 @@+# Research-quality eval harness++The eval suite measures the quality properties that ordinary unit tests do not: whether ranked evidence is grounded in retrieved inputs, stays inside the requested window, forms coherent clusters, accounts for every usable fixture source, and remains deterministic.++It runs the production pipeline offline. Recorded HTTP exchanges replay at `lib/http.py`; CLI-backed adapters such as yt-dlp, Digg, arXiv, Techmeme, and Trustpilot replay their parsed result at the source-module seam. Planning is supplied by each fixture manifest, and normalization, date filtering, scoring, fusion, clustering, source outcomes, and the versioned agent JSON export all run normally. The harness never calls an LLM or the network.++## Run it++From the repository root:++```bash+uv run pytest tests/eval -x -s+```++The `-s` keeps the score table visible. To print only the scored run and return a nonzero exit when a floor is missed:++```bash+uv run python tests/eval/harness.py+```++CI runs the pytest command in the `eval` job of `.github/workflows/validate.yml`, so every pull request gets a score table and a hard baseline check.++## Metrics++| Metric | Deterministic definition |+|---|---|+| Citation grounding | Fraction of exported result URLs that occur in the recorded fixture inputs. |+| Recency compliance | Fraction of ranked source items whose known publication date is inside the report's inclusive date window. Undated evidence is not falsely classified as stale. |+| Cluster coherence | Fraction of within-cluster candidate pairs meeting the production entity-overlap threshold (`0.45`). Singleton clusters are coherent by definition. |+| Coverage | Fraction of fixture sources represented by usable report items or an explicit `Report.source_status` outcome. |+| Determinism | `schema.to_dict()` equality for two runs with fixed time and identical recorded inputs. |++Aggregate floors live in `tests/eval/baseline.json`. The fixture matrix covers a tech product, a person, a comparison, breaking events, a niche technical topic, and a non-English CJK topic.++## Add or refresh a fixture++Fixture directories contain:++- `manifest.json`: topic archetype, fixed `as_of_date`, sources, safe dummy config, and a deterministic external query plan.+- `http.json`: scrubbed HTTP exchanges and any CLI-backed source exchanges.++Use the direct engine invocation below only for development/fixture capture; `/last30days <topic>` remains the product interface:++```bash+python3 skills/last30days/scripts/last30days.py \+ "<topic>" \+ --quick \+ --as-of 2026-07-10 \+ --search grounding,hackernews \+ --plan /tmp/eval-plan.json \+ --record-fixtures tests/eval/fixtures/<fixture-name>+```++`--record-fixtures` is intentionally hidden from `--help`. It records the live run's shared HTTP traffic and the bounded CLI-adapter seams, scrubs credential-shaped query/body/response fields, and writes `http.json`. It does not create the manifest because archetype, fixed date, source contract, and query plan are review decisions.++Before committing a recording:++1. Inspect `http.json` for cookies, keys, tokens, personal identifiers, and unnecessary long bodies.+2. Truncate content to the smallest structure that exercises the adapter and pipeline.+3. Replace irrelevant real usernames with obvious fixture identities.+4. Add the manifest and run both commands above with networking unavailable.++The replay is fail-closed: an unrecorded request or an unused recorded exchange fails the run.++## Fixture flags++- `expects_clusters` (bool): fixtures whose topic historically forms multi-member clusters set this true; if cluster formation regresses to singletons on such a fixture, coherence scores 0.0 instead of a vacuous 1.0. Sparse topics (niche, non-english-cjk, tech-product) set it false because singletons are their legitimate shape.+- Post-ranking enrichment (YouTube transcripts, Digg posts) is recorded and replayed by merging recorded `metadata` onto freshly computed items by item_id, so normalization/scoring/dedupe regressions stay visible to the eval rather than being overwritten by fixture state.+- Post-rerank GitHub star enrichment records its repo->stars map and replays via `github.apply_star_map`, keeping runs offline even when `GITHUB_TOKEN` is set in CI. GitHub project-mode (`--github-repo`) and person-mode (`--github-user`) runs are not yet fixture-recordable; the network guard fails loudly if a fixture attempts them.++## Known seams++- Module-backed sources (yt-dlp, digg-pp-cli and other CLI adapters) record post-parse items at the module boundary, so replay does not re-exercise their parsing/normalization code the way HTTP-backed sources do (those replay raw responses through the real pipeline). A normalization regression in a module adapter is covered by that adapter's unit tests, not the eval. Recording raw CLI stdout is a possible future upgrade.+- Cluster coherence shares `entity_extract` with production clustering. The pinned-predicate test (`test_entity_overlap_predicate_pinned`) guards against the shared predicate drifting permissive, and per-fixture floors in baseline.json catch a single archetype collapsing even when the cross-fixture average stays green.++## Move a baseline++Baseline edits are explicit quality-policy changes, not snapshot refreshes. Move a floor only when an intentional product change makes the old threshold invalid or when a new fixture legitimately changes the measured distribution.++Include in the review:++1. The old and new score tables.+2. The reason the metric changed.+3. A focused test proving the intended behavior.+4. An explanation for any lower floor; never lower a floor solely to make CI green.++`test_intentional_out_of_window_regression_fails_recency_floor` is the standing negative control: it injects stale ranked evidence and proves the baseline check detects the regression.diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex d1498038..456703d2 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -396,6 +396,8 @@ The engine reads `LAST30DAYS_MEMORY_DIR` from either the process env or `~/.confWhen both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine runs the research through that configured remote API instead of local sources (unless `--mock` is passed); `LAST30DAYS_API_BASE` is the endpoint and has no built-in default, so leaving either variable unset runs local sources normally. The invocation is unchanged: same flags, `--quick`/`--deep` map to search depth, progress lines still stream on stderr (`[narrate] step=...` plus a compact elapsed/eta line), and the report prints on stdout and saves to the memory dir as usual, so Steps 1-4 proceed normally on the output. The exception is research JSON: the remote endpoint does not return the local `Report` needed for the versioned agent profile, so use `--emit=json --json-profile=raw` for its existing server-response JSON contract. No per-source keys or setup-wizard credentials are needed for the search itself in this mode. Two engine exits need specific handling: exit code 3 means the API asked a clarifying question first - the engine prints the question and options on stderr; present them to the user and re-run with the chosen angle folded into the topic. An insufficient-credits failure (HTTP 402) prints the account's balance, the amount needed, and a billing link - relay those lines to the user verbatim; do not fall back to WebSearch-only synthesis.+**Developer-only eval capture:** `--record-fixtures <dir>` is a hidden direct-engine flag for maintaining the deterministic research-quality suite. It records scrubbed HTTP and CLI-adapter responses to `<dir>/http.json`; it is never part of the user-facing slash-command invocation. Follow `docs/reference/eval.md` for fixture review, replay, and baseline rules.+## Step 0: First-Run Setup Wizard**CRITICAL: ALWAYS execute Step 0 BEFORE Step 1, even when the user provided a topic.** If the user typed `/last30days Mercer Island`, you MUST run the wizard BEFORE any research. The topic is preserved - research runs immediately after the wizard completes. Do NOT skip the wizard because a topic was provided. It takes about 30 seconds and only runs once, ever.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 0303dbc0..2b0da15e 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -47,7 +47,7 @@ if os.name == "nt":SCRIPT_DIR = Path(__file__).parent.resolve()sys.path.insert(0, str(SCRIPT_DIR))-from lib import dates, env, html_render, permission_preflight, pipeline, render, schema, ui+from lib import dates, env, html_render, http, permission_preflight, pipeline, render, schema, ui_child_pids: set[int] = set()_child_pids_lock = threading.Lock()@@ -373,6 +373,11 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--deep", action="store_true", help="Higher-recall retrieval profile")parser.add_argument("--debug", action="store_true", help="Enable HTTP debug logging")parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures")+ parser.add_argument(+ "--record-fixtures",+ metavar="DIR",+ help=argparse.SUPPRESS,+ )parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability")parser.add_argument("--preflight", action="store_true",help="Print a safe human-readable permission preflight")@@ -1044,6 +1049,17 @@ def main() -> int:# Use parse_known_args so setup sub-flags (--device-auth, --github,# --openclaw) pass through without argparse hard-exiting.args, extra_argv = parser.parse_known_args()+ if args.record_fixtures:+ with http.recording_requests(Path(args.record_fixtures)):+ return _main(parser, args, extra_argv)+ return _main(parser, args, extra_argv)+++def _main(+ parser: argparse.ArgumentParser,+ args: argparse.Namespace,+ extra_argv: list[str],+) -> int:if args.debug:os.environ["LAST30DAYS_DEBUG"] = "1"@@ -1173,6 +1189,7 @@ def main() -> int:topicand not args.diagnoseand not args.mock+ and not args.record_fixturesand env.read_secret_env("LAST30DAYS_API_KEY")and os.environ.get("LAST30DAYS_API_BASE")):diff --git a/skills/last30days/scripts/lib/cluster.py b/skills/last30days/scripts/lib/cluster.pyindex bd9e501a..3360a034 100644--- a/skills/last30days/scripts/lib/cluster.py+++ b/skills/last30days/scripts/lib/cluster.py@@ -2,59 +2,13 @@from __future__ import annotations-import re--from . import dedupe, schema+from . import dedupe, entity_extract, schemaCLUSTERABLE_INTENTS = {"breaking_news", "opinion", "comparison", "prediction"}-# Words too common to signal shared topic between clusters.-_ENTITY_STOPWORDS = frozenset({- "the", "a", "an", "to", "for", "how", "is", "in", "of", "on", "and",- "with", "from", "by", "at", "this", "that", "it", "what", "are", "do",- "can", "his", "her", "he", "she", "its", "was", "has", "new", "just",- "says", "said", "will", "about", "after", "now", "all", "been", "here",- "not", "out", "up", "more", "also", "but", "who", "year", "first",- "make", "being", "making", "over", "into", "than", "they", "their",- "would", "could", "get", "got", "some", "like", "back", "going",- "breaking", "https", "http", "www", "com",-})--def _candidate_text(candidate: schema.Candidate) -> str:return " ".join(part for part in [candidate.title, candidate.snippet] if part).strip()--def _extract_entities(text: str) -> set[str]:- """Extract significant words (proper nouns, numbers, capitalized words) from text.-- Used for cross-source cluster merging where phrasing differs but entities overlap.- """- # Normalize but preserve word boundaries- words = re.sub(r"[^\w\s]", " ", text).split()- entities = set()- for word in words:- lower = word.lower()- if lower in _ENTITY_STOPWORDS or len(word) <= 2:- continue- # Keep words that are: capitalized, ALL CAPS, contain digits, or 4+ chars- if word[0].isupper() or word.isupper() or any(c.isdigit() for c in word) or len(word) >= 4:- entities.add(lower)- return entities---def _entity_overlap(entities_a: set[str], entities_b: set[str]) -> float:- """Jaccard-style overlap on extracted entities."""- if not entities_a or not entities_b:- return 0.0- intersection = entities_a & entities_b- smaller = min(len(entities_a), len(entities_b))- # Use overlap coefficient (intersection / min) instead of Jaccard,- # because a short tweet about the same event as a long Reddit post- # will have fewer total entities but high overlap with the larger set.- return len(intersection) / smaller if smaller > 0 else 0.0--def _mmr_representatives(candidates: list[schema.Candidate],text_cache: dict[str, dedupe._PreparedText],@@ -182,7 +136,7 @@ def _merge_entity_clusters(for cid in cl.candidate_ids:cand = candidate_map.get(cid)if cand:- entities |= _extract_entities(_candidate_text(cand))+ entities |= entity_extract.extract_text_entities(_candidate_text(cand))cluster_entities.append(entities)# Only merge clusters with <= 3 items (don't merge already-large clusters)@@ -207,7 +161,7 @@ def _merge_entity_clusters(if poly_i != poly_j:continue- overlap = _entity_overlap(cluster_entities[i], cluster_entities[j])+ overlap = entity_extract.entity_overlap(cluster_entities[i], cluster_entities[j])if overlap >= 0.45:merged_into[j] = idiff --git a/skills/last30days/scripts/lib/entity_extract.py b/skills/last30days/scripts/lib/entity_extract.pyindex 43dd3632..b011a1ee 100644--- a/skills/last30days/scripts/lib/entity_extract.py+++ b/skills/last30days/scripts/lib/entity_extract.py@@ -13,6 +13,37 @@ GENERIC_HANDLES = {"verified", "jack", "sundarpichai",}+ENTITY_STOPWORDS = frozenset({+ "the", "a", "an", "to", "for", "how", "is", "in", "of", "on", "and",+ "with", "from", "by", "at", "this", "that", "it", "what", "are", "do",+ "can", "his", "her", "he", "she", "its", "was", "has", "new", "just",+ "says", "said", "will", "about", "after", "now", "all", "been", "here",+ "not", "out", "up", "more", "also", "but", "who", "year", "first",+ "make", "being", "making", "over", "into", "than", "they", "their",+ "would", "could", "get", "got", "some", "like", "back", "going",+ "breaking", "https", "http", "www", "com",+})+++def extract_text_entities(text: str) -> set[str]:+ """Extract significant words used by clustering and eval scoring."""+ words = re.sub(r"[^\w\s]", " ", text).split()+ entities = set()+ for word in words:+ lower = word.lower()+ if lower in ENTITY_STOPWORDS or len(word) <= 2:+ continue+ if word[0].isupper() or word.isupper() or any(char.isdigit() for char in word) or len(word) >= 4:+ entities.add(lower)+ return entities+++def entity_overlap(entities_a: set[str], entities_b: set[str]) -> float:+ """Return overlap coefficient for two extracted entity sets."""+ if not entities_a or not entities_b:+ return 0.0+ return len(entities_a & entities_b) / min(len(entities_a), len(entities_b))+def extract_entities(reddit_items: List[Dict[str, Any]],diff --git a/skills/last30days/scripts/lib/github.py b/skills/last30days/scripts/lib/github.pyindex 8ec91b0b..d428b9ee 100644--- a/skills/last30days/scripts/lib/github.py+++ b/skills/last30days/scripts/lib/github.py@@ -951,6 +951,7 @@ def enrich_candidates_with_stars(token: Optional[str] = None,already_enriched: Optional[set] = None,max_repos: int = 10,+ collect_map: Optional[Dict[str, int]] = None,) -> int:"""Annotate candidates with live GitHub star counts.@@ -984,9 +985,22 @@ def enrich_candidates_with_stars(except Exception:pass+ if collect_map is not None:+ collect_map.update(star_map)if not star_map:return 0+ return apply_star_map(candidates, star_map)+++def apply_star_map(candidates: List[Any], star_map: Dict[str, int]) -> int:+ """Annotate candidates from a repo->stars map (fetch/apply split).++ Split out so offline replay (the eval harness) can apply a recorded map+ without any network or gh-credential access.+ """+ if not star_map:+ return 0# Annotate candidatesenriched_count = 0for c in candidates:diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.pyindex 9cb4e3f9..b525c25b 100644--- a/skills/last30days/scripts/lib/http.py+++ b/skills/last30days/scripts/lib/http.py@@ -1,6 +1,7 @@"""HTTP utilities for last30days skill (stdlib only)."""import json+import osimport reimport socketimport sys@@ -10,8 +11,9 @@ import urllib.errorimport urllib.requestfrom contextlib import contextmanagerfrom contextvars import ContextVar, copy_context+from pathlib import Pathfrom typing import Any, Dict, Optional, Union-from urllib.parse import urlencode+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom . import healthfrom . import log as _log@@ -43,6 +45,353 @@ _expected_miss_statuses: ContextVar[frozenset[int]] = ContextVar(default=frozenset(),)+_FIXTURE_FORMAT = "last30days-http-fixture/v1"+_FIXTURE_SECRET_KEYS = frozenset(+ {"api_key", "apikey", "authorization", "cookie", "key", "secret", "token"}+)+_fixture_lock = threading.Lock()+_fixture_state: Optional[dict[str, Any]] = None+_NO_FIXTURE = object()+_fixture_module_capture: ContextVar[bool] = ContextVar(+ "last30days_fixture_module_capture",+ default=False,+)+++def _is_secret_key(value: object) -> bool:+ key = re.sub(r"[^a-z0-9]+", "_", str(value).lower()).strip("_")+ return (+ key in _FIXTURE_SECRET_KEYS+ or key.endswith(("_api_key", "_authorization", "_cookie", "_secret", "_token"))+ )+++def _scrub_fixture_value(+ value: Any,+ *,+ key: str = "",+ redactions: frozenset[str] = frozenset(),+) -> Any:+ """Remove credentials before a recorded exchange reaches disk."""+ if key and _is_secret_key(key):+ return "<redacted>"+ if isinstance(value, dict):+ return {+ str(child_key): _scrub_fixture_value(+ child_value,+ key=str(child_key),+ redactions=redactions,+ )+ for child_key, child_value in value.items()+ }+ if isinstance(value, list):+ return [_scrub_fixture_value(item, redactions=redactions) for item in value]+ if isinstance(value, str):+ scrubbed = value+ for secret in sorted(redactions, key=len, reverse=True):+ if len(secret) >= 4:+ scrubbed = scrubbed.replace(secret, "<redacted>")+ return scrubbed+ return value+++def _collect_secret_values(value: Any, *, key: str = "") -> set[str]:+ values: set[str] = set()+ if key and _is_secret_key(key) and value not in (None, ""):+ values.add(str(value))+ return values+ if isinstance(value, dict):+ for child_key, child_value in value.items():+ values.update(_collect_secret_values(child_value, key=str(child_key)))+ elif isinstance(value, list):+ for child in value:+ values.update(_collect_secret_values(child))+ return values+++def _fixture_redactions(+ url: str,+ headers: dict[str, str],+ json_data: Optional[Dict[str, Any]],+) -> frozenset[str]:+ values: set[str] = set()+ try:+ for key, value in parse_qsl(urlsplit(url).query, keep_blank_values=True):+ if _is_secret_key(key) and value:+ values.add(value)+ except ValueError:+ pass+ values.update(_collect_secret_values(headers))+ values.update(_collect_secret_values(json_data))+ return frozenset(values)+++def _scrub_fixture_url(url: str) -> str:+ try:+ parts = urlsplit(url)+ query = urlencode(+ [+ (key, "<redacted>" if _is_secret_key(key) else value)+ for key, value in parse_qsl(parts.query, keep_blank_values=True)+ ]+ )+ return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment))+ except ValueError:+ return url+++def _fixture_request(+ method: str,+ url: str,+ json_data: Optional[Dict[str, Any]],+ raw: bool,+) -> dict[str, Any]:+ request_data: dict[str, Any] = {+ "method": method.upper(),+ "url": _scrub_fixture_url(url),+ "raw": bool(raw),+ }+ if json_data is not None:+ request_data["json"] = _scrub_fixture_value(json_data)+ return request_data+++def _fixture_key(request_data: dict[str, Any]) -> str:+ return json.dumps(request_data, sort_keys=True, separators=(",", ":"), ensure_ascii=False)+++@contextmanager+def recording_requests(path: str | Path):+ """Record scrubbed HTTP exchanges to ``path`` for offline eval replay.++ This process-global session is deliberate: source requests run in worker+ threads, so a ContextVar would not observe the complete pipeline fan-out.+ Nested or concurrent recording/replay sessions are rejected.+ """+ global _fixture_state+ target = Path(path).expanduser()+ if target.suffix.lower() != ".json":+ target = target / "http.json"+ with _fixture_lock:+ if _fixture_state is not None:+ raise RuntimeError("An HTTP fixture session is already active")+ _fixture_state = {+ "mode": "record",+ "path": target,+ "exchanges": [],+ "source_exchanges": [],+ # Secret VALUES from the environment, so module-seam recordings+ # scrub tokens echoed inside normal string fields (adapter error+ # messages, parsed item text), not just secret-named keys.+ "redactions": frozenset(+ value+ for key, value in os.environ.items()+ if _is_secret_key(key) and isinstance(value, str) and len(value) >= 4+ ),+ }+ completed = False+ try:+ yield target+ completed = True+ finally:+ with _fixture_lock:+ state = _fixture_state+ _fixture_state = None+ if state is not None and completed:+ target.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "format": _FIXTURE_FORMAT,+ "exchanges": state["exchanges"],+ "source_exchanges": state["source_exchanges"],+ }+ temporary = target.with_name(f".{target.name}.tmp")+ temporary.write_text(+ json.dumps(payload, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ if os.name != "nt":+ temporary.chmod(0o644)+ temporary.replace(target)+++@contextmanager+def fixture_module_capture(enabled: bool):+ """Suppress nested HTTP recording when a whole adapter result is captured."""+ token = _fixture_module_capture.set(enabled)+ try:+ yield+ finally:+ _fixture_module_capture.reset(token)+++@contextmanager+def replaying_requests(path: str | Path):+ """Replay recorded exchanges and fail closed on any unrecorded request."""+ global _fixture_state+ target = Path(path).expanduser()+ if target.is_dir():+ target = target / "http.json"+ payload = json.loads(target.read_text(encoding="utf-8"))+ if payload.get("format") != _FIXTURE_FORMAT:+ raise ValueError(f"Unsupported HTTP fixture format in {target}")+ queues: dict[str, list[dict[str, Any]]] = {}+ for exchange in payload.get("exchanges") or []:+ queues.setdefault(_fixture_key(exchange["request"]), []).append(exchange["response"])+ source_queues: dict[str, list[Any]] = {}+ for exchange in payload.get("source_exchanges") or []:+ source_queues.setdefault(_fixture_key(exchange["request"]), []).append(exchange)+ with _fixture_lock:+ if _fixture_state is not None:+ raise RuntimeError("An HTTP fixture session is already active")+ _fixture_state = {+ "mode": "replay",+ "path": target,+ "queues": queues,+ "source_queues": source_queues,+ }+ try:+ yield target+ with _fixture_lock:+ unused = sum(len(values) for values in queues.values()) + sum(+ len(values) for values in source_queues.values()+ )+ if unused:+ raise AssertionError(f"HTTP fixture replay left {unused} unused exchange(s): {target}")+ finally:+ with _fixture_lock:+ _fixture_state = None+++def _fixture_replay(request_data: dict[str, Any]) -> Any:+ with _fixture_lock:+ state = _fixture_state+ if state is None or state["mode"] != "replay":+ return _NO_FIXTURE+ queue = state["queues"].get(_fixture_key(request_data))+ if not queue:+ raise AssertionError(+ "Unrecorded HTTP request during fixture replay: "+ f"{request_data['method']} {request_data['url']}"+ )+ response = queue.pop(0)+ if response.get("error"):+ error = response["error"]+ recorded_error = HTTPError(+ str(error.get("message") or "Recorded HTTP error"),+ status_code=error.get("status_code"),+ body=error.get("body"),+ outcome_state=error.get("outcome_state"),+ )+ _raise(recorded_error)+ return response.get("value")+++def _fixture_record(+ request_data: dict[str, Any],+ *,+ value: Any = None,+ error: Optional["HTTPError"] = None,+ redactions: frozenset[str] = frozenset(),+) -> None:+ if _fixture_module_capture.get():+ return+ with _fixture_lock:+ state = _fixture_state+ if state is None or state["mode"] != "record":+ return+ response: dict[str, Any]+ if error is None:+ response = {"value": _scrub_fixture_value(value, redactions=redactions)}+ else:+ response = {+ "error": _scrub_fixture_value(+ {+ "message": str(error),+ "status_code": error.status_code,+ "body": error.body,+ "outcome_state": error.outcome_state,+ },+ redactions=redactions,+ )+ }+ state["exchanges"].append({"request": request_data, "response": response})+++def fixture_source_replay(request_data: dict[str, Any]) -> tuple[bool, Any]:+ """Return a recorded CLI-backed source result when replay is active."""+ scrubbed = _scrub_fixture_value(request_data)+ with _fixture_lock:+ state = _fixture_state+ if state is None or state["mode"] != "replay":+ return False, None+ queue = state["source_queues"].get(_fixture_key(scrubbed))+ if not queue:+ raise AssertionError(+ "Unrecorded CLI-backed source request during fixture replay: "+ f"{request_data.get('source', 'unknown')}"+ )+ exchange = queue.pop(0)+ if exchange.get("type") == "error":+ error = exchange.get("error") or {}+ raise RecordedSourceError(+ str(error.get("message") or "Recorded source error"),+ exception_type=str(error.get("exception_type") or "Exception"),+ outcome_state=error.get("outcome_state"),+ )+ return True, exchange.get("value")+++def fixture_source_record(request_data: dict[str, Any], value: Any) -> None:+ """Record the parsed output of a source adapter that bypasses http.py."""+ with _fixture_lock:+ state = _fixture_state+ if state is None or state["mode"] != "record":+ return+ session_redactions = state.get("redactions") or frozenset()+ state["source_exchanges"].append(+ {+ "request": _scrub_fixture_value(request_data, redactions=session_redactions),+ "value": _scrub_fixture_value(value, redactions=session_redactions),+ }+ )+++def fixture_source_record_error(request_data: dict[str, Any], error: Exception) -> None:+ """Record a replayable failure from a source adapter that bypasses http.py."""+ with _fixture_lock:+ state = _fixture_state+ if state is None or state["mode"] != "record":+ return+ session_redactions = state.get("redactions") or frozenset()+ state["source_exchanges"].append(+ {+ "request": _scrub_fixture_value(request_data, redactions=session_redactions),+ "type": "error",+ "error": _scrub_fixture_value(+ {+ "exception_type": type(error).__name__,+ "message": str(error),+ "outcome_state": getattr(error, "outcome_state", None),+ }+ , redactions=session_redactions),+ }+ )+++class RecordedSourceError(RuntimeError):+ """Failure restored from a recorded module-backed source exchange."""++ def __init__(+ self,+ message: str,+ *,+ exception_type: str,+ outcome_state: Optional[str] = None,+ ):+ super().__init__(message)+ self.exception_type = exception_type+ self.outcome_state = outcome_state+def _is_dns_failure(err: urllib.error.URLError) -> bool:"""Return True if a URLError was caused by DNS resolution (gaierror)."""@@ -208,6 +557,12 @@ def request(separator = "&" if ("?" in url) else "?"url = f"{url}{separator}{urlencode(filtered)}"+ fixture_request = _fixture_request(method, url, json_data, raw)+ fixture_redactions = _fixture_redactions(url, headers, json_data)+ replayed = _fixture_replay(fixture_request)+ if replayed is not _NO_FIXTURE:+ return replayed+data = Noneif json_data is not None:data = json.dumps(json_data).encode('utf-8')@@ -226,14 +581,22 @@ def request(effective_retries = retriesdns_attempts = 0attempt = 0++ def raise_recorded(error: HTTPError) -> None:+ _fixture_record(fixture_request, error=error, redactions=fixture_redactions)+ _raise(error)+while attempt < effective_retries:try:with urllib.request.urlopen(req, timeout=timeout) as response:body = response.read().decode('utf-8')log(f"Response: {response.status} ({len(body)} bytes)")if raw:+ _fixture_record(fixture_request, value=body, redactions=fixture_redactions)return body- return json.loads(body) if body else {}+ parsed = json.loads(body) if body else {}+ _fixture_record(fixture_request, value=parsed, redactions=fixture_redactions)+ return parsedexcept urllib.error.HTTPError as e:body = Nonetry:@@ -248,13 +611,13 @@ def request(# Don't retry client errors (4xx) except rate limitsif 400 <= e.code < 500 and e.code != 429:- _raise(last_error)+ raise_recorded(last_error)# Cap 429 retries separately to avoid wasting latencyif e.code == 429:rate_limit_count += 1if rate_limit_count >= max_429_retries:- _raise(last_error)+ raise_recorded(last_error)# HTTP errors respect the caller's original `retries`; only DNS# failures get the widened `effective_retries` budget.@@ -324,7 +687,7 @@ def request(f"Invalid JSON response: {e}",outcome_state=health.SCHEMA_DRIFT,)- _raise(last_error)+ raise_recorded(last_error)except (OSError, TimeoutError, ConnectionResetError) as e:# Handle socket-level errors (connection reset, timeout, etc.)log(f"Connection error: {type(e).__name__}: {e}")@@ -343,9 +706,9 @@ def request(attempt += 1if last_error:- _raise(last_error)+ raise_recorded(last_error)error = HTTPError("Request failed with no error details")- _raise(error)+ raise_recorded(error)def get(url: str, headers: Optional[Dict[str, str]] = None, **kwargs) -> Dict[str, Any]:diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 557d20b1..dab67552 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -742,13 +742,30 @@ def run(model=None if mock else runtime.rerank_model,)- # Phase 3: post-rerank GitHub star enrichment+ # Phase 3: post-rerank GitHub star enrichment. Record/replay-aware so the+ # eval harness stays fully offline: this path calls the GitHub API (and the+ # gh-credential fallback) outside the _retrieve_stream seam, so it gets its+ # own fixture exchange keyed by phase.if "github" in available and not mock:- github.enrich_candidates_with_stars(- ranked_candidates,- token=config.get("GITHUB_TOKEN"),- already_enriched=_github_enriched_repos,- )+ star_request = {+ "source": "github",+ "phase": "post_rerank_star_enrichment",+ "topic": topic,+ "depth": depth,+ }+ star_matched, star_replayed = http.fixture_source_replay(star_request)+ if star_matched:+ star_map = star_replayed if isinstance(star_replayed, dict) else {}+ github.apply_star_map(ranked_candidates, star_map)+ else:+ collected_star_map: dict[str, int] = {}+ github.enrich_candidates_with_stars(+ ranked_candidates,+ token=config.get("GITHUB_TOKEN"),+ already_enriched=_github_enriched_repos,+ collect_map=collected_star_map,+ )+ http.fixture_source_record(star_request, collected_star_map)clusters = cluster_candidates(ranked_candidates, plan)warnings = _warnings(items_by_source, ranked_candidates, bundle.errors_by_source, degraded_by_source)@@ -814,6 +831,12 @@ def _finalize_items_by_source(for source, items in items_by_source_raw.items():items = sorted(items, key=lambda item: item.local_rank_score or 0.0, reverse=True)items = dedupe.dedupe_items(items)+ enrichment_request = {+ "source": source,+ "phase": "post_ranking_enrichment",+ "topic": topic,+ "depth": depth,+ }if source == "youtube" and items and not mock:# Same budget-at-the-survivors principle as the digg branch# below: retrieval-time transcripts go to each search's@@ -821,13 +844,18 @@ def _finalize_items_by_source(# relevance. Backfill survivors that arrived without one so the# transcript budget lands on videos the brief actually shows# (#542).- sc_token = (- config.get("SCRAPECREATORS_API_KEY")- if config and env.is_youtube_sc_available(config) else None- )- youtube_yt.backfill_transcripts(- items, topic=topic, depth=depth, token=sc_token,- )+ matched, replayed = http.fixture_source_replay(enrichment_request)+ if matched:+ items = _merge_replayed_enrichment(items, replayed)+ else:+ sc_token = (+ config.get("SCRAPECREATORS_API_KEY")+ if config and env.is_youtube_sc_available(config) else None+ )+ youtube_yt.backfill_transcripts(+ items, topic=topic, depth=depth, token=sc_token,+ )+ http.fixture_source_record(enrichment_request, schema.to_dict(items))# Post-merge topic-relevance filter for Polymarket: comparison queries# fan out into per-entity subqueries ("Hermes", "OpenClaw") whose topic# is too narrow for Gamma API to filter meaningfully. Re-validating the@@ -845,11 +873,37 @@ def _finalize_items_by_source(# in the brief. Spending the enrichment budget here (rather than# at retrieval time) keeps the inline 'via Digg' quotes# paired with the clusters dedupe actually kept.- digg.enrich_source_items(items, top_k=3)+ matched, replayed = http.fixture_source_replay(enrichment_request)+ if matched:+ items = _merge_replayed_enrichment(items, replayed)+ else:+ digg.enrich_source_items(items, top_k=3)+ http.fixture_source_record(enrichment_request, schema.to_dict(items))finalized[source] = itemsreturn finalized+def _merge_replayed_enrichment(+ items: list[schema.SourceItem],+ replayed: list[dict],+) -> list[schema.SourceItem]:+ """Apply recorded post-ranking enrichment onto freshly computed items.++ Enrichment (transcripts, Digg posts) only mutates ``metadata``. Merging by+ item_id instead of replacing the list keeps normalization, scoring, and+ dedupe regressions visible to the eval - fixture state must not overwrite+ what the current pipeline computed.+ """+ replayed_by_id = {+ entry.get("item_id"): entry for entry in replayed if isinstance(entry, dict)+ }+ for item in items:+ record = replayed_by_id.get(item.item_id)+ if record and record.get("metadata"):+ item.metadata.update(record["metadata"])+ return items++def _apply_hiring_signal_gate(bundle: schema.RetrievalBundle,*,@@ -1533,13 +1587,42 @@ def _merge_reddit_items(free: list[dict], sc: list[dict]) -> list[dict]:def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:"""Run one stream and retain HTTP failures swallowed by source adapters."""+ source = str(kwargs.get("source") or "")+ fixture_request = {+ "source": source,+ "topic": kwargs.get("topic") or "",+ "search_query": getattr(kwargs.get("subquery"), "search_query", ""),+ "date_range": list(kwargs.get("date_range") or ()),+ "depth": kwargs.get("depth") or "",+ }+ module_backed = source in {+ "reddit",+ "x",+ "youtube",+ "stocktwits",+ "digg",+ "arxiv",+ "techmeme",+ "trustpilot",+ "github",+ }+ if module_backed:+ matched, replayed = http.fixture_source_replay(fixture_request)+ if matched:+ return replayed[0], replayed[1]try:- with http.capture_failures() as failures:+ with http.capture_failures() as failures, \+ http.fixture_module_capture(module_backed):items, artifact = _retrieve_stream_impl(*args, **kwargs)except Exception as exc:+ recorded_exc = excif failures and not getattr(exc, "outcome_state", None):failure = failures[-1]- raise SourceRunError(str(exc), failure.outcome_state) from exc+ recorded_exc = SourceRunError(str(exc), failure.outcome_state)+ if module_backed:+ http.fixture_source_record_error(fixture_request, recorded_exc)+ if recorded_exc is not exc:+ raise recorded_exc from excraiseoutcome_note = _resolve_stream_outcome(str(kwargs.get("source") or ""),@@ -1549,6 +1632,8 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:if outcome_note:artifact = dict(artifact or {})artifact["_source_outcome"] = outcome_note+ if module_backed:+ http.fixture_source_record(fixture_request, [items, artifact])return items, artifactdiff --git a/tests/eval/__init__.py b/tests/eval/__init__.pynew file mode 100644index 00000000..0b17b9e7--- /dev/null+++ b/tests/eval/__init__.py@@ -0,0 +1 @@+"""Deterministic research-quality evaluation suite."""diff --git a/tests/eval/baseline.json b/tests/eval/baseline.jsonnew file mode 100644index 00000000..84db8ae2--- /dev/null+++ b/tests/eval/baseline.json@@ -0,0 +1,17 @@+{+ "schema_version": 1,+ "metrics": {+ "citation_grounding": 1.0,+ "recency_compliance": 1.0,+ "cluster_coherence": 0.8,+ "coverage": 1.0,+ "determinism": 1.0+ },+ "per_fixture_floors": {+ "citation_grounding": 1.0,+ "recency_compliance": 1.0,+ "cluster_coherence": 0.4,+ "coverage": 1.0,+ "determinism": 1.0+ }+}diff --git a/tests/eval/fixtures/breaking-event/http.json b/tests/eval/fixtures/breaking-event/http.jsonnew file mode 100644index 00000000..1e749cd2--- /dev/null+++ b/tests/eval/fixtures/breaking-event/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=aurora&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "Aurora compiler 2.0 release adds incremental builds",+ "url": "https://web.example.test/breaking-event/result-1",+ "description": "Aurora compiler 2.0 release adds incremental builds. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "Aurora compiler 2.0 release cuts compile latency",+ "url": "https://web.example.test/breaking-event/result-2",+ "description": "Aurora compiler 2.0 release cuts compile latency. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "Aurora compiler users report on the 2.0 release",+ "url": "https://web.example.test/breaking-event/result-3",+ "description": "Aurora compiler users report on the 2.0 release. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=aurora&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "breaking-event-hn-1",+ "title": "Aurora compiler 2.0 ships incremental builds",+ "url": "https://news.example.test/breaking-event/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "breaking-event-hn-2",+ "title": "Aurora 2.0 release cuts compile latency",+ "url": "https://news.example.test/breaking-event/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "breaking-event-hn-3",+ "title": "Aurora compiler users test the 2.0 release",+ "url": "https://news.example.test/breaking-event/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/breaking-event/manifest.json b/tests/eval/fixtures/breaking-event/manifest.jsonnew file mode 100644index 00000000..0f1b1e13--- /dev/null+++ b/tests/eval/fixtures/breaking-event/manifest.json@@ -0,0 +1,42 @@+{+ "name": "breaking-event",+ "archetype": "breaking-event",+ "topic": "Aurora compiler 2.0 released?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "breaking_news",+ "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "raw_topic": "Aurora compiler 2.0 released",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "aurora",+ "ranking_query": "What recent evidence matters for Aurora compiler 2.0 released?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": true+}diff --git a/tests/eval/fixtures/comparison/http.json b/tests/eval/fixtures/comparison/http.jsonnew file mode 100644index 00000000..12659240--- /dev/null+++ b/tests/eval/fixtures/comparison/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=novadb&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "NovaDB versus OrbitDB replication benchmark results",+ "url": "https://web.example.test/comparison/result-1",+ "description": "NovaDB versus OrbitDB replication benchmark results. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "NovaDB and OrbitDB users compare migration costs",+ "url": "https://web.example.test/comparison/result-2",+ "description": "NovaDB and OrbitDB users compare migration costs. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "NovaDB versus OrbitDB edge deployment review",+ "url": "https://web.example.test/comparison/result-3",+ "description": "NovaDB versus OrbitDB edge deployment review. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=novadb&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "comparison-hn-1",+ "title": "NovaDB and OrbitDB trade replication benchmarks",+ "url": "https://news.example.test/comparison/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "comparison-hn-2",+ "title": "NovaDB users compare OrbitDB migration costs",+ "url": "https://news.example.test/comparison/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "comparison-hn-3",+ "title": "NovaDB versus OrbitDB at the edge",+ "url": "https://news.example.test/comparison/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/comparison/manifest.json b/tests/eval/fixtures/comparison/manifest.jsonnew file mode 100644index 00000000..a619e4c0--- /dev/null+++ b/tests/eval/fixtures/comparison/manifest.json@@ -0,0 +1,42 @@+{+ "name": "comparison",+ "archetype": "comparison",+ "topic": "NovaDB vs OrbitDB?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "comparison",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "debate",+ "raw_topic": "NovaDB vs OrbitDB",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "novadb",+ "ranking_query": "What recent evidence matters for NovaDB vs OrbitDB?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": true+}diff --git a/tests/eval/fixtures/emerging-event/http.json b/tests/eval/fixtures/emerging-event/http.jsonnew file mode 100644index 00000000..fee5e300--- /dev/null+++ b/tests/eval/fixtures/emerging-event/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=lunar&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "Lunar robotics launch completes a first field test",+ "url": "https://web.example.test/emerging-event/result-1",+ "description": "Lunar robotics launch completes a first field test. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "Lunar robotics launch telemetry is now public",+ "url": "https://web.example.test/emerging-event/result-2",+ "description": "Lunar robotics launch telemetry is now public. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "Lunar robotics launch prompts a reliability review",+ "url": "https://web.example.test/emerging-event/result-3",+ "description": "Lunar robotics launch prompts a reliability review. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=lunar&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "emerging-event-hn-1",+ "title": "Lunar robotics launch completes first field test",+ "url": "https://news.example.test/emerging-event/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "emerging-event-hn-2",+ "title": "Lunar robotics team publishes launch telemetry",+ "url": "https://news.example.test/emerging-event/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "emerging-event-hn-3",+ "title": "Lunar robotics launch prompts reliability review",+ "url": "https://news.example.test/emerging-event/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/emerging-event/manifest.json b/tests/eval/fixtures/emerging-event/manifest.jsonnew file mode 100644index 00000000..f4405072--- /dev/null+++ b/tests/eval/fixtures/emerging-event/manifest.json@@ -0,0 +1,42 @@+{+ "name": "emerging-event",+ "archetype": "breaking-event",+ "topic": "Lunar robotics launch?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "breaking_news",+ "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "raw_topic": "Lunar robotics launch",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "lunar",+ "ranking_query": "What recent evidence matters for Lunar robotics launch?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": true+}diff --git a/tests/eval/fixtures/niche/http.json b/tests/eval/fixtures/niche/http.jsonnew file mode 100644index 00000000..fde62f72--- /dev/null+++ b/tests/eval/fixtures/niche/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=crdt&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "CRDT design handles edge cache invalidation",+ "url": "https://web.example.test/niche/result-1",+ "description": "CRDT design handles edge cache invalidation. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "CRDT tombstones reduce stale reads in edge caches",+ "url": "https://web.example.test/niche/result-2",+ "description": "CRDT tombstones reduce stale reads in edge caches. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "CRDT cache research compares invalidation strategies",+ "url": "https://web.example.test/niche/result-3",+ "description": "CRDT cache research compares invalidation strategies. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=crdt&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "niche-hn-1",+ "title": "CRDT design improves edge cache invalidation",+ "url": "https://news.example.test/niche/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "niche-hn-2",+ "title": "CRDT tombstones reduce stale edge reads",+ "url": "https://news.example.test/niche/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "niche-hn-3",+ "title": "CRDT cache paper compares invalidation strategies",+ "url": "https://news.example.test/niche/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/niche/manifest.json b/tests/eval/fixtures/niche/manifest.jsonnew file mode 100644index 00000000..afbe7e31--- /dev/null+++ b/tests/eval/fixtures/niche/manifest.json@@ -0,0 +1,42 @@+{+ "name": "niche",+ "archetype": "niche",+ "topic": "CRDT edge cache invalidation?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "concept",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "none",+ "raw_topic": "CRDT edge cache invalidation",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "crdt",+ "ranking_query": "What recent evidence matters for CRDT edge cache invalidation?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": false+}diff --git a/tests/eval/fixtures/non-english-cjk/http.json b/tests/eval/fixtures/non-english-cjk/http.jsonnew file mode 100644index 00000000..f9b3c754--- /dev/null+++ b/tests/eval/fixtures/non-english-cjk/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=%E6%97%A5%E6%9C%AC%E8%AA%9E&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "日本語 AI エージェントの新しい評価手法",+ "url": "https://web.example.test/non-english-cjk/result-1",+ "description": "日本語 AI エージェントの新しい評価手法. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "日本語対応 AI エージェントの実運用報告",+ "url": "https://web.example.test/non-english-cjk/result-2",+ "description": "日本語対応 AI エージェントの実運用報告. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "日本語 AI エージェントの安全設計ガイド",+ "url": "https://web.example.test/non-english-cjk/result-3",+ "description": "日本語 AI エージェントの安全設計ガイド. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=%E6%97%A5%E6%9C%AC%E8%AA%9E&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "non-english-cjk-hn-1",+ "title": "日本語 AI エージェントの評価手法",+ "url": "https://news.example.test/non-english-cjk/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "non-english-cjk-hn-2",+ "title": "日本語対応エージェントの実運用",+ "url": "https://news.example.test/non-english-cjk/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "non-english-cjk-hn-3",+ "title": "日本語 AI エージェントの安全設計",+ "url": "https://news.example.test/non-english-cjk/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/non-english-cjk/manifest.json b/tests/eval/fixtures/non-english-cjk/manifest.jsonnew file mode 100644index 00000000..d39038ce--- /dev/null+++ b/tests/eval/fixtures/non-english-cjk/manifest.json@@ -0,0 +1,42 @@+{+ "name": "non-english-cjk",+ "archetype": "non-english-cjk",+ "topic": "\u65e5\u672c\u8a9e AI \u30a8\u30fc\u30b8\u30a7\u30f3\u30c8?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "concept",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "none",+ "raw_topic": "\u65e5\u672c\u8a9e AI \u30a8\u30fc\u30b8\u30a7\u30f3\u30c8",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "\u65e5\u672c\u8a9e",+ "ranking_query": "What recent evidence matters for \u65e5\u672c\u8a9e AI \u30a8\u30fc\u30b8\u30a7\u30f3\u30c8?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": false+}diff --git a/tests/eval/fixtures/person/http.json b/tests/eval/fixtures/person/http.jsonnew file mode 100644index 00000000..43def758--- /dev/null+++ b/tests/eval/fixtures/person/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=maya&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "Maya Chen shares a practical AI safety field guide",+ "url": "https://web.example.test/person/result-1",+ "description": "Maya Chen shares a practical AI safety field guide. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "Maya Chen explains recurring evaluation failures",+ "url": "https://web.example.test/person/result-2",+ "description": "Maya Chen explains recurring evaluation failures. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "Maya Chen releases an open AI safety benchmark",+ "url": "https://web.example.test/person/result-3",+ "description": "Maya Chen releases an open AI safety benchmark. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=maya&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "person-hn-1",+ "title": "Maya Chen publishes an AI safety field guide",+ "url": "https://news.example.test/person/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "person-hn-2",+ "title": "Maya Chen discusses evaluation failures",+ "url": "https://news.example.test/person/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "person-hn-3",+ "title": "Maya Chen opens a safety benchmark",+ "url": "https://news.example.test/person/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/person/manifest.json b/tests/eval/fixtures/person/manifest.jsonnew file mode 100644index 00000000..744a8365--- /dev/null+++ b/tests/eval/fixtures/person/manifest.json@@ -0,0 +1,42 @@+{+ "name": "person",+ "archetype": "person",+ "topic": "Maya Chen AI safety?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "opinion",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "debate",+ "raw_topic": "Maya Chen AI safety",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "maya",+ "ranking_query": "What recent evidence matters for Maya Chen AI safety?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": true+}diff --git a/tests/eval/fixtures/tech-product/http.json b/tests/eval/fixtures/tech-product/http.jsonnew file mode 100644index 00000000..29af6322--- /dev/null+++ b/tests/eval/fixtures/tech-product/http.json@@ -0,0 +1,83 @@+{+ "format": "last30days-http-fixture/v1",+ "exchanges": [+ {+ "request": {+ "method": "GET",+ "url": "https://api.search.brave.com/res/v1/web/search?q=nimbus&count=5&freshness=2026-06-10to2026-07-10",+ "raw": false+ },+ "response": {+ "value": {+ "web": {+ "results": [+ {+ "title": "Nimbus tool routing improves reliable agent workflows",+ "url": "https://web.example.test/tech-product/result-1",+ "description": "Nimbus tool routing improves reliable agent workflows. Recorded public fixture content.",+ "page_age": "2026-07-02T00:00:00Z"+ },+ {+ "title": "Nimbus benchmark measures faster local research runs",+ "url": "https://web.example.test/tech-product/result-2",+ "description": "Nimbus benchmark measures faster local research runs. Recorded public fixture content.",+ "page_age": "2026-07-03T00:00:00Z"+ },+ {+ "title": "Nimbus users compare memory defaults in production",+ "url": "https://web.example.test/tech-product/result-3",+ "description": "Nimbus users compare memory defaults in production. Recorded public fixture content.",+ "page_age": "2026-07-04T00:00:00Z"+ }+ ]+ }+ }+ }+ },+ {+ "request": {+ "method": "GET",+ "url": "https://hn.algolia.com/api/v1/search?query=nimbus&tags=story&numericFilters=created_at_i%3E1781049600%2Ccreated_at_i%3C1783728000&hitsPerPage=30",+ "raw": false+ },+ "response": {+ "value": {+ "hits": [+ {+ "objectID": "tech-product-hn-1",+ "title": "Nimbus agents add deterministic tool routing",+ "url": "https://news.example.test/tech-product/hn-1",+ "author": "fixture_author_1",+ "points": 120,+ "num_comments": 35,+ "created_at_i": 1782864000,+ "created_at": "2026-07-01T00:00:00Z"+ },+ {+ "objectID": "tech-product-hn-2",+ "title": "Nimbus benchmark shows faster local research",+ "url": "https://news.example.test/tech-product/hn-2",+ "author": "fixture_author_2",+ "points": 100,+ "num_comments": 30,+ "created_at_i": 1782950400,+ "created_at": "2026-07-02T00:00:00Z"+ },+ {+ "objectID": "tech-product-hn-3",+ "title": "Nimbus users debate memory defaults",+ "url": "https://news.example.test/tech-product/hn-3",+ "author": "fixture_author_3",+ "points": 80,+ "num_comments": 25,+ "created_at_i": 1783036800,+ "created_at": "2026-07-03T00:00:00Z"+ }+ ],+ "page": 0,+ "nbHits": 3+ }+ }+ }+ ]+}diff --git a/tests/eval/fixtures/tech-product/manifest.json b/tests/eval/fixtures/tech-product/manifest.jsonnew file mode 100644index 00000000..fd0793a7--- /dev/null+++ b/tests/eval/fixtures/tech-product/manifest.json@@ -0,0 +1,42 @@+{+ "name": "tech-product",+ "archetype": "tech-product",+ "topic": "Nimbus Agent workflows?",+ "as_of_date": "2026-07-10",+ "lookback_days": 30,+ "depth": "quick",+ "fixture_sources": [+ "grounding",+ "hackernews"+ ],+ "web_backend": "brave",+ "config": {+ "BRAVE_API_KEY": "fixture-key"+ },+ "plan": {+ "intent": "product",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "none",+ "raw_topic": "Nimbus Agent workflows",+ "subqueries": [+ {+ "label": "primary",+ "search_query": "nimbus",+ "ranking_query": "What recent evidence matters for Nimbus Agent workflows?",+ "sources": [+ "grounding",+ "hackernews"+ ],+ "weight": 1+ }+ ],+ "source_weights": {+ "grounding": 1,+ "hackernews": 1+ },+ "notes": [+ "eval-fixture-plan"+ ]+ },+ "expects_clusters": false+}diff --git a/tests/eval/harness.py b/tests/eval/harness.pynew file mode 100644index 00000000..646a1eb9--- /dev/null+++ b/tests/eval/harness.py@@ -0,0 +1,274 @@+"""Offline research-quality eval harness built on recorded source responses."""++from __future__ import annotations++import itertools+import json+import sys+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any+from unittest import mock++ROOT = Path(__file__).resolve().parents[2]+SCRIPTS = ROOT / "skills" / "last30days" / "scripts"+if str(SCRIPTS) not in sys.path:+ sys.path.insert(0, str(SCRIPTS))++from lib import entity_extract, http, pipeline, schema # noqa: E402++FIXTURES_DIR = Path(__file__).with_name("fixtures")+BASELINE_PATH = Path(__file__).with_name("baseline.json")+METRIC_NAMES = (+ "citation_grounding",+ "recency_compliance",+ "cluster_coherence",+ "coverage",+ "determinism",+)+ENTITY_OVERLAP_FLOOR = 0.45+++class _FrozenDateTime(datetime):+ @classmethod+ def now(cls, tz=None):+ fixed = cls(2026, 7, 10, 12, 0, 0, tzinfo=timezone.utc)+ return fixed if tz is not None else fixed.replace(tzinfo=None)+++@dataclass(frozen=True)+class EvalFixture:+ name: str+ path: Path+ manifest: dict[str, Any]+ input_urls: frozenset[str]+++@dataclass+class EvalResult:+ fixture: EvalFixture+ report: schema.Report+ scores: dict[str, float]+++def _http_urls(value: Any) -> set[str]:+ urls: set[str] = set()+ if isinstance(value, dict):+ for child in value.values():+ urls.update(_http_urls(child))+ elif isinstance(value, list):+ for child in value:+ urls.update(_http_urls(child))+ elif isinstance(value, str) and value.startswith(("https://", "http://")):+ urls.add(value)+ return urls+++def load_fixtures(root: Path = FIXTURES_DIR) -> list[EvalFixture]:+ fixtures: list[EvalFixture] = []+ for manifest_path in sorted(root.glob("*/manifest.json")):+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ http_payload = json.loads((manifest_path.parent / "http.json").read_text(encoding="utf-8"))+ input_urls: set[str] = set()+ for exchange in http_payload.get("exchanges") or []:+ input_urls.update(_http_urls((exchange.get("response") or {}).get("value")))+ for exchange in http_payload.get("source_exchanges") or []:+ input_urls.update(_http_urls(exchange.get("value")))+ fixtures.append(+ EvalFixture(+ name=manifest.get("name") or manifest_path.parent.name,+ path=manifest_path.parent,+ manifest=manifest,+ input_urls=frozenset(input_urls),+ )+ )+ return fixtures+++def _run_once(fixture: EvalFixture) -> schema.Report:+ manifest = fixture.manifest+ config = dict(manifest.get("config") or {})+ network_error = AssertionError(f"Network attempted while replaying {fixture.name}")+ with mock.patch.object(pipeline, "datetime", _FrozenDateTime), \+ mock.patch.object(schema, "datetime", _FrozenDateTime), \+ mock.patch.object(+ pipeline,+ "available_sources",+ return_value=list(manifest["fixture_sources"]),+ ), \+ mock.patch.object(http.urllib.request, "urlopen", side_effect=network_error), \+ http.replaying_requests(fixture.path):+ return pipeline.run(+ topic=manifest["topic"],+ config=config,+ depth=manifest.get("depth", "quick"),+ requested_sources=list(manifest["fixture_sources"]),+ mock=False,+ web_backend=manifest.get("web_backend", "none"),+ external_plan=manifest["plan"],+ lookback_days=int(manifest.get("lookback_days", 30)),+ as_of_date=manifest["as_of_date"],+ )+++def _citation_grounding(report: schema.Report, fixture: EvalFixture) -> float:+ results = schema.to_agent_export(report)["results"]+ if not results:+ return 0.0+ grounded = sum(bool(result.get("url")) and result["url"] in fixture.input_urls for result in results)+ return grounded / len(results)+++def _recency_compliance(report: schema.Report) -> float:+ ranked_items = [+ item+ for candidate in report.ranked_candidates+ for item in candidate.source_items+ ]+ if not ranked_items:+ return 0.0+ compliant = sum(+ not item.published_at+ or report.range_from <= item.published_at[:10] <= report.range_to+ for item in ranked_items+ )+ return compliant / len(ranked_items)+++def _cluster_coherence(report: schema.Report, fixture: EvalFixture) -> float:+ candidates = {candidate.candidate_id: candidate for candidate in report.ranked_candidates}+ pair_scores: list[float] = []+ for report_cluster in report.clusters:+ members = [candidates[candidate_id] for candidate_id in report_cluster.candidate_ids if candidate_id in candidates]+ for left, right in itertools.combinations(members, 2):+ left_entities = entity_extract.extract_text_entities(f"{left.title} {left.snippet}")+ right_entities = entity_extract.extract_text_entities(f"{right.title} {right.snippet}")+ overlap = entity_extract.entity_overlap(left_entities, right_entities)+ pair_scores.append(1.0 if overlap >= ENTITY_OVERLAP_FLOOR else 0.0)+ if pair_scores:+ return sum(pair_scores) / len(pair_scores)+ # No multi-member clusters formed. For fixtures that historically cluster+ # (expects_clusters: true in the manifest), that means cluster formation+ # regressed and must fail rather than score a vacuous 1.0. Sparse topics+ # that legitimately produce singletons declare expects_clusters: false.+ return 0.0 if fixture.manifest.get("expects_clusters") else 1.0+++def _coverage(report: schema.Report, fixture: EvalFixture) -> float:+ sources = list(fixture.manifest["fixture_sources"])+ if not sources:+ return 0.0+ covered = sum(+ bool(report.items_by_source.get(source)) or source in report.source_status+ for source in sources+ )+ return covered / len(sources)+++def score_report(+ report: schema.Report,+ fixture: EvalFixture,+ *,+ deterministic: bool,+) -> dict[str, float]:+ return {+ "citation_grounding": _citation_grounding(report, fixture),+ "recency_compliance": _recency_compliance(report),+ "cluster_coherence": _cluster_coherence(report, fixture),+ "coverage": _coverage(report, fixture),+ "determinism": 1.0 if deterministic else 0.0,+ }+++def evaluate_fixture(fixture: EvalFixture) -> EvalResult:+ first = _run_once(fixture)+ second = _run_once(fixture)+ deterministic = schema.to_dict(first) == schema.to_dict(second)+ return EvalResult(+ fixture=fixture,+ report=first,+ scores=score_report(first, fixture, deterministic=deterministic),+ )+++def evaluate_all(fixtures: list[EvalFixture] | None = None) -> list[EvalResult]:+ selected = fixtures if fixtures is not None else load_fixtures()+ if not selected:+ raise AssertionError(f"No eval fixtures found under {FIXTURES_DIR}")+ return [evaluate_fixture(fixture) for fixture in selected]+++def aggregate_scores(results: list[EvalResult]) -> dict[str, float]:+ return {+ metric: sum(result.scores[metric] for result in results) / len(results)+ for metric in METRIC_NAMES+ }+++def load_baseline(path: Path = BASELINE_PATH) -> dict[str, float]:+ payload = json.loads(path.read_text(encoding="utf-8"))+ return {metric: float(payload["metrics"][metric]) for metric in METRIC_NAMES}+++def baseline_failures(+ scores: dict[str, float],+ baseline: dict[str, float] | None = None,+) -> list[str]:+ floors = baseline if baseline is not None else load_baseline()+ return [+ f"{metric}: {scores[metric]:.3f} < {floors[metric]:.3f}"+ for metric in METRIC_NAMES+ if scores[metric] + 1e-12 < floors[metric]+ ]+++def per_fixture_failures(results: list["EvalResult"]) -> list[str]:+ """Enforce per-fixture floors so one broken archetype cannot hide in the+ cross-fixture average (a total clustering failure on breaking-event scores+ 0.0 but averages to 0.857 across seven fixtures)."""+ raw = json.loads(BASELINE_PATH.read_text())+ floors = raw.get("per_fixture_floors") or {}+ failures: list[str] = []+ for result in results:+ for metric, floor in floors.items():+ value = result.scores.get(metric)+ if value is not None and value + 1e-12 < float(floor):+ failures.append(+ f"{result.fixture.name}/{metric}: {value:.3f} < {float(floor):.3f}"+ )+ return failures+++def format_score_table(results: list[EvalResult]) -> str:+ aggregate = aggregate_scores(results)+ headers = ["fixture", *METRIC_NAMES]+ rows = [+ [result.fixture.name, *(f"{result.scores[name]:.3f}" for name in METRIC_NAMES)]+ for result in results+ ]+ rows.append(["AVERAGE", *(f"{aggregate[name]:.3f}" for name in METRIC_NAMES)])+ widths = [max(len(str(row[index])) for row in [headers, *rows]) for index in range(len(headers))]+ rendered = [" | ".join(str(value).ljust(widths[index]) for index, value in enumerate(headers))]+ rendered.append("-+-".join("-" * width for width in widths))+ rendered.extend(+ " | ".join(str(value).ljust(widths[index]) for index, value in enumerate(row))+ for row in rows+ )+ return "\n".join(rendered)+++def main() -> int:+ results = evaluate_all()+ print(format_score_table(results))+ failures = baseline_failures(aggregate_scores(results))+ if failures:+ print("\nBaseline failures:", file=sys.stderr)+ for failure in failures:+ print(f"- {failure}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/eval/test_eval_harness.py b/tests/eval/test_eval_harness.pynew file mode 100644index 00000000..f648b5d7--- /dev/null+++ b/tests/eval/test_eval_harness.py@@ -0,0 +1,200 @@+from __future__ import annotations++import json+from copy import deepcopy+from unittest import mock++from . import harness+++def test_fixture_matrix_covers_required_topic_archetypes():+ fixtures = harness.load_fixtures()+ archetypes = {fixture.manifest["archetype"] for fixture in fixtures}++ assert 6 <= len(fixtures) <= 8+ assert {+ "tech-product",+ "person",+ "comparison",+ "breaking-event",+ "niche",+ "non-english-cjk",+ } <= archetypes+++def test_research_quality_scores_meet_committed_baselines():+ results = harness.evaluate_all()+ print(harness.format_score_table(results))++ failures = harness.baseline_failures(harness.aggregate_scores(results))+ failures += harness.per_fixture_failures(results)+ assert not failures, "\n".join(failures)+++def test_per_fixture_floor_catches_single_broken_archetype():+ results = harness.evaluate_all()+ # Simulate a total clustering failure on one clustered fixture: the+ # average stays above the aggregate floor but the per-fixture floor fires.+ broken = None+ for result in results:+ if result.fixture.manifest.get("expects_clusters"):+ result.scores["cluster_coherence"] = 0.0+ broken = result.fixture.name+ break+ assert broken is not None+ aggregate_ok = not harness.baseline_failures(harness.aggregate_scores(results))+ per_fixture = harness.per_fixture_failures(results)+ assert any(f.startswith(f"{broken}/cluster_coherence") for f in per_fixture)+ # Document why the per-fixture layer exists: with 7 fixtures the aggregate+ # can absorb one zero.+ if aggregate_ok:+ assert per_fixture+++def test_entity_overlap_predicate_pinned():+ # The coherence metric shares extract_text_entities/entity_overlap with+ # production clustering. Pin the predicate on fixed inputs so a+ # too-permissive drift is caught independently of the (circular) metric.+ from lib import entity_extract++ same = entity_extract.entity_overlap(+ entity_extract.extract_text_entities("OpenAI ships GPT-6 to enterprise customers"),+ entity_extract.extract_text_entities("Enterprise customers get GPT-6 from OpenAI"),+ )+ unrelated = entity_extract.entity_overlap(+ entity_extract.extract_text_entities("OpenAI ships GPT-6 to enterprise customers"),+ entity_extract.extract_text_entities("Best sourdough starter recipes for beginners"),+ )+ assert same >= harness.ENTITY_OVERLAP_FLOOR, f"related pair fell below floor: {same}"+ assert unrelated < harness.ENTITY_OVERLAP_FLOOR, (+ f"unrelated pair passed the overlap floor ({unrelated}); the shared "+ "predicate got too permissive and the coherence metric is now blind"+ )+++def test_replay_uses_manifest_source_availability(tmp_path):+ fixture_path = tmp_path / "cli-sources"+ fixture_path.mkdir()+ (fixture_path / "http.json").write_text(+ json.dumps(+ {+ "format": "last30days-http-fixture/v1",+ "exchanges": [],+ "source_exchanges": [],+ }+ ),+ encoding="utf-8",+ )+ fixture = harness.EvalFixture(+ name="cli-sources",+ path=fixture_path,+ manifest={+ "topic": "fixture topic",+ "as_of_date": "2026-07-10",+ "fixture_sources": ["digg", "arxiv", "techmeme", "trustpilot"],+ "plan": {},+ },+ input_urls=frozenset(),+ )++ def observe_availability(**_kwargs):+ return harness.pipeline.available_sources({}, fixture.manifest["fixture_sources"])++ with mock.patch.object(harness.pipeline, "run", side_effect=observe_availability), \+ mock.patch.object(harness.pipeline, "which", return_value=None):+ available = harness._run_once(fixture)++ assert available == fixture.manifest["fixture_sources"]+++def test_intentional_out_of_window_regression_fails_recency_floor():+ fixture = harness.load_fixtures()[0]+ result = harness.evaluate_fixture(fixture)+ regressed = deepcopy(result.report)+ primary = regressed.ranked_candidates[0].source_items[0]+ primary.published_at = "2025-01-01"++ scores = harness.score_report(regressed, fixture, deterministic=True)+ failures = harness.baseline_failures(scores)++ assert scores["recency_compliance"] < 1.0+ assert any(failure.startswith("recency_compliance:") for failure in failures)+++def test_coherence_fails_when_expected_clusters_vanish():+ fixtures = {f.name: f for f in harness.load_fixtures()}+ clustered = fixtures["breaking-event"]+ assert clustered.manifest["expects_clusters"] is True+ report = harness._run_once(clustered)+ # Simulate cluster formation regressing to singletons.+ report.clusters = []+ assert harness._cluster_coherence(report, clustered) == 0.0+++def test_coherence_allows_singletons_for_sparse_fixtures():+ fixtures = {f.name: f for f in harness.load_fixtures()}+ sparse = fixtures["niche"]+ assert sparse.manifest.get("expects_clusters") is False+ report = harness._run_once(sparse)+ report.clusters = []+ assert harness._cluster_coherence(report, sparse) == 1.0+++def test_enrichment_replay_merges_metadata_without_replacing_items():+ import sys+ sys.path.insert(0, "skills/last30days/scripts")+ from lib import pipeline, schema++ fresh = schema.SourceItem(+ item_id="yt-1",+ source="youtube",+ title="Fresh title from current normalization",+ body="fresh body",+ url="https://youtube.com/watch?v=1",+ published_at="2026-07-01",+ snippet="fresh snippet",+ engagement={"views": 10},+ metadata={"channel": "fresh-channel"},+ )+ replayed = [{+ "item_id": "yt-1",+ "title": "STALE fixture title",+ "snippet": "STALE snippet",+ "metadata": {"transcript_snippet": "recorded transcript"},+ }]+ merged = pipeline._merge_replayed_enrichment([fresh], replayed)+ assert merged[0].title == "Fresh title from current normalization"+ assert merged[0].snippet == "fresh snippet"+ assert merged[0].metadata["transcript_snippet"] == "recorded transcript"+ assert merged[0].metadata["channel"] == "fresh-channel"+++def test_star_enrichment_apply_map_offline():+ import sys+ sys.path.insert(0, "skills/last30days/scripts")+ from lib import github, schema++ candidate = schema.Candidate(+ candidate_id="c-gh",+ item_id="gh-1",+ source="github",+ title="repo mvanhorn/last30days-skill discussion",+ url="https://github.com/mvanhorn/last30days-skill",+ snippet="s",+ subquery_labels=["primary"],+ native_ranks={"primary:github": 1},+ local_relevance=0.9,+ freshness=90,+ engagement=10,+ source_quality=0.5,+ rrf_score=0.1,+ final_score=90,+ cluster_id="cl",+ source_items=[],+ metadata={},+ )+ enriched = github.apply_star_map(+ [candidate], {"mvanhorn/last30days-skill": 51436}+ )+ assert enriched == 1+ assert candidate.metadata["github_stars"]["mvanhorn/last30days-skill"] == 51436diff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex ed8d1b8d..eea22593 100644--- a/tests/test_doc_flag_contract.py+++ b/tests/test_doc_flag_contract.py@@ -34,6 +34,9 @@ def test_configuration_documents_new_safety_flags():assert "--publish-password" in flagsassert "--publish-password" in textassert "LAST30DAYS_PUBLISH_PASSWORD" in text+ assert "--record-fixtures" in flags+ assert "--record-fixtures" in text+ assert "docs/reference/eval.md" in textdef test_html_publish_reference_prompts_for_password_choice():diff --git a/tests/test_github_device_auth.py b/tests/test_github_device_auth.pyindex 928867eb..f6672f47 100644--- a/tests/test_github_device_auth.py+++ b/tests/test_github_device_auth.py@@ -20,7 +20,10 @@ class TestUserCodeValidation:@patch("lib.setup_wizard.subprocess.run")@patch("lib.setup_wizard.run_device_auth")- def test_malformed_user_code_is_rejected(self, mock_run_device, mock_subprocess_run):+ @patch("lib.setup_wizard._existing_scrapecreators_key", return_value=None)+ def test_malformed_user_code_is_rejected(+ self, _mock_existing, mock_run_device, mock_subprocess_run+ ):# mock_subprocess_run patches setup_wizard.subprocess.run; the only such# call in run_full_device_auth is the pbcopy of the code.# A key-shaped value (no dash, 28 chars) must never be treated as a code.@@ -49,8 +52,9 @@ class TestDeviceCodeReadyEmission:@patch("lib.setup_wizard.subprocess.run")@patch("lib.setup_wizard.poll_device_auth")@patch("lib.setup_wizard.run_device_auth")+ @patch("lib.setup_wizard._existing_scrapecreators_key", return_value=None)def test_valid_code_emitted_to_stdout(- self, mock_run_device, mock_poll, mock_pbcopy, mock_browser+ self, _mock_existing, mock_run_device, mock_poll, mock_pbcopy, mock_browser):mock_run_device.return_value = ("dev-code-123",diff --git a/tests/test_http_fixtures.py b/tests/test_http_fixtures.pynew file mode 100644index 00000000..5a1076e0--- /dev/null+++ b/tests/test_http_fixtures.py@@ -0,0 +1,239 @@+from __future__ import annotations++import json+from unittest.mock import MagicMock++import pytest++import last30days as cli+from lib import http, pipeline, schema+++def _response(body: str):+ response = MagicMock()+ response.__enter__.return_value = response+ response.__exit__.return_value = False+ response.read.return_value = body.encode("utf-8")+ response.status = 200+ return response+++def test_http_recording_scrubs_credentials_and_replays_offline(tmp_path, monkeypatch):+ monkeypatch.setattr(http.urllib.request, "urlopen", lambda *_args, **_kwargs: _response('{"items": [{"url": "https://example.test/item"}]}'))+ fixture_dir = tmp_path / "fixture"++ with http.recording_requests(fixture_dir):+ live = http.get("https://api.example.test/search?api_key=live-secret&q=agents")++ fixture_text = (fixture_dir / "http.json").read_text(encoding="utf-8")+ assert "live-secret" not in fixture_text+ assert "%3Credacted%3E" in fixture_text++ monkeypatch.setattr(+ http.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: pytest.fail("fixture replay attempted the network"),+ )+ with http.replaying_requests(fixture_dir):+ replayed = http.get("https://api.example.test/search?api_key=another-secret&q=agents")++ assert replayed == live+++def test_http_recording_redacts_credentials_echoed_in_response_values(tmp_path, monkeypatch):+ monkeypatch.setattr(+ http.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: _response('{"echo": "Bearer live-secret"}'),+ )+ fixture_dir = tmp_path / "fixture"++ with http.recording_requests(fixture_dir):+ http.get(+ "https://api.example.test/profile",+ headers={"Authorization": "Bearer live-secret"},+ )++ fixture_text = (fixture_dir / "http.json").read_text(encoding="utf-8")+ assert "live-secret" not in fixture_text+ assert '"echo": "<redacted>"' in fixture_text+++def test_aborted_recording_does_not_overwrite_existing_fixture(tmp_path):+ fixture = tmp_path / "http.json"+ fixture.write_text("existing fixture\n", encoding="utf-8")++ with pytest.raises(RuntimeError, match="capture failed"):+ with http.recording_requests(fixture):+ raise RuntimeError("capture failed")++ assert fixture.read_text(encoding="utf-8") == "existing fixture\n"+++def test_http_replay_rejects_unrecorded_requests(tmp_path):+ fixture = tmp_path / "http.json"+ fixture.write_text(+ json.dumps({"format": "last30days-http-fixture/v1", "exchanges": []}),+ encoding="utf-8",+ )++ with pytest.raises(AssertionError, match="Unrecorded HTTP request"), \+ http.replaying_requests(fixture):+ http.get("https://example.test/not-recorded")+++def test_cli_backed_source_results_record_at_the_module_seam(tmp_path):+ fixture_dir = tmp_path / "fixture"+ request = {+ "source": "digg",+ "topic": "agents",+ "search_query": "agents",+ "date_range": ["2026-06-10", "2026-07-10"],+ "depth": "quick",+ }+ value = [[{"url": "https://di.gg/ai/example"}], {"provider": "fixture"}]++ with http.recording_requests(fixture_dir):+ http.fixture_source_record(request, value)++ with http.replaying_requests(fixture_dir):+ matched, replayed = http.fixture_source_replay(request)++ assert matched is True+ assert replayed == value+++def test_module_seam_capture_omits_nested_http_exchanges(tmp_path, monkeypatch):+ monkeypatch.setattr(http.urllib.request, "urlopen", lambda *_args, **_kwargs: _response('{"ok": true}'))+ fixture_dir = tmp_path / "fixture"+ request = {+ "source": "youtube",+ "topic": "agents",+ "search_query": "agents",+ "date_range": ["2026-06-10", "2026-07-10"],+ "depth": "quick",+ }++ with http.recording_requests(fixture_dir):+ with http.fixture_module_capture(True):+ http.get("https://api.example.test/nested-enrichment")+ http.fixture_source_record(request, [[], {}])++ payload = json.loads((fixture_dir / "http.json").read_text(encoding="utf-8"))+ assert payload["exchanges"] == []+ assert len(payload["source_exchanges"]) == 1+++def test_module_seam_records_and_replays_adapter_failures(tmp_path, monkeypatch):+ fixture_dir = tmp_path / "fixture"+ kwargs = {+ "source": "digg",+ "topic": "agents",+ "subquery": type("SubQuery", (), {"search_query": "agents"})(),+ "date_range": ("2026-06-10", "2026-07-10"),+ "depth": "quick",+ }+ monkeypatch.setattr(+ pipeline,+ "_retrieve_stream_impl",+ lambda **_kwargs: (_ for _ in ()).throw(RuntimeError("adapter failed")),+ )++ with http.recording_requests(fixture_dir):+ with pytest.raises(RuntimeError, match="adapter failed"):+ pipeline._retrieve_stream(**kwargs)++ payload = json.loads((fixture_dir / "http.json").read_text(encoding="utf-8"))+ assert payload["source_exchanges"] == [+ {+ "request": {+ "source": "digg",+ "topic": "agents",+ "search_query": "agents",+ "date_range": ["2026-06-10", "2026-07-10"],+ "depth": "quick",+ },+ "type": "error",+ "error": {+ "exception_type": "RuntimeError",+ "message": "adapter failed",+ "outcome_state": None,+ },+ }+ ]++ monkeypatch.setattr(+ pipeline,+ "_retrieve_stream_impl",+ lambda **_kwargs: pytest.fail("replay called the live adapter"),+ )+ with http.replaying_requests(fixture_dir):+ with pytest.raises(http.RecordedSourceError, match="adapter failed") as replayed:+ pipeline._retrieve_stream(**kwargs)++ assert replayed.value.exception_type == "RuntimeError"++[email protected]("source", ["youtube", "digg"])+def test_post_ranking_cli_enrichment_records_and_replays(+ tmp_path,+ monkeypatch,+ source,+):+ fixture_dir = tmp_path / source+ item = schema.SourceItem(+ item_id="item-1",+ source=source,+ title="Fixture item",+ body="Fixture body",+ url=f"https://example.test/{source}/item-1",+ engagement={"postCount": 1} if source == "digg" else {},+ metadata={"clusterUrlId": "cluster-1"} if source == "digg" else {},+ )+ if source == "youtube":+ def enrich(items, **_kwargs):+ items[0].metadata["transcript_snippet"] = "recorded transcript"++ monkeypatch.setattr(pipeline.youtube_yt, "backfill_transcripts", enrich)+ else:+ def enrich(items, **_kwargs):+ items[0].metadata["posts"] = [{"url": "https://x.com/example/status/1"}]+ return items++ monkeypatch.setattr(pipeline.digg, "enrich_source_items", enrich)++ with http.recording_requests(fixture_dir):+ recorded = pipeline._finalize_items_by_source(+ {source: [item]}, topic="agents", depth="quick",+ )++ expected_metadata = recorded[source][0].metadata+ replay_item = schema.SourceItem(+ item_id="item-1",+ source=source,+ title="Fixture item",+ body="Fixture body",+ url=f"https://example.test/{source}/item-1",+ engagement={"postCount": 1} if source == "digg" else {},+ metadata={"clusterUrlId": "cluster-1"} if source == "digg" else {},+ )+ monkeypatch.setattr(+ pipeline.youtube_yt if source == "youtube" else pipeline.digg,+ "backfill_transcripts" if source == "youtube" else "enrich_source_items",+ lambda *_args, **_kwargs: pytest.fail("replay executed CLI enrichment"),+ )++ with http.replaying_requests(fixture_dir):+ replayed = pipeline._finalize_items_by_source(+ {source: [replay_item]}, topic="agents", depth="quick",+ )++ assert replayed[source][0].metadata == expected_metadata+++def test_record_fixtures_flag_is_dev_only_and_hidden_from_help():+ parser = cli.build_parser()+ args = parser.parse_args(["topic", "--record-fixtures", "tmp/eval-topic"])++ assert args.record_fixtures == "tmp/eval-topic"+ assert "--record-fixtures" not in parser.format_help()