""" Agent-Specific Historical Backfill. Pulls historical data for the 57-agent registry from sources that support date-range queries. This extends the observation window from 14 days to 3+ months for the NeurIPS D&B submission. Backfill sources: - Hacker News (Algolia API): full history, date-filterable - arXiv: papers mentioning agents from last 6 months - Stack Overflow: questions with fromdate/todate (SE API v2.3) - GitHub: star history, releases, contributor growth - PyPI: historical download stats (pypistats.org) Usage: python -m collectors.backfill_agents # all sources, 3 months python -m collectors.backfill_agents --source hn # HN only python -m collectors.backfill_agents --months 4 # go back 4 months python -m collectors.backfill_agents --source github # GitHub history """ import sys import time import json import httpx import logging import argparse from datetime import datetime, timedelta, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent)) from db.schema import db, get_connection from collectors.agent_signals import AGENT_REGISTRY logger = logging.getLogger(__name__) # ═══════════════════════════════════════════════════════════════════════════════ # Build search terms from agent registry # ═══════════════════════════════════════════════════════════════════════════════ def _get_agent_search_terms() -> dict[str, list[str]]: """Return {search_term: [agent_name, ...]} for all agents.""" terms = {} for agent_name, info in AGENT_REGISTRY.items(): for term in info.get("search", []): terms.setdefault(term, []).append(agent_name) return terms # ═══════════════════════════════════════════════════════════════════════════════ # HN Backfill (Algolia API — supports full history) # ═══════════════════════════════════════════════════════════════════════════════ def backfill_hn_agents(months: int = 3) -> int: """Backfill HN stories mentioning agents from past N months.""" logger.info("[backfill-agents] HN: going back %d months...", months) rows_inserted = 0 now = datetime.now(timezone.utc) start_ts = int((now - timedelta(days=months * 30)).timestamp()) agent_terms = _get_agent_search_terms() with httpx.Client(timeout=30) as client: for term, agent_names in agent_terms.items(): page = 0 while page < 10: params = { "query": term, "tags": "(story,ask_hn,comment)", "numericFilters": f"created_at_i>{start_ts}", "hitsPerPage": 50, "page": page, } try: r = client.get("https://hn.algolia.com/api/v1/search", params=params) if r.status_code != 200: break except Exception: break data = r.json() hits = data.get("hits", []) if not hits: break with db() as conn: for hit in hits: story_id = str(hit.get("objectID", "")) created_ts = hit.get("created_at_i") created_at = (datetime.fromtimestamp(created_ts, tz=timezone.utc) .strftime("%Y-%m-%d %H:%M:%S") if created_ts else None) title = hit.get("title") or hit.get("comment_text", "")[:200] or "" for agent_name in agent_names: try: conn.execute(""" INSERT OR IGNORE INTO hn_signals (model_slug, story_id, title, score, num_comments, author, created_at, collected_at) VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now')) """, (agent_name, story_id, title[:500], hit.get("points", 0), hit.get("num_comments", 0), hit.get("author"), created_at)) rows_inserted += 1 except Exception: pass page += 1 if page >= data.get("nbPages", 0): break time.sleep(0.3) time.sleep(0.5) logger.info("[backfill-agents] HN: inserted %d rows", rows_inserted) return rows_inserted # ═══════════════════════════════════════════════════════════════════════════════ # Stack Overflow Backfill (SE API v2.3 — supports fromdate/todate) # ═══════════════════════════════════════════════════════════════════════════════ def backfill_stackoverflow_agents(months: int = 3) -> int: """Backfill Stack Overflow questions mentioning agents from past N months.""" logger.info("[backfill-agents] StackOverflow: going back %d months...", months) rows_inserted = 0 now = datetime.now(timezone.utc) from_ts = int((now - timedelta(days=months * 30)).timestamp()) agent_terms = _get_agent_search_terms() with httpx.Client(timeout=30) as client: for term, agent_names in agent_terms.items(): params = { "order": "desc", "sort": "creation", "q": term, "site": "stackoverflow", "pagesize": 50, "fromdate": from_ts, "filter": "default", } try: r = client.get("https://api.stackexchange.com/2.3/search/advanced", params=params) if r.status_code != 200: continue data = r.json() except Exception: continue items = data.get("items", []) with db() as conn: for item in items: q_id = str(item.get("question_id", "")) created_at = datetime.fromtimestamp( item.get("creation_date", 0), tz=timezone.utc ).strftime("%Y-%m-%d %H:%M:%S") for agent_name in agent_names: try: conn.execute(""" INSERT OR IGNORE INTO stackoverflow_signals (model_slug, question_id, title, score, answer_count, view_count, is_answered, tags, created_at, collected_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now')) """, (agent_name, q_id, item.get("title", ""), item.get("score", 0), item.get("answer_count", 0), item.get("view_count", 0), 1 if item.get("is_answered") else 0, ",".join(item.get("tags", [])), created_at)) rows_inserted += 1 except Exception: pass # SE API has 300 req/day quota — pace conservatively time.sleep(2) if data.get("quota_remaining", 999) < 10: logger.warning("[backfill-agents] SO quota low, stopping") break logger.info("[backfill-agents] SO: inserted %d rows", rows_inserted) return rows_inserted # ═══════════════════════════════════════════════════════════════════════════════ # GitHub Historical Backfill (star history, releases, contributors over time) # ═══════════════════════════════════════════════════════════════════════════════ def backfill_github_agents(months: int = 3) -> int: """Backfill GitHub release history + contributor growth for agents with repos.""" logger.info("[backfill-agents] GitHub: going back %d months...", months) rows_inserted = 0 import os token = os.environ.get("GITHUB_TOKEN", "") headers = {"Accept": "application/vnd.github+json"} if token: headers["Authorization"] = f"Bearer {token}" with httpx.Client(timeout=30, headers=headers) as client: for agent_name, info in AGENT_REGISTRY.items(): repo = info.get("github") if not repo: continue # Get release history try: r = client.get(f"https://api.github.com/repos/{repo}/releases", params={"per_page": 30}) if r.status_code == 200: releases = r.json() with db() as conn: for rel in releases: published = rel.get("published_at", "") tag = rel.get("tag_name", "") try: conn.execute(""" INSERT OR IGNORE INTO agent_github_history (agent_name, event_type, event_data, event_at, collected_at) VALUES (?, 'release', ?, ?, datetime('now')) """, (agent_name, json.dumps({"tag": tag, "name": rel.get("name", "")}), published)) rows_inserted += 1 except Exception: pass except Exception: pass # Get contributor count over time (via contributors endpoint) try: r = client.get(f"https://api.github.com/repos/{repo}/contributors", params={"per_page": 1, "anon": "false"}) if r.status_code == 200 and "Link" in r.headers: # Parse last page from Link header to get total contributors link = r.headers["Link"] if 'rel="last"' in link: import re m = re.search(r'page=(\d+)>; rel="last"', link) if m: total = int(m.group(1)) with db() as conn: conn.execute(""" INSERT OR IGNORE INTO agent_github_history (agent_name, event_type, event_data, event_at, collected_at) VALUES (?, 'contributors_snapshot', ?, datetime('now'), datetime('now')) """, (agent_name, json.dumps({"total": total}))) rows_inserted += 1 except Exception: pass # Get weekly commit activity (last year) try: r = client.get(f"https://api.github.com/repos/{repo}/stats/commit_activity") if r.status_code == 200: weeks = r.json() if isinstance(weeks, list): with db() as conn: for week in weeks[-months * 4:]: # last N months of weeks week_ts = week.get("week", 0) week_date = datetime.fromtimestamp(week_ts, tz=timezone.utc).strftime("%Y-%m-%d") try: conn.execute(""" INSERT OR IGNORE INTO agent_github_history (agent_name, event_type, event_data, event_at, collected_at) VALUES (?, 'weekly_commits', ?, ?, datetime('now')) """, (agent_name, json.dumps({"total": week.get("total", 0)}), week_date)) rows_inserted += 1 except Exception: pass except Exception: pass time.sleep(1) # GitHub rate limit: 60/hr unauthenticated, 5000/hr with token logger.info("[backfill-agents] GitHub: inserted %d rows", rows_inserted) return rows_inserted # ═══════════════════════════════════════════════════════════════════════════════ # PyPI Historical Downloads (pypistats.org API — 180 days of daily data) # ═══════════════════════════════════════════════════════════════════════════════ def backfill_pypi_agents(months: int = 3) -> int: """Backfill PyPI download history for agents with pypi packages.""" logger.info("[backfill-agents] PyPI: going back %d months...", months) rows_inserted = 0 with httpx.Client(timeout=30) as client: for agent_name, info in AGENT_REGISTRY.items(): pkg = info.get("pypi") if not pkg: continue try: r = client.get(f"https://pypistats.org/api/packages/{pkg}/overall", params={"mirrors": "false"}) if r.status_code != 200: continue data = r.json() except Exception: continue cutoff = (datetime.now(timezone.utc) - timedelta(days=months * 30)).strftime("%Y-%m-%d") with db() as conn: for entry in data.get("data", []): date = entry.get("date", "") if date < cutoff: continue downloads = entry.get("downloads", 0) try: conn.execute(""" INSERT OR IGNORE INTO agent_pypi_history (agent_name, date, downloads, collected_at) VALUES (?, ?, ?, datetime('now')) """, (agent_name, date, downloads)) rows_inserted += 1 except Exception: pass time.sleep(1) logger.info("[backfill-agents] PyPI: inserted %d rows", rows_inserted) return rows_inserted # ═══════════════════════════════════════════════════════════════════════════════ # arXiv Backfill (papers mentioning agents) # ═══════════════════════════════════════════════════════════════════════════════ def backfill_arxiv_agents(months: int = 6) -> int: """Backfill arXiv papers mentioning agents.""" import arxiv logger.info("[backfill-agents] arXiv: going back %d months...", months) rows_inserted = 0 client = arxiv.Client() # Map agent names to arxiv search terms ARXIV_AGENT_TERMS = { "SWE-bench": ["SWE-agent", "OpenHands", "Devin", "Claude Code"], "code agent": ["Claude Code", "Cursor", "Cline", "Aider", "OpenAI Codex"], "AI coding assistant": ["GitHub Copilot", "Windsurf", "Tabnine", "Continue"], "multi-agent": ["CrewAI", "Microsoft AutoGen", "LangGraph", "MetaGPT"], "browser agent": ["Browser Use", "OpenClaw", "Operator", "Multion"], "LLM agent evaluation": ["SWE-agent", "OpenHands", "Claude Code"], "autonomous agent": ["AutoGPT", "Devin", "Manus", "MetaGPT"], "tool use LLM": ["Claude MCP", "OpenAI Agents SDK", "LlamaIndex"], } for term, agent_names in ARXIV_AGENT_TERMS.items(): try: search = arxiv.Search( query=f'all:"{term}"', max_results=100, sort_by=arxiv.SortCriterion.SubmittedDate, sort_order=arxiv.SortOrder.Descending, ) results = list(client.results(search)) with db() as conn: for paper in results: paper_id = paper.entry_id.split("/")[-1] categories = ",".join(paper.categories) published = paper.published.strftime("%Y-%m-%d %H:%M:%S") if paper.published else None for agent_name in agent_names: try: conn.execute(""" INSERT OR IGNORE INTO arxiv_signals (model_slug, paper_id, title, abstract_preview, categories, authors_count, published_at) VALUES (?, ?, ?, ?, ?, ?, ?) """, (agent_name, paper_id, paper.title, (paper.summary or "")[:500], categories, len(paper.authors), published)) rows_inserted += 1 except Exception: pass except Exception as e: logger.warning("[backfill-agents] arXiv error for '%s': %s", term, str(e)[:100]) time.sleep(3) logger.info("[backfill-agents] arXiv: inserted %d rows", rows_inserted) return rows_inserted # ═══════════════════════════════════════════════════════════════════════════════ # DB table creation for historical data # ═══════════════════════════════════════════════════════════════════════════════ def ensure_history_tables(): """Create tables for historical agent data if they don't exist.""" with db() as conn: conn.execute(""" CREATE TABLE IF NOT EXISTS agent_github_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, agent_name TEXT NOT NULL, event_type TEXT NOT NULL, event_data TEXT, event_at TEXT, collected_at TEXT DEFAULT CURRENT_TIMESTAMP, UNIQUE(agent_name, event_type, event_at) ) """) conn.execute(""" CREATE TABLE IF NOT EXISTS agent_pypi_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, agent_name TEXT NOT NULL, date TEXT NOT NULL, downloads INTEGER DEFAULT 0, collected_at TEXT DEFAULT CURRENT_TIMESTAMP, UNIQUE(agent_name, date) ) """) # ═══════════════════════════════════════════════════════════════════════════════ # Main entry point # ═══════════════════════════════════════════════════════════════════════════════ def run_agent_backfill(sources: list[str] = None, months: int = 3) -> dict: """Run agent-specific backfill operations.""" ensure_history_tables() results = {} if sources is None: sources = ["hn", "so", "github", "pypi", "arxiv"] if "hn" in sources: results["hn"] = backfill_hn_agents(months) if "so" in sources: results["so"] = backfill_stackoverflow_agents(months) if "github" in sources: results["github"] = backfill_github_agents(months) if "pypi" in sources: results["pypi"] = backfill_pypi_agents(months) if "arxiv" in sources: results["arxiv"] = backfill_arxiv_agents(min(months, 6)) return results if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s") parser = argparse.ArgumentParser(description="Agent-specific historical backfill") parser.add_argument("--source", type=str, help="Source to backfill (hn, so, github, pypi, arxiv)") parser.add_argument("--months", type=int, default=3, help="Months to go back (default: 3)") args = parser.parse_args() sources = [args.source] if args.source else None results = run_agent_backfill(sources, args.months) total = sum(results.values()) print(f"\n=== Agent Backfill Results ({total} total rows) ===") for source, rows in results.items(): print(f" {source}: {rows} rows inserted")