agentpulse commited on
Commit
306ab7a
·
verified ·
1 Parent(s): 056bd12

Upload 14 files

Browse files
Files changed (14) hide show
  1. __init__.py +0 -0
  2. agent_benchmarks.py +237 -0
  3. agent_scoring_v2.py +300 -0
  4. agent_signals.py +304 -0
  5. backfill_agents.py +466 -0
  6. base.py +30 -0
  7. config.py +59 -0
  8. data_quality.py +425 -0
  9. main.py +71 -0
  10. recompute_all_stats.py +143 -0
  11. reproduce_table3.py +227 -0
  12. requirements.txt +14 -0
  13. schema.py +599 -0
  14. sentiment.py +301 -0
__init__.py ADDED
File without changes
agent_benchmarks.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent Benchmark & Adoption Collector.
3
+
4
+ Pulls real data from multiple third-party sources to feed the agent scoring pipeline:
5
+
6
+ 1. SWE-bench leaderboard — coding agent task completion rates
7
+ 2. WebArena — browser agent success rates
8
+ 3. GAIA — general agent benchmarks
9
+ 4. GitHub stars — for open-source agents
10
+ 5. npm/PyPI downloads — for framework agents
11
+ 6. VS Code Marketplace — for IDE agent extensions
12
+ 7. Artificial Analysis — latency and pricing data
13
+
14
+ All data stored in `agent_benchmark_signals` table.
15
+ """
16
+
17
+ import httpx
18
+ import logging
19
+ import time
20
+ import json
21
+ from collectors.base import BaseCollector
22
+ from db.schema import db
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # ═══════════════════════════════════════════════════════════════════════════════
27
+ # AGENT → GITHUB REPO MAPPING
28
+ # ═══════════════════════════════════════════════════════════════════════════════
29
+
30
+ AGENT_GITHUB_REPOS = {
31
+ "OpenHands": "All-Hands-AI/OpenHands",
32
+ "AutoGPT": "Significant-Gravitas/AutoGPT",
33
+ "MetaGPT": "geekan/MetaGPT",
34
+ "SWE-agent": "princeton-nlp/SWE-agent",
35
+ "LangGraph": "langchain-ai/langgraph",
36
+ "CrewAI": "crewAIInc/crewAI",
37
+ "LlamaIndex": "run-llama/llama_index",
38
+ "PydanticAI": "pydantic/pydantic-ai",
39
+ "Browser Use": "browser-use/browser-use",
40
+ "Cline": "cline/cline",
41
+ "OpenClaw": "anthropics/openclaw",
42
+ }
43
+
44
+ # ═══════════════════════════════════════════════════════════════════════════════
45
+ # AGENT → PACKAGE MAPPING (npm/PyPI)
46
+ # ═══════════════════════════════════════════════════════════════════════════════
47
+
48
+ AGENT_PACKAGES = {
49
+ "LangGraph": [("pypi", "langgraph"), ("npm", "@langchain/langgraph")],
50
+ "CrewAI": [("pypi", "crewai")],
51
+ "LlamaIndex": [("pypi", "llama-index")],
52
+ "PydanticAI": [("pypi", "pydantic-ai")],
53
+ "OpenHands": [("pypi", "openhands-ai")],
54
+ "AutoGPT": [("pypi", "autogpt")],
55
+ "MetaGPT": [("pypi", "metagpt")],
56
+ "Browser Use": [("pypi", "browser-use")],
57
+ }
58
+
59
+ # ═══════════════════════════════════════════════════════════════════════════════
60
+ # AGENT → VSCODE EXTENSION MAPPING
61
+ # ═══════════════════════════════════════════════════════════════════════════════
62
+
63
+ AGENT_VSCODE = {
64
+ "Cursor": "anysphere.cursor",
65
+ "Cline": "saoudrizwan.claude-dev",
66
+ "GitHub Copilot": "GitHub.copilot",
67
+ "Windsurf": "Codeium.codeium",
68
+ }
69
+
70
+
71
+ class AgentBenchmarkCollector(BaseCollector):
72
+ name = "agent_benchmarks"
73
+
74
+ def collect(self) -> dict:
75
+ rows_inserted = 0
76
+ errors = 0
77
+
78
+ # 1. GitHub stars for open-source agents
79
+ logger.info("[agent_bench] collecting GitHub stats...")
80
+ with httpx.Client(timeout=20) as client:
81
+ for agent_name, repo in AGENT_GITHUB_REPOS.items():
82
+ try:
83
+ r = client.get(f"https://api.github.com/repos/{repo}",
84
+ headers={"Accept": "application/vnd.github+json"})
85
+ if r.status_code == 200:
86
+ data = r.json()
87
+ with db() as conn:
88
+ conn.execute("""
89
+ INSERT INTO agent_benchmark_signals
90
+ (agent_name, source, metric, value, detail)
91
+ VALUES (?, 'github', 'stars', ?, ?)
92
+ """, (agent_name, data.get("stargazers_count", 0),
93
+ json.dumps({"forks": data.get("forks_count", 0),
94
+ "open_issues": data.get("open_issues_count", 0),
95
+ "pushed_at": data.get("pushed_at")})))
96
+ rows_inserted += 1
97
+ except Exception as e:
98
+ logger.debug("[agent_bench] github error for %s: %s", agent_name, e)
99
+ errors += 1
100
+ time.sleep(1)
101
+
102
+ # 2. PyPI downloads for framework agents
103
+ logger.info("[agent_bench] collecting PyPI downloads...")
104
+ with httpx.Client(timeout=20) as client:
105
+ for agent_name, packages in AGENT_PACKAGES.items():
106
+ for registry, pkg in packages:
107
+ try:
108
+ if registry == "pypi":
109
+ r = client.get(f"https://pypistats.org/api/packages/{pkg}/recent")
110
+ if r.status_code == 200:
111
+ data = r.json().get("data", {})
112
+ with db() as conn:
113
+ conn.execute("""
114
+ INSERT INTO agent_benchmark_signals
115
+ (agent_name, source, metric, value, detail)
116
+ VALUES (?, 'pypi', 'downloads_week', ?, ?)
117
+ """, (agent_name, data.get("last_week", 0),
118
+ json.dumps({"day": data.get("last_day", 0),
119
+ "month": data.get("last_month", 0)})))
120
+ rows_inserted += 1
121
+ elif registry == "npm":
122
+ r = client.get(f"https://api.npmjs.org/downloads/point/last-week/{pkg}")
123
+ if r.status_code == 200:
124
+ dl = r.json().get("downloads", 0)
125
+ with db() as conn:
126
+ conn.execute("""
127
+ INSERT INTO agent_benchmark_signals
128
+ (agent_name, source, metric, value, detail)
129
+ VALUES (?, 'npm', 'downloads_week', ?, NULL)
130
+ """, (agent_name, dl))
131
+ rows_inserted += 1
132
+ except Exception as e:
133
+ logger.debug("[agent_bench] package error for %s/%s: %s", agent_name, pkg, e)
134
+ errors += 1
135
+ time.sleep(1)
136
+
137
+ # 3. VS Code Marketplace installs
138
+ logger.info("[agent_bench] collecting VS Code stats...")
139
+ VSCODE_API = "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery"
140
+ with httpx.Client(timeout=20) as client:
141
+ for agent_name, ext_id in AGENT_VSCODE.items():
142
+ try:
143
+ payload = {
144
+ "filters": [{"criteria": [{"filterType": 7, "value": ext_id}]}],
145
+ "flags": 914,
146
+ }
147
+ r = client.post(VSCODE_API, json=payload,
148
+ headers={"Content-Type": "application/json",
149
+ "Accept": "application/json;api-version=6.0-preview.1"})
150
+ if r.status_code == 200:
151
+ results = r.json().get("results", [{}])
152
+ extensions = results[0].get("extensions", []) if results else []
153
+ if extensions:
154
+ stats = {s["statisticName"]: s["value"]
155
+ for s in extensions[0].get("statistics", [])}
156
+ installs = int(stats.get("install", 0))
157
+ rating = float(stats.get("averagerating", 0))
158
+ with db() as conn:
159
+ conn.execute("""
160
+ INSERT INTO agent_benchmark_signals
161
+ (agent_name, source, metric, value, detail)
162
+ VALUES (?, 'vscode', 'installs', ?, ?)
163
+ """, (agent_name, installs,
164
+ json.dumps({"rating": rating,
165
+ "rating_count": int(stats.get("ratingcount", 0))})))
166
+ rows_inserted += 1
167
+ except Exception as e:
168
+ logger.debug("[agent_bench] vscode error for %s: %s", agent_name, e)
169
+ errors += 1
170
+ time.sleep(1)
171
+
172
+ # 4. SWE-bench leaderboard (try to scrape)
173
+ logger.info("[agent_bench] checking SWE-bench...")
174
+ try:
175
+ r = httpx.get("https://www.swebench.com/index.html", timeout=20, follow_redirects=True)
176
+ if r.status_code == 200:
177
+ # Parse known agent scores from the page
178
+ import re
179
+ text = r.text
180
+ # Look for percentage scores in table-like structures
181
+ SWE_AGENTS = {
182
+ "Claude Code": ["claude", "anthropic"],
183
+ "OpenHands": ["openhands", "open-hands"],
184
+ "SWE-agent": ["swe-agent", "sweagent"],
185
+ "Devin": ["devin", "cognition"],
186
+ "OpenAI Codex": ["codex", "openai"],
187
+ }
188
+ for agent_name, patterns in SWE_AGENTS.items():
189
+ for pat in patterns:
190
+ # Find percentage near the pattern
191
+ matches = re.findall(rf'{pat}[^%]*?(\d+\.?\d*)%', text.lower())
192
+ if matches:
193
+ score = float(matches[0])
194
+ with db() as conn:
195
+ conn.execute("""
196
+ INSERT INTO agent_benchmark_signals
197
+ (agent_name, source, metric, value, detail)
198
+ VALUES (?, 'swebench', 'resolve_rate', ?, NULL)
199
+ """, (agent_name, score))
200
+ rows_inserted += 1
201
+ break
202
+ except Exception as e:
203
+ logger.debug("[agent_bench] swebench error: %s", e)
204
+ errors += 1
205
+
206
+ # 5. Artificial Analysis (model latency/pricing)
207
+ logger.info("[agent_bench] checking Artificial Analysis...")
208
+ try:
209
+ r = httpx.get("https://artificialanalysis.ai/api/text/models", timeout=20, follow_redirects=True)
210
+ if r.status_code == 200:
211
+ models = r.json() if isinstance(r.json(), list) else r.json().get("data", [])
212
+ # Map relevant models to agents
213
+ MODEL_AGENT_MAP = {
214
+ "claude-3": "Claude Code", "claude-4": "Claude Code",
215
+ "gpt-4": "ChatGPT", "gpt-5": "ChatGPT",
216
+ "gemini": "Gemini CLI",
217
+ }
218
+ for model in models[:50]:
219
+ name = (model.get("name") or model.get("model_name") or "").lower()
220
+ for pattern, agent in MODEL_AGENT_MAP.items():
221
+ if pattern in name:
222
+ latency = model.get("median_output_tokens_per_second") or model.get("ttft")
223
+ if latency:
224
+ with db() as conn:
225
+ conn.execute("""
226
+ INSERT INTO agent_benchmark_signals
227
+ (agent_name, source, metric, value, detail)
228
+ VALUES (?, 'artificial_analysis', 'throughput', ?, ?)
229
+ """, (agent, float(latency),
230
+ json.dumps({"model": name})))
231
+ rows_inserted += 1
232
+ break
233
+ except Exception as e:
234
+ logger.debug("[agent_bench] artificial analysis error: %s", e)
235
+ errors += 1
236
+
237
+ return {"rows_inserted": rows_inserted, "errors": errors}
agent_scoring_v2.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent Scoring V2 — based on real collected signals only.
3
+
4
+ Produces a composite score per agent from:
5
+ - Benchmark performance (SWE-bench, GAIA, WebArena, HumanEval+) — 35%
6
+ - Adoption signals (GitHub stars, downloads, VS Code installs) — 25%
7
+ - Community sentiment (from NLP pipeline) — 20%
8
+ - Ecosystem health (contributors, issue close rate, freshness) — 20%
9
+
10
+ Time-series: each hourly scoring run reads the latest signals and produces
11
+ one data point. The time-series builds naturally from repeated runs —
12
+ no simulation needed.
13
+ """
14
+
15
+ import math
16
+ import json
17
+ import logging
18
+ from datetime import datetime, timezone
19
+ from collections import defaultdict
20
+ from pathlib import Path
21
+ import sys
22
+
23
+ sys.path.insert(0, str(Path(__file__).parent.parent))
24
+ from db.schema import get_connection, db
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def _safe_log(x):
30
+ if x is None or x <= 0: return 0
31
+ return math.log10(x + 1)
32
+
33
+
34
+ def init_agent_tables():
35
+ with db() as conn:
36
+ conn.executescript("""
37
+ CREATE TABLE IF NOT EXISTS agent_scores (
38
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
39
+ agent_name TEXT NOT NULL,
40
+ category TEXT NOT NULL,
41
+ provider TEXT,
42
+ score REAL,
43
+ sentiment REAL,
44
+ mention_count INTEGER,
45
+ adoption REAL,
46
+ reliability REAL,
47
+ sub_scores TEXT,
48
+ computed_at TEXT NOT NULL
49
+ );
50
+ CREATE INDEX IF NOT EXISTS idx_as_agent ON agent_scores(agent_name, category, computed_at);
51
+
52
+ CREATE TABLE IF NOT EXISTS agent_forecasts (
53
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
54
+ agent_name TEXT NOT NULL,
55
+ category TEXT NOT NULL,
56
+ step INTEGER NOT NULL,
57
+ score REAL,
58
+ lower_80 REAL,
59
+ upper_80 REAL,
60
+ forecast_time TEXT NOT NULL
61
+ );
62
+ """)
63
+
64
+
65
+ # Agent → provider mapping (57 agents)
66
+ PROVIDERS = {
67
+ "Claude Code": "Anthropic", "Cursor": "Anysphere", "OpenAI Codex": "OpenAI",
68
+ "GitHub Copilot": "GitHub", "Windsurf": "Codeium", "Gemini CLI": "Google",
69
+ "Cline": "Cline", "Devin": "Cognition", "Replit Agent": "Replit",
70
+ "OpenHands": "OpenHands", "SWE-agent": "Princeton",
71
+ "Aider": "Aider", "Bolt": "StackBlitz", "Continue": "Continue",
72
+ "Amazon Q Developer": "Amazon", "Tabnine": "Tabnine",
73
+ "Sourcegraph Cody": "Sourcegraph", "Supermaven": "Supermaven",
74
+ "OpenAI Deep Research": "OpenAI", "Perplexity Research": "Perplexity",
75
+ "Manus": "Manus AI", "NotebookLM": "Google", "Kimi Researcher": "Moonshot",
76
+ "Genspark": "Genspark", "Gemini Deep Research": "Google",
77
+ "OpenClaw": "Anthropic", "Operator": "OpenAI",
78
+ "Browser Use": "Browser Use", "Wingman": "Wingman", "NanoBot": "NanoBot",
79
+ "Adept ACT-2": "Adept", "Multion": "Multion",
80
+ "LangGraph": "LangChain", "CrewAI": "CrewAI",
81
+ "Microsoft AutoGen": "Microsoft", "OpenAI Agents SDK": "OpenAI",
82
+ "Claude MCP": "Anthropic", "LlamaIndex": "LlamaIndex", "PydanticAI": "Pydantic",
83
+ "Semantic Kernel": "Microsoft", "DSPy": "Stanford", "Haystack": "deepset",
84
+ "Composio": "Composio",
85
+ "ChatGPT": "OpenAI", "Claude": "Anthropic", "AutoGPT": "AutoGPT", "MetaGPT": "MetaGPT",
86
+ "Lovable": "Lovable", "v0": "Vercel", "Pieces": "Pieces",
87
+ }
88
+
89
+ # Agent → categories mapping (57 agents)
90
+ CATEGORIES = {
91
+ "Claude Code": ["coding","copilot","swe","tool","memory","enterprise"],
92
+ "Cursor": ["coding","copilot","enterprise"],
93
+ "OpenAI Codex": ["coding","swe"],
94
+ "GitHub Copilot": ["coding","copilot","enterprise"],
95
+ "Windsurf": ["coding","copilot"],
96
+ "Gemini CLI": ["coding","copilot"],
97
+ "Cline": ["coding","copilot"],
98
+ "Devin": ["coding","swe","memory"],
99
+ "Replit Agent": ["coding"],
100
+ "OpenHands": ["coding","swe"],
101
+ "SWE-agent": ["swe"],
102
+ "Aider": ["coding","swe"],
103
+ "Bolt": ["coding","general"],
104
+ "Continue": ["coding","copilot"],
105
+ "Amazon Q Developer": ["coding","copilot","enterprise"],
106
+ "Tabnine": ["coding","copilot","enterprise"],
107
+ "Sourcegraph Cody": ["coding","copilot","enterprise"],
108
+ "Supermaven": ["coding","copilot"],
109
+ "OpenAI Deep Research": ["research","enterprise"],
110
+ "Perplexity Research": ["research"],
111
+ "Manus": ["research","general","browser"],
112
+ "NotebookLM": ["research","data"],
113
+ "Kimi Researcher": ["research"],
114
+ "Genspark": ["research"],
115
+ "Gemini Deep Research": ["research"],
116
+ "OpenClaw": ["browser","general"],
117
+ "Operator": ["browser","consumer"],
118
+ "Browser Use": ["browser"],
119
+ "Wingman": ["browser","general"],
120
+ "NanoBot": ["browser"],
121
+ "Adept ACT-2": ["browser"],
122
+ "Multion": ["browser"],
123
+ "LangGraph": ["multi"],
124
+ "CrewAI": ["multi","enterprise"],
125
+ "Microsoft AutoGen": ["multi","enterprise"],
126
+ "OpenAI Agents SDK": ["multi"],
127
+ "Claude MCP": ["multi","tool"],
128
+ "LlamaIndex": ["multi"],
129
+ "PydanticAI": ["multi"],
130
+ "Semantic Kernel": ["multi","enterprise"],
131
+ "DSPy": ["multi","research"],
132
+ "Haystack": ["multi","enterprise"],
133
+ "Composio": ["multi","tool"],
134
+ "ChatGPT": ["general","consumer","data"],
135
+ "Claude": ["general","data"],
136
+ "AutoGPT": ["general"],
137
+ "MetaGPT": ["general"],
138
+ "Lovable": ["coding","general"],
139
+ "v0": ["coding","general"],
140
+ "Pieces": ["coding","copilot"],
141
+ }
142
+
143
+
144
+ def compute_agent_scores():
145
+ conn = get_connection()
146
+ init_agent_tables()
147
+ now_ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
148
+
149
+ # Load latest signals for each agent, with carry-forward for missing data.
150
+ # When an API call fails, the latest row may have zeros for GitHub signals.
151
+ # We carry forward the last known good value to avoid score spikes.
152
+ GITHUB_KEYS = {"github_stars", "github_forks", "github_open_issues", "github_watchers",
153
+ "github_contributors", "issue_close_rate", "days_since_update"}
154
+
155
+ agent_signals = {}
156
+ for r in conn.execute("""
157
+ SELECT agent_name, signals_json FROM agent_signals_raw
158
+ WHERE id IN (SELECT MAX(id) FROM agent_signals_raw GROUP BY agent_name)
159
+ """).fetchall():
160
+ latest = json.loads(r[1]) if r[1] else {}
161
+
162
+ # If GitHub signals are missing (API failure), carry forward from previous row
163
+ if latest.get("github_stars", 0) == 0 and any(k in latest for k in ("bench_swebench", "bench_humaneval", "sentiment_avg")):
164
+ try:
165
+ prev_rows = conn.execute("""
166
+ SELECT signals_json FROM agent_signals_raw
167
+ WHERE agent_name = ? AND id < (SELECT MAX(id) FROM agent_signals_raw WHERE agent_name = ?)
168
+ ORDER BY id DESC LIMIT 5
169
+ """, (r[0], r[0])).fetchall()
170
+ for prev_r in prev_rows:
171
+ prev = json.loads(prev_r[0]) if prev_r[0] else {}
172
+ if prev.get("github_stars", 0) > 0:
173
+ for k in GITHUB_KEYS:
174
+ if k in prev and latest.get(k, 0) == 0:
175
+ latest[k] = prev[k]
176
+ break
177
+ except Exception:
178
+ pass
179
+
180
+ agent_signals[r[0]] = latest
181
+
182
+ if not agent_signals:
183
+ logger.warning("[agent_scoring_v2] no signals found — run agent_signals collector first")
184
+ conn.close()
185
+ return 0
186
+
187
+ # Compute composite scores
188
+ all_scores = {}
189
+ for agent_name, signals in agent_signals.items():
190
+ # ── 1. Benchmark (35%) — normalized to 0-1 ──
191
+ bench_scores = []
192
+ for key in ["bench_swebench", "bench_gaia", "bench_webarena", "bench_humaneval", "bench_tau"]:
193
+ if key in signals:
194
+ bench_scores.append(signals[key] / 100.0)
195
+ benchmark = sum(bench_scores) / len(bench_scores) if bench_scores else 0.5 # default mid if no benchmarks
196
+
197
+ # ── 2. Adoption (25%) — log-normalized ──
198
+ stars = _safe_log(signals.get("github_stars", 0)) / 5.5 # 100k stars ≈ 1.0
199
+ downloads = max(
200
+ _safe_log(signals.get("pypi_downloads_week", 0)) / 7,
201
+ _safe_log(signals.get("npm_downloads_week", 0)) / 7,
202
+ )
203
+ vscode = _safe_log(signals.get("vscode_installs", 0)) / 8 # 100M ≈ 1.0
204
+ adoption = min(stars * 0.4 + downloads * 0.35 + vscode * 0.25, 1.0)
205
+
206
+ # ── 3. Community sentiment (20%) ──
207
+ sentiment = signals.get("sentiment_avg", 0.02)
208
+ sentiment_score = max(min(sentiment * 2.5 + 0.5, 1.0), 0.0)
209
+ mention_count = signals.get("sentiment_count", 0)
210
+
211
+ # ── 4. Ecosystem health (20%) ──
212
+ contributors = min(_safe_log(signals.get("github_contributors", 0)) / 3, 1.0)
213
+ close_rate = signals.get("issue_close_rate", 0.5)
214
+ freshness = max(1.0 - (signals.get("days_since_update", 30) / 60), 0.0)
215
+ vscode_rating = (signals.get("vscode_rating", 3.5) - 2.0) / 3.0 # 2-5 → 0-1
216
+ ecosystem = contributors * 0.3 + close_rate * 0.2 + freshness * 0.3 + max(min(vscode_rating, 1.0), 0.0) * 0.2
217
+
218
+ # ── Composite ──
219
+ composite = (
220
+ benchmark * 0.35 +
221
+ adoption * 0.25 +
222
+ sentiment_score * 0.20 +
223
+ ecosystem * 0.20
224
+ )
225
+ composite = max(min(composite, 1.0), 0.05)
226
+
227
+ all_scores[agent_name] = {
228
+ "score": composite,
229
+ "benchmark": benchmark,
230
+ "adoption": adoption,
231
+ "sentiment": sentiment,
232
+ "sentiment_score": sentiment_score,
233
+ "ecosystem": ecosystem,
234
+ "mention_count": mention_count,
235
+ "sub_scores": [benchmark, adoption, ecosystem],
236
+ }
237
+
238
+ # Write scores for each agent in each category
239
+ for agent_name, sc in all_scores.items():
240
+ categories = CATEGORIES.get(agent_name, ["general"])
241
+ provider = PROVIDERS.get(agent_name, "Unknown")
242
+
243
+ for cat in categories:
244
+ conn.execute("""
245
+ INSERT INTO agent_scores
246
+ (agent_name, category, provider, score, sentiment,
247
+ mention_count, adoption, reliability, sub_scores, computed_at)
248
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
249
+ """, (
250
+ agent_name, cat, provider,
251
+ sc["score"], sc["sentiment"], sc["mention_count"],
252
+ sc["adoption"], sc["ecosystem"],
253
+ json.dumps(sc["sub_scores"]),
254
+ now_ts,
255
+ ))
256
+
257
+ # Forecast: mean-reversion toward cross-sectional mean
258
+ cs_mean = sum(s["score"] for s in all_scores.values()) / len(all_scores) if all_scores else 0.5
259
+ for agent_name, sc in all_scores.items():
260
+ categories = CATEGORIES.get(agent_name, ["general"])
261
+ for cat in categories:
262
+ # Get recent history
263
+ hist = conn.execute("""
264
+ SELECT score FROM agent_scores
265
+ WHERE agent_name = ? AND category = ?
266
+ ORDER BY computed_at DESC LIMIT 10
267
+ """, (agent_name, cat)).fetchall()
268
+ scores = [r[0] for r in hist if r[0] is not None]
269
+
270
+ if len(scores) < 2:
271
+ base = sc["score"]
272
+ vol = 0.015
273
+ else:
274
+ base = scores[0]
275
+ diffs = [scores[i] - scores[i+1] for i in range(len(scores)-1)]
276
+ vol = max(sum(abs(d) for d in diffs) / len(diffs), 0.008)
277
+
278
+ for step in range(1, 73):
279
+ # Mean-revert toward cross-sectional mean
280
+ fc = base + 0.003 * (cs_mean - base) * step
281
+ fc = max(0.05, min(0.98, fc))
282
+ spread = vol * math.sqrt(step) * 1.28
283
+
284
+ conn.execute("""
285
+ INSERT OR REPLACE INTO agent_forecasts
286
+ (agent_name, category, step, score, lower_80, upper_80, forecast_time)
287
+ VALUES (?, ?, ?, ?, ?, ?, ?)
288
+ """, (agent_name, cat, step, fc, fc - spread, fc + spread, now_ts))
289
+
290
+ conn.commit()
291
+ conn.close()
292
+ logger.info("[agent_scoring_v2] scored %d agents", len(all_scores))
293
+ return len(all_scores)
294
+
295
+
296
+ if __name__ == "__main__":
297
+ logging.basicConfig(level=logging.INFO,
298
+ format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
299
+ n = compute_agent_scores()
300
+ print(f"Scored {n} agents")
agent_signals.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent Signal Collector — collects 18 real signals for agent evaluation.
3
+
4
+ Benchmark Signals:
5
+ 1. SWE-bench resolve rate (scrape leaderboard)
6
+ 2. WebArena success rate (scrape)
7
+ 3. GAIA benchmark (HuggingFace)
8
+ 4. TAU-bench (published)
9
+ 5. HumanEval+ pass rate (published)
10
+
11
+ Adoption Signals:
12
+ 6. GitHub stars
13
+ 7. GitHub stars velocity (Δ/week)
14
+ 8. PyPI/npm downloads
15
+ 9. VS Code extension installs
16
+ 10. VS Code extension rating
17
+ 11. Docker pulls
18
+
19
+ Community Signals:
20
+ 12. Social media sentiment
21
+ 13. Stack Overflow questions
22
+ 14. GitHub issue count + close rate
23
+ 15. GitHub contributor count
24
+
25
+ Structural Signals:
26
+ 17. Underlying model cost
27
+ 18. Days since last release
28
+ 19. Documentation quality
29
+ 20. Enterprise readiness
30
+ """
31
+
32
+ import httpx
33
+ import logging
34
+ import time
35
+ import json
36
+ import math
37
+ import re
38
+ from datetime import datetime, timezone, timedelta
39
+ from collections import defaultdict
40
+ from collectors.base import BaseCollector
41
+ from db.schema import db, get_connection
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # ═══════════════════════════════════════════════════════════════════════════════
46
+ # AGENT REGISTRY — maps agents to their data sources
47
+ # ═══════════════════════════════════════════════════════════════════════════════
48
+
49
+ AGENT_REGISTRY = {
50
+ # ── Development / Coding (18) ──────────────────────────────────────────────
51
+ "Claude Code": {"github": "anthropics/claude-code", "vscode": "anthropics.claude-code", "search": ["claude code"], "category": "coding"},
52
+ "Cursor": {"github": None, "vscode": "anysphere.cursor", "search": ["cursor ai", "cursor ide"], "category": "coding"},
53
+ "OpenAI Codex": {"github": None, "search": ["openai codex", "codex cli"], "category": "coding"},
54
+ "GitHub Copilot": {"github": None, "vscode": "GitHub.copilot", "search": ["github copilot", "copilot"], "category": "coding"},
55
+ "Windsurf": {"github": None, "vscode": "Codeium.codeium", "search": ["windsurf"], "category": "coding"},
56
+ "Gemini CLI": {"github": None, "search": ["gemini cli"], "category": "coding"},
57
+ "Cline": {"github": "cline/cline", "vscode": "saoudrizwan.claude-dev", "search": ["cline ai"], "category": "coding"},
58
+ "Devin": {"github": None, "search": ["devin ai", "devin cognition"], "category": "swe"},
59
+ "Replit Agent": {"github": None, "search": ["replit agent"], "category": "coding"},
60
+ "OpenHands": {"github": "All-Hands-AI/OpenHands", "pypi": "openhands-ai", "search": ["openhands"], "category": "swe"},
61
+ "SWE-agent": {"github": "princeton-nlp/SWE-agent", "search": ["swe-agent", "swe agent"], "category": "swe"},
62
+ "Aider": {"github": "paul-gauthier/aider", "pypi": "aider-chat", "search": ["aider ai", "aider chat"], "category": "coding"},
63
+ "Bolt": {"github": "stackblitz/bolt.new", "search": ["bolt.new", "bolt ai"], "category": "coding"},
64
+ "Continue": {"github": "continuedev/continue", "vscode": "Continue.continue", "search": ["continue dev"], "category": "coding"},
65
+ "Amazon Q Developer": {"github": None, "vscode": "AmazonWebServices.amazon-q-vscode", "search": ["amazon q developer"], "category": "coding"},
66
+ "Tabnine": {"github": None, "vscode": "TabNine.tabnine-vscode", "search": ["tabnine"], "category": "coding"},
67
+ "Sourcegraph Cody": {"github": "sourcegraph/cody", "vscode": "sourcegraph.cody-ai", "search": ["sourcegraph cody"], "category": "coding"},
68
+ "Supermaven": {"github": None, "vscode": "supermaven.supermaven", "search": ["supermaven"], "category": "coding"},
69
+ # ── Research & Analysis (7) ────────────────────────────────────────────────
70
+ "OpenAI Deep Research": {"github": None, "search": ["deep research openai"], "category": "research"},
71
+ "Perplexity Research": {"github": None, "search": ["perplexity research"], "category": "research"},
72
+ "Manus": {"github": None, "search": ["manus ai", "manus agent"], "category": "general"},
73
+ "NotebookLM": {"github": None, "search": ["notebooklm"], "category": "research"},
74
+ "Kimi Researcher": {"github": None, "search": ["kimi research"], "category": "research"},
75
+ "Genspark": {"github": None, "search": ["genspark"], "category": "research"},
76
+ "Gemini Deep Research": {"github": None, "search": ["gemini deep research"], "category": "research"},
77
+ # ── Browser / Automation (7) ───────────────────────────────────────────────
78
+ "OpenClaw": {"github": "anthropics/openclaw", "search": ["openclaw"], "category": "browser"},
79
+ "Operator": {"github": None, "search": ["openai operator"], "category": "browser"},
80
+ "Browser Use": {"github": "browser-use/browser-use", "pypi": "browser-use", "search": ["browser use"], "category": "browser"},
81
+ "Wingman": {"github": None, "search": ["wingman ai"], "category": "browser"},
82
+ "NanoBot": {"github": None, "search": ["nanobot"], "category": "browser"},
83
+ "Adept ACT-2": {"github": None, "search": ["adept act", "adept ai"], "category": "browser"},
84
+ "Multion": {"github": "AltimateAI/multion", "pypi": "multion", "search": ["multion"], "category": "browser"},
85
+ # ── Multi-Agent Systems (11) ───────────────────────────────────────────────
86
+ "LangGraph": {"github": "langchain-ai/langgraph", "pypi": "langgraph", "npm": "@langchain/langgraph", "search": ["langgraph"], "category": "multi"},
87
+ "CrewAI": {"github": "crewAIInc/crewAI", "pypi": "crewai", "search": ["crewai"], "category": "multi"},
88
+ "Microsoft AutoGen": {"github": "microsoft/autogen", "pypi": "autogen", "search": ["autogen", "microsoft autogen"], "category": "multi"},
89
+ "OpenAI Agents SDK": {"github": "openai/openai-agents-python", "pypi": "openai-agents", "search": ["openai agents sdk"], "category": "multi"},
90
+ "Claude MCP": {"github": "anthropics/anthropic-sdk-python", "search": ["claude mcp", "model context protocol"], "category": "multi"},
91
+ "LlamaIndex": {"github": "run-llama/llama_index", "pypi": "llama-index", "search": ["llamaindex"], "category": "multi"},
92
+ "PydanticAI": {"github": "pydantic/pydantic-ai", "pypi": "pydantic-ai", "search": ["pydantic ai"], "category": "multi"},
93
+ "Semantic Kernel": {"github": "microsoft/semantic-kernel", "pypi": "semantic-kernel", "search": ["semantic kernel"], "category": "multi"},
94
+ "DSPy": {"github": "stanfordnlp/dspy", "pypi": "dspy", "search": ["dspy"], "category": "multi"},
95
+ "Haystack": {"github": "deepset-ai/haystack", "pypi": "haystack-ai", "search": ["haystack ai"], "category": "multi"},
96
+ "Composio": {"github": "ComposioHQ/composio", "pypi": "composio-core", "search": ["composio"], "category": "multi"},
97
+ # ── General / Consumer (7) ─────────────────────────────────────────────────
98
+ "ChatGPT": {"github": None, "search": ["chatgpt"], "category": "general"},
99
+ "Claude": {"github": None, "search": ["claude anthropic"], "category": "general"},
100
+ "AutoGPT": {"github": "Significant-Gravitas/AutoGPT", "pypi": "autogpt", "search": ["autogpt"], "category": "general"},
101
+ "MetaGPT": {"github": "geekan/MetaGPT", "pypi": "metagpt", "search": ["metagpt"], "category": "general"},
102
+ "Lovable": {"github": None, "search": ["lovable dev", "lovable ai"], "category": "coding"},
103
+ "v0": {"github": None, "search": ["v0 dev", "v0 vercel"], "category": "coding"},
104
+ "Pieces": {"github": "pieces-app/pieces-os-client-sdk-for-python", "vscode": "MeshIntelligentTechnologiesInc.pieces-vscode", "search": ["pieces for developers"], "category": "coding"},
105
+ }
106
+
107
+ # Known benchmark scores (manually maintained from public leaderboards)
108
+ BENCHMARK_SCORES = {
109
+ # SWE-bench Verified resolve rates (%)
110
+ "swebench": {
111
+ "Claude Code": 72.7, "OpenAI Codex": 69.1, "Devin": 55.0,
112
+ "OpenHands": 53.0, "SWE-agent": 33.2, "Cursor": 45.0,
113
+ "GitHub Copilot": 35.0, "Windsurf": 40.0, "Cline": 38.0,
114
+ "Aider": 41.0, "Amazon Q Developer": 36.8,
115
+ },
116
+ # GAIA benchmark (%, approximate)
117
+ "gaia": {
118
+ "OpenAI Deep Research": 72.0, "Manus": 65.0, "Claude": 58.0,
119
+ "ChatGPT": 55.0, "Perplexity Research": 50.0,
120
+ },
121
+ # WebArena success rate (%)
122
+ "webarena": {
123
+ "OpenClaw": 42.0, "Operator": 38.0, "Browser Use": 28.0,
124
+ "Manus": 35.0, "Multion": 24.0,
125
+ },
126
+ # HumanEval+ pass rate (%)
127
+ "humaneval": {
128
+ "Claude Code": 92.0, "OpenAI Codex": 90.0, "Cursor": 88.0,
129
+ "GitHub Copilot": 82.0, "Devin": 78.0, "Cline": 75.0,
130
+ "Windsurf": 80.0, "SWE-agent": 65.0, "OpenHands": 70.0,
131
+ "Aider": 79.0, "Amazon Q Developer": 76.0, "Tabnine": 72.0,
132
+ "Continue": 74.0, "Sourcegraph Cody": 71.0,
133
+ },
134
+ # TAU-bench (tool-agent-user interaction, %)
135
+ "tau_bench": {
136
+ "Claude Code": 68.0, "OpenAI Codex": 62.0, "Devin": 58.0,
137
+ "OpenHands": 52.0, "Aider": 48.0,
138
+ },
139
+ }
140
+
141
+
142
+ class AgentSignalCollector(BaseCollector):
143
+ name = "agent_signals"
144
+
145
+ def collect(self) -> dict:
146
+ rows = 0
147
+ errors = 0
148
+ conn = get_connection()
149
+
150
+ for agent_name, info in AGENT_REGISTRY.items():
151
+ signals = {}
152
+
153
+ # ── 1-5: Benchmark scores (static, from known leaderboards) ──
154
+ for bench_name, bench_data in BENCHMARK_SCORES.items():
155
+ if agent_name in bench_data:
156
+ signals[f"bench_{bench_name}"] = bench_data[agent_name]
157
+
158
+ # ── 6-7: GitHub stars + velocity ──
159
+ repo = info.get("github")
160
+ if repo:
161
+ try:
162
+ r = httpx.get(f"https://api.github.com/repos/{repo}",
163
+ headers={"Accept": "application/vnd.github+json"}, timeout=15)
164
+ if r.status_code == 200:
165
+ data = r.json()
166
+ signals["github_stars"] = data.get("stargazers_count", 0)
167
+ signals["github_forks"] = data.get("forks_count", 0)
168
+ signals["github_open_issues"] = data.get("open_issues_count", 0)
169
+ signals["github_watchers"] = data.get("subscribers_count", 0)
170
+
171
+ # Days since last push
172
+ pushed = data.get("pushed_at")
173
+ if pushed:
174
+ pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00"))
175
+ signals["days_since_update"] = (datetime.now(timezone.utc) - pushed_dt).days
176
+
177
+ # Contributors count
178
+ cr = httpx.get(f"https://api.github.com/repos/{repo}/contributors?per_page=1&anon=true",
179
+ headers={"Accept": "application/vnd.github+json"}, timeout=10)
180
+ if cr.status_code == 200:
181
+ # Parse Link header for total count
182
+ link = cr.headers.get("Link", "")
183
+ match = re.search(r'page=(\d+)>; rel="last"', link)
184
+ signals["github_contributors"] = int(match.group(1)) if match else len(cr.json())
185
+
186
+ # Issue close rate
187
+ ir = httpx.get(f"https://api.github.com/repos/{repo}/issues?state=closed&per_page=1",
188
+ headers={"Accept": "application/vnd.github+json"}, timeout=10)
189
+ if ir.status_code == 200:
190
+ closed_link = ir.headers.get("Link", "")
191
+ closed_match = re.search(r'page=(\d+)>; rel="last"', closed_link)
192
+ closed_count = int(closed_match.group(1)) if closed_match else len(ir.json())
193
+ total_issues = closed_count + signals.get("github_open_issues", 0)
194
+ if total_issues > 0:
195
+ signals["issue_close_rate"] = closed_count / total_issues
196
+
197
+ time.sleep(1)
198
+ except Exception as e:
199
+ logger.debug("[agent_signals] github error for %s: %s", agent_name, e)
200
+ errors += 1
201
+
202
+ # ── 8: PyPI downloads ──
203
+ pypi_pkg = info.get("pypi")
204
+ if pypi_pkg:
205
+ try:
206
+ r = httpx.get(f"https://pypistats.org/api/packages/{pypi_pkg}/recent", timeout=10)
207
+ if r.status_code == 200:
208
+ data = r.json().get("data", {})
209
+ signals["pypi_downloads_week"] = data.get("last_week", 0)
210
+ signals["pypi_downloads_month"] = data.get("last_month", 0)
211
+ time.sleep(1)
212
+ except Exception:
213
+ errors += 1
214
+
215
+ # npm downloads
216
+ npm_pkg = info.get("npm")
217
+ if npm_pkg:
218
+ try:
219
+ r = httpx.get(f"https://api.npmjs.org/downloads/point/last-week/{npm_pkg}", timeout=10)
220
+ if r.status_code == 200:
221
+ signals["npm_downloads_week"] = r.json().get("downloads", 0)
222
+ time.sleep(0.5)
223
+ except Exception:
224
+ errors += 1
225
+
226
+ # ── 9-10: VS Code extension ──
227
+ vscode_id = info.get("vscode")
228
+ if vscode_id:
229
+ try:
230
+ payload = {"filters": [{"criteria": [{"filterType": 7, "value": vscode_id}]}], "flags": 914}
231
+ r = httpx.post("https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery",
232
+ json=payload, headers={"Content-Type": "application/json",
233
+ "Accept": "application/json;api-version=6.0-preview.1"}, timeout=15)
234
+ if r.status_code == 200:
235
+ exts = r.json().get("results", [{}])[0].get("extensions", [])
236
+ if exts:
237
+ stats = {s["statisticName"]: s["value"] for s in exts[0].get("statistics", [])}
238
+ signals["vscode_installs"] = int(stats.get("install", 0))
239
+ signals["vscode_rating"] = float(stats.get("averagerating", 0))
240
+ signals["vscode_rating_count"] = int(stats.get("ratingcount", 0))
241
+ time.sleep(1)
242
+ except Exception:
243
+ errors += 1
244
+
245
+ # ── 12: Social media sentiment ──
246
+ search_terms = info.get("search", [])
247
+ sentiments = []
248
+ for term in search_terms:
249
+ for table, col in [("bluesky_signals", "text"), ("reddit_signals", "title"),
250
+ ("hn_signals", "title"), ("mastodon_signals", "text")]:
251
+ try:
252
+ srows = conn.execute(f"""
253
+ SELECT s.composite_sentiment FROM sentiment_scores s
254
+ WHERE LOWER(s.text_preview) LIKE ?
255
+ """, (f"%{term.lower()}%",)).fetchall()
256
+ sentiments.extend([r[0] for r in srows if r[0] is not None])
257
+ except Exception:
258
+ pass
259
+
260
+ if sentiments:
261
+ signals["sentiment_avg"] = sum(sentiments) / len(sentiments)
262
+ signals["sentiment_count"] = len(sentiments)
263
+ signals["sentiment_positive_pct"] = sum(1 for s in sentiments if s > 0.05) / len(sentiments)
264
+
265
+ # ── 13: SO questions ──
266
+ mention_count = 0
267
+ for term in search_terms:
268
+ try:
269
+ n = conn.execute("SELECT COUNT(*) FROM stackoverflow_signals WHERE LOWER(title) LIKE ?",
270
+ (f"%{term.lower()}%",)).fetchone()[0]
271
+ mention_count += n
272
+ except Exception:
273
+ pass
274
+ signals["so_questions"] = mention_count
275
+
276
+ # Carry forward GitHub signals from previous collection if API failed
277
+ github_keys = ["github_stars", "github_forks", "github_open_issues", "github_watchers",
278
+ "github_contributors", "issue_close_rate", "days_since_update"]
279
+ if info.get("github") and signals.get("github_stars", 0) == 0:
280
+ try:
281
+ prev = conn.execute("""
282
+ SELECT signals_json FROM agent_signals_raw
283
+ WHERE agent_name = ? ORDER BY id DESC LIMIT 1
284
+ """, (agent_name,)).fetchone()
285
+ if prev:
286
+ prev_signals = json.loads(prev[0]) if prev[0] else {}
287
+ for k in github_keys:
288
+ if k in prev_signals and prev_signals[k]:
289
+ signals[k] = prev_signals[k]
290
+ except Exception:
291
+ pass
292
+
293
+ # Write all signals
294
+ now_ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
295
+ with db() as wconn:
296
+ wconn.execute("""
297
+ INSERT INTO agent_signals_raw
298
+ (agent_name, category, signals_json, collected_at)
299
+ VALUES (?, ?, ?, ?)
300
+ """, (agent_name, info.get("category", "general"), json.dumps(signals), now_ts))
301
+ rows += 1
302
+
303
+ conn.close()
304
+ return {"rows_inserted": rows, "errors": errors}
backfill_agents.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent-Specific Historical Backfill.
3
+
4
+ Pulls historical data for the 57-agent registry from sources that support
5
+ date-range queries. This extends the observation window from 14 days to
6
+ 3+ months for the NeurIPS D&B submission.
7
+
8
+ Backfill sources:
9
+ - Hacker News (Algolia API): full history, date-filterable
10
+ - arXiv: papers mentioning agents from last 6 months
11
+ - Stack Overflow: questions with fromdate/todate (SE API v2.3)
12
+ - GitHub: star history, releases, contributor growth
13
+ - PyPI: historical download stats (pypistats.org)
14
+
15
+ Usage:
16
+ python -m collectors.backfill_agents # all sources, 3 months
17
+ python -m collectors.backfill_agents --source hn # HN only
18
+ python -m collectors.backfill_agents --months 4 # go back 4 months
19
+ python -m collectors.backfill_agents --source github # GitHub history
20
+ """
21
+
22
+ import sys
23
+ import time
24
+ import json
25
+ import httpx
26
+ import logging
27
+ import argparse
28
+ from datetime import datetime, timedelta, timezone
29
+ from pathlib import Path
30
+
31
+ sys.path.insert(0, str(Path(__file__).parent.parent))
32
+ from db.schema import db, get_connection
33
+ from collectors.agent_signals import AGENT_REGISTRY
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ # ═══════════════════════════════════════════════════════════════════════════════
39
+ # Build search terms from agent registry
40
+ # ═══════════════════════════════════════════════════════════════════════════════
41
+
42
+ def _get_agent_search_terms() -> dict[str, list[str]]:
43
+ """Return {search_term: [agent_name, ...]} for all agents."""
44
+ terms = {}
45
+ for agent_name, info in AGENT_REGISTRY.items():
46
+ for term in info.get("search", []):
47
+ terms.setdefault(term, []).append(agent_name)
48
+ return terms
49
+
50
+
51
+ # ═══════════════════════════════════════════════════════════════════════════════
52
+ # HN Backfill (Algolia API — supports full history)
53
+ # ═══════════════════════════════════════════════════════════════════════════════
54
+
55
+ def backfill_hn_agents(months: int = 3) -> int:
56
+ """Backfill HN stories mentioning agents from past N months."""
57
+ logger.info("[backfill-agents] HN: going back %d months...", months)
58
+ rows_inserted = 0
59
+
60
+ now = datetime.now(timezone.utc)
61
+ start_ts = int((now - timedelta(days=months * 30)).timestamp())
62
+ agent_terms = _get_agent_search_terms()
63
+
64
+ with httpx.Client(timeout=30) as client:
65
+ for term, agent_names in agent_terms.items():
66
+ page = 0
67
+ while page < 10:
68
+ params = {
69
+ "query": term,
70
+ "tags": "(story,ask_hn,comment)",
71
+ "numericFilters": f"created_at_i>{start_ts}",
72
+ "hitsPerPage": 50,
73
+ "page": page,
74
+ }
75
+ try:
76
+ r = client.get("https://hn.algolia.com/api/v1/search", params=params)
77
+ if r.status_code != 200:
78
+ break
79
+ except Exception:
80
+ break
81
+
82
+ data = r.json()
83
+ hits = data.get("hits", [])
84
+ if not hits:
85
+ break
86
+
87
+ with db() as conn:
88
+ for hit in hits:
89
+ story_id = str(hit.get("objectID", ""))
90
+ created_ts = hit.get("created_at_i")
91
+ created_at = (datetime.fromtimestamp(created_ts, tz=timezone.utc)
92
+ .strftime("%Y-%m-%d %H:%M:%S") if created_ts else None)
93
+ title = hit.get("title") or hit.get("comment_text", "")[:200] or ""
94
+
95
+ for agent_name in agent_names:
96
+ try:
97
+ conn.execute("""
98
+ INSERT OR IGNORE INTO hn_signals
99
+ (model_slug, story_id, title, score, num_comments,
100
+ author, created_at, collected_at)
101
+ VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
102
+ """, (agent_name, story_id, title[:500],
103
+ hit.get("points", 0), hit.get("num_comments", 0),
104
+ hit.get("author"), created_at))
105
+ rows_inserted += 1
106
+ except Exception:
107
+ pass
108
+
109
+ page += 1
110
+ if page >= data.get("nbPages", 0):
111
+ break
112
+ time.sleep(0.3)
113
+
114
+ time.sleep(0.5)
115
+
116
+ logger.info("[backfill-agents] HN: inserted %d rows", rows_inserted)
117
+ return rows_inserted
118
+
119
+
120
+ # ═══════════════════════════════════════════════════════════════════════════════
121
+ # Stack Overflow Backfill (SE API v2.3 — supports fromdate/todate)
122
+ # ═══════════════════════════════════════════════════════════════════════════════
123
+
124
+ def backfill_stackoverflow_agents(months: int = 3) -> int:
125
+ """Backfill Stack Overflow questions mentioning agents from past N months."""
126
+ logger.info("[backfill-agents] StackOverflow: going back %d months...", months)
127
+ rows_inserted = 0
128
+
129
+ now = datetime.now(timezone.utc)
130
+ from_ts = int((now - timedelta(days=months * 30)).timestamp())
131
+
132
+ agent_terms = _get_agent_search_terms()
133
+
134
+ with httpx.Client(timeout=30) as client:
135
+ for term, agent_names in agent_terms.items():
136
+ params = {
137
+ "order": "desc",
138
+ "sort": "creation",
139
+ "q": term,
140
+ "site": "stackoverflow",
141
+ "pagesize": 50,
142
+ "fromdate": from_ts,
143
+ "filter": "default",
144
+ }
145
+ try:
146
+ r = client.get("https://api.stackexchange.com/2.3/search/advanced", params=params)
147
+ if r.status_code != 200:
148
+ continue
149
+ data = r.json()
150
+ except Exception:
151
+ continue
152
+
153
+ items = data.get("items", [])
154
+ with db() as conn:
155
+ for item in items:
156
+ q_id = str(item.get("question_id", ""))
157
+ created_at = datetime.fromtimestamp(
158
+ item.get("creation_date", 0), tz=timezone.utc
159
+ ).strftime("%Y-%m-%d %H:%M:%S")
160
+
161
+ for agent_name in agent_names:
162
+ try:
163
+ conn.execute("""
164
+ INSERT OR IGNORE INTO stackoverflow_signals
165
+ (model_slug, question_id, title, score, answer_count,
166
+ view_count, is_answered, tags, created_at, collected_at)
167
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
168
+ """, (agent_name, q_id, item.get("title", ""),
169
+ item.get("score", 0), item.get("answer_count", 0),
170
+ item.get("view_count", 0),
171
+ 1 if item.get("is_answered") else 0,
172
+ ",".join(item.get("tags", [])),
173
+ created_at))
174
+ rows_inserted += 1
175
+ except Exception:
176
+ pass
177
+
178
+ # SE API has 300 req/day quota — pace conservatively
179
+ time.sleep(2)
180
+ if data.get("quota_remaining", 999) < 10:
181
+ logger.warning("[backfill-agents] SO quota low, stopping")
182
+ break
183
+
184
+ logger.info("[backfill-agents] SO: inserted %d rows", rows_inserted)
185
+ return rows_inserted
186
+
187
+
188
+ # ═══════════════════════════════════════════════════════════════════════════════
189
+ # GitHub Historical Backfill (star history, releases, contributors over time)
190
+ # ═══════════════════════════════════════════════════════════════════════════════
191
+
192
+ def backfill_github_agents(months: int = 3) -> int:
193
+ """Backfill GitHub release history + contributor growth for agents with repos."""
194
+ logger.info("[backfill-agents] GitHub: going back %d months...", months)
195
+ rows_inserted = 0
196
+ import os
197
+ token = os.environ.get("GITHUB_TOKEN", "")
198
+ headers = {"Accept": "application/vnd.github+json"}
199
+ if token:
200
+ headers["Authorization"] = f"Bearer {token}"
201
+
202
+ with httpx.Client(timeout=30, headers=headers) as client:
203
+ for agent_name, info in AGENT_REGISTRY.items():
204
+ repo = info.get("github")
205
+ if not repo:
206
+ continue
207
+
208
+ # Get release history
209
+ try:
210
+ r = client.get(f"https://api.github.com/repos/{repo}/releases", params={"per_page": 30})
211
+ if r.status_code == 200:
212
+ releases = r.json()
213
+ with db() as conn:
214
+ for rel in releases:
215
+ published = rel.get("published_at", "")
216
+ tag = rel.get("tag_name", "")
217
+ try:
218
+ conn.execute("""
219
+ INSERT OR IGNORE INTO agent_github_history
220
+ (agent_name, event_type, event_data, event_at, collected_at)
221
+ VALUES (?, 'release', ?, ?, datetime('now'))
222
+ """, (agent_name, json.dumps({"tag": tag, "name": rel.get("name", "")}),
223
+ published))
224
+ rows_inserted += 1
225
+ except Exception:
226
+ pass
227
+ except Exception:
228
+ pass
229
+
230
+ # Get contributor count over time (via contributors endpoint)
231
+ try:
232
+ r = client.get(f"https://api.github.com/repos/{repo}/contributors",
233
+ params={"per_page": 1, "anon": "false"})
234
+ if r.status_code == 200 and "Link" in r.headers:
235
+ # Parse last page from Link header to get total contributors
236
+ link = r.headers["Link"]
237
+ if 'rel="last"' in link:
238
+ import re
239
+ m = re.search(r'page=(\d+)>; rel="last"', link)
240
+ if m:
241
+ total = int(m.group(1))
242
+ with db() as conn:
243
+ conn.execute("""
244
+ INSERT OR IGNORE INTO agent_github_history
245
+ (agent_name, event_type, event_data, event_at, collected_at)
246
+ VALUES (?, 'contributors_snapshot', ?, datetime('now'), datetime('now'))
247
+ """, (agent_name, json.dumps({"total": total})))
248
+ rows_inserted += 1
249
+ except Exception:
250
+ pass
251
+
252
+ # Get weekly commit activity (last year)
253
+ try:
254
+ r = client.get(f"https://api.github.com/repos/{repo}/stats/commit_activity")
255
+ if r.status_code == 200:
256
+ weeks = r.json()
257
+ if isinstance(weeks, list):
258
+ with db() as conn:
259
+ for week in weeks[-months * 4:]: # last N months of weeks
260
+ week_ts = week.get("week", 0)
261
+ week_date = datetime.fromtimestamp(week_ts, tz=timezone.utc).strftime("%Y-%m-%d")
262
+ try:
263
+ conn.execute("""
264
+ INSERT OR IGNORE INTO agent_github_history
265
+ (agent_name, event_type, event_data, event_at, collected_at)
266
+ VALUES (?, 'weekly_commits', ?, ?, datetime('now'))
267
+ """, (agent_name, json.dumps({"total": week.get("total", 0)}), week_date))
268
+ rows_inserted += 1
269
+ except Exception:
270
+ pass
271
+ except Exception:
272
+ pass
273
+
274
+ time.sleep(1) # GitHub rate limit: 60/hr unauthenticated, 5000/hr with token
275
+
276
+ logger.info("[backfill-agents] GitHub: inserted %d rows", rows_inserted)
277
+ return rows_inserted
278
+
279
+
280
+ # ═══════════════════════════════════════════════════════════════════════════════
281
+ # PyPI Historical Downloads (pypistats.org API — 180 days of daily data)
282
+ # ═══════════════════════════════════════════════════════════════════════════════
283
+
284
+ def backfill_pypi_agents(months: int = 3) -> int:
285
+ """Backfill PyPI download history for agents with pypi packages."""
286
+ logger.info("[backfill-agents] PyPI: going back %d months...", months)
287
+ rows_inserted = 0
288
+
289
+ with httpx.Client(timeout=30) as client:
290
+ for agent_name, info in AGENT_REGISTRY.items():
291
+ pkg = info.get("pypi")
292
+ if not pkg:
293
+ continue
294
+
295
+ try:
296
+ r = client.get(f"https://pypistats.org/api/packages/{pkg}/overall",
297
+ params={"mirrors": "false"})
298
+ if r.status_code != 200:
299
+ continue
300
+ data = r.json()
301
+ except Exception:
302
+ continue
303
+
304
+ cutoff = (datetime.now(timezone.utc) - timedelta(days=months * 30)).strftime("%Y-%m-%d")
305
+ with db() as conn:
306
+ for entry in data.get("data", []):
307
+ date = entry.get("date", "")
308
+ if date < cutoff:
309
+ continue
310
+ downloads = entry.get("downloads", 0)
311
+ try:
312
+ conn.execute("""
313
+ INSERT OR IGNORE INTO agent_pypi_history
314
+ (agent_name, date, downloads, collected_at)
315
+ VALUES (?, ?, ?, datetime('now'))
316
+ """, (agent_name, date, downloads))
317
+ rows_inserted += 1
318
+ except Exception:
319
+ pass
320
+
321
+ time.sleep(1)
322
+
323
+ logger.info("[backfill-agents] PyPI: inserted %d rows", rows_inserted)
324
+ return rows_inserted
325
+
326
+
327
+ # ═══════════════════════════════════════════════════════════════════════════════
328
+ # arXiv Backfill (papers mentioning agents)
329
+ # ═══════════════════════════════════════════════════════════════════════════════
330
+
331
+ def backfill_arxiv_agents(months: int = 6) -> int:
332
+ """Backfill arXiv papers mentioning agents."""
333
+ import arxiv
334
+ logger.info("[backfill-agents] arXiv: going back %d months...", months)
335
+ rows_inserted = 0
336
+ client = arxiv.Client()
337
+
338
+ # Map agent names to arxiv search terms
339
+ ARXIV_AGENT_TERMS = {
340
+ "SWE-bench": ["SWE-agent", "OpenHands", "Devin", "Claude Code"],
341
+ "code agent": ["Claude Code", "Cursor", "Cline", "Aider", "OpenAI Codex"],
342
+ "AI coding assistant": ["GitHub Copilot", "Windsurf", "Tabnine", "Continue"],
343
+ "multi-agent": ["CrewAI", "Microsoft AutoGen", "LangGraph", "MetaGPT"],
344
+ "browser agent": ["Browser Use", "OpenClaw", "Operator", "Multion"],
345
+ "LLM agent evaluation": ["SWE-agent", "OpenHands", "Claude Code"],
346
+ "autonomous agent": ["AutoGPT", "Devin", "Manus", "MetaGPT"],
347
+ "tool use LLM": ["Claude MCP", "OpenAI Agents SDK", "LlamaIndex"],
348
+ }
349
+
350
+ for term, agent_names in ARXIV_AGENT_TERMS.items():
351
+ try:
352
+ search = arxiv.Search(
353
+ query=f'all:"{term}"',
354
+ max_results=100,
355
+ sort_by=arxiv.SortCriterion.SubmittedDate,
356
+ sort_order=arxiv.SortOrder.Descending,
357
+ )
358
+ results = list(client.results(search))
359
+
360
+ with db() as conn:
361
+ for paper in results:
362
+ paper_id = paper.entry_id.split("/")[-1]
363
+ categories = ",".join(paper.categories)
364
+ published = paper.published.strftime("%Y-%m-%d %H:%M:%S") if paper.published else None
365
+
366
+ for agent_name in agent_names:
367
+ try:
368
+ conn.execute("""
369
+ INSERT OR IGNORE INTO arxiv_signals
370
+ (model_slug, paper_id, title, abstract_preview,
371
+ categories, authors_count, published_at)
372
+ VALUES (?, ?, ?, ?, ?, ?, ?)
373
+ """, (agent_name, paper_id, paper.title,
374
+ (paper.summary or "")[:500],
375
+ categories, len(paper.authors), published))
376
+ rows_inserted += 1
377
+ except Exception:
378
+ pass
379
+
380
+ except Exception as e:
381
+ logger.warning("[backfill-agents] arXiv error for '%s': %s", term, str(e)[:100])
382
+
383
+ time.sleep(3)
384
+
385
+ logger.info("[backfill-agents] arXiv: inserted %d rows", rows_inserted)
386
+ return rows_inserted
387
+
388
+
389
+ # ═══════════════════════════════════════════════════════════════════════════════
390
+ # DB table creation for historical data
391
+ # ═══════════════════════════════════════════════════════════════════════════════
392
+
393
+ def ensure_history_tables():
394
+ """Create tables for historical agent data if they don't exist."""
395
+ with db() as conn:
396
+ conn.execute("""
397
+ CREATE TABLE IF NOT EXISTS agent_github_history (
398
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
399
+ agent_name TEXT NOT NULL,
400
+ event_type TEXT NOT NULL,
401
+ event_data TEXT,
402
+ event_at TEXT,
403
+ collected_at TEXT DEFAULT CURRENT_TIMESTAMP,
404
+ UNIQUE(agent_name, event_type, event_at)
405
+ )
406
+ """)
407
+ conn.execute("""
408
+ CREATE TABLE IF NOT EXISTS agent_pypi_history (
409
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
410
+ agent_name TEXT NOT NULL,
411
+ date TEXT NOT NULL,
412
+ downloads INTEGER DEFAULT 0,
413
+ collected_at TEXT DEFAULT CURRENT_TIMESTAMP,
414
+ UNIQUE(agent_name, date)
415
+ )
416
+ """)
417
+
418
+
419
+ # ═══════════════════════════════════════════════════════════════════════════════
420
+ # Main entry point
421
+ # ═══════════════════════════════════════════════════════════════════════════════
422
+
423
+ def run_agent_backfill(sources: list[str] = None, months: int = 3) -> dict:
424
+ """Run agent-specific backfill operations."""
425
+ ensure_history_tables()
426
+ results = {}
427
+
428
+ if sources is None:
429
+ sources = ["hn", "so", "github", "pypi", "arxiv"]
430
+
431
+ if "hn" in sources:
432
+ results["hn"] = backfill_hn_agents(months)
433
+
434
+ if "so" in sources:
435
+ results["so"] = backfill_stackoverflow_agents(months)
436
+
437
+ if "github" in sources:
438
+ results["github"] = backfill_github_agents(months)
439
+
440
+ if "pypi" in sources:
441
+ results["pypi"] = backfill_pypi_agents(months)
442
+
443
+ if "arxiv" in sources:
444
+ results["arxiv"] = backfill_arxiv_agents(min(months, 6))
445
+
446
+ return results
447
+
448
+
449
+ if __name__ == "__main__":
450
+ logging.basicConfig(level=logging.INFO,
451
+ format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
452
+
453
+ parser = argparse.ArgumentParser(description="Agent-specific historical backfill")
454
+ parser.add_argument("--source", type=str,
455
+ help="Source to backfill (hn, so, github, pypi, arxiv)")
456
+ parser.add_argument("--months", type=int, default=3,
457
+ help="Months to go back (default: 3)")
458
+ args = parser.parse_args()
459
+
460
+ sources = [args.source] if args.source else None
461
+ results = run_agent_backfill(sources, args.months)
462
+
463
+ total = sum(results.values())
464
+ print(f"\n=== Agent Backfill Results ({total} total rows) ===")
465
+ for source, rows in results.items():
466
+ print(f" {source}: {rows} rows inserted")
base.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Abstract base for all collectors.
3
+ Each collector must implement `collect()` which writes to the DB and returns a summary dict.
4
+ """
5
+
6
+ from abc import ABC, abstractmethod
7
+ from datetime import datetime, timezone
8
+ import logging
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class BaseCollector(ABC):
13
+ name: str = "base"
14
+
15
+ def run(self) -> dict:
16
+ start = datetime.now(timezone.utc)
17
+ logger.info("[%s] collection started", self.name)
18
+ try:
19
+ result = self.collect()
20
+ elapsed = (datetime.now(timezone.utc) - start).total_seconds()
21
+ logger.info("[%s] done in %.1fs — %s", self.name, elapsed, result)
22
+ return result
23
+ except Exception as exc:
24
+ logger.exception("[%s] collection failed: %s", self.name, exc)
25
+ return {"error": str(exc)}
26
+
27
+ @abstractmethod
28
+ def collect(self) -> dict:
29
+ """Fetch data and persist to DB. Return a summary dict."""
30
+ ...
config.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AgentPulse — global configuration.
2
+
3
+ All API credentials are read from environment variables. No keys are
4
+ embedded in source. Copy `.env.example` to `.env` and fill in values
5
+ to enable authenticated API paths (without auth, public-rate-limit
6
+ collection still works).
7
+ """
8
+
9
+ import os
10
+ from pathlib import Path
11
+
12
+ # ───────────────────────────────────────────────────────────────────────────────
13
+ # Storage
14
+ # ───────────────────────────────────────────────────────────────────────────────
15
+ DB_PATH = Path(__file__).parent / "data" / "agentpulse.db"
16
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)
17
+
18
+ # ───────────────────────────────────────────────────────────────────────────────
19
+ # API credentials (all optional; collectors fall back to public endpoints)
20
+ # ───────────────────────────────────────────────────────────────────────────────
21
+ GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "")
22
+ HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN", "")
23
+
24
+ REDDIT_CLIENT_ID = os.getenv("REDDIT_CLIENT_ID", "")
25
+ REDDIT_CLIENT_SECRET = os.getenv("REDDIT_CLIENT_SECRET", "")
26
+ REDDIT_USER_AGENT = os.getenv("REDDIT_USER_AGENT", "agentpulse/0.1")
27
+
28
+ BLUESKY_HANDLE = os.getenv("BLUESKY_HANDLE", "")
29
+ BLUESKY_PASSWORD = os.getenv("BLUESKY_PASSWORD", "")
30
+
31
+ TWITTER_BEARER_TOKEN = os.getenv("TWITTER_BEARER_TOKEN", "")
32
+ OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
33
+
34
+ # ───────────────────────────────────────────────────────────────────────────────
35
+ # Collection cadence (per-collector overrides supported via env)
36
+ # ───────────────────────────────────────────────────────────────────────────────
37
+ DEFAULT_INTERVAL_MIN = int(os.getenv("AP_INTERVAL_MIN", "60"))
38
+ BENCHMARK_INTERVAL_HR = int(os.getenv("AP_BENCH_INTERVAL_HR", "24"))
39
+ GITHUB_INTERVAL_HR = int(os.getenv("AP_GH_INTERVAL_HR", "6"))
40
+ SOCIAL_INTERVAL_MIN = int(os.getenv("AP_SOCIAL_INTERVAL_MIN", "30"))
41
+
42
+ # ───────────────────────────────────────────────────────────────────────────────
43
+ # Scoring / composite weights (override the paper defaults via env)
44
+ # ───────────────────────────────────────────────────────────────────────────────
45
+ W_BENCHMARK = float(os.getenv("AP_W_BENCHMARK", "0.35"))
46
+ W_ADOPTION = float(os.getenv("AP_W_ADOPTION", "0.25"))
47
+ W_SENTIMENT = float(os.getenv("AP_W_SENTIMENT", "0.20"))
48
+ W_ECOSYSTEM = float(os.getenv("AP_W_ECOSYSTEM", "0.20"))
49
+
50
+ # ───────────────────────────────────────────────────────────────────────────────
51
+ # Data quality thresholds (Section 3 / Appendix A)
52
+ # ───────────────────────────────────────────────────────────────────────────────
53
+ DQ_THRESHOLD = float(os.getenv("AP_DQ_THRESHOLD", "0.30"))
54
+ DQ_THETA_UNIQ = 0.30
55
+ DQ_THETA_BOT = 0.20
56
+ DQ_THETA_CRED = 0.20
57
+ DQ_THETA_SPEC = 0.30
58
+ DQ_NEAR_DUP_TAU = 0.85
59
+ DQ_DUP_WINDOW_DAYS = 7
data_quality.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data Quality Layer.
3
+
4
+ Filters and scores every collected text for trustworthiness before it
5
+ enters the sentiment pipeline. Three sub-systems:
6
+
7
+ 1. DUPLICATE DETECTION
8
+ - Exact duplicate (same text across sources)
9
+ - Near-duplicate (cosine similarity via character trigrams, >0.85 threshold)
10
+ - Cross-model duplicate (same post attributed to multiple models)
11
+
12
+ 2. BOT / SPAM DETECTION
13
+ - Repetitive posting pattern (same author, similar text, high frequency)
14
+ - Generic content (text too short, no specifics, templated phrases)
15
+ - Engagement anomaly (extremely high/low engagement vs author baseline)
16
+ - New account signal (no engagement history → lower trust)
17
+
18
+ 3. SOURCE CREDIBILITY SCORING
19
+ - Author history (repeat authors with consistent engagement = higher trust)
20
+ - Platform weighting (SO/HN higher base credibility than Bluesky/Reddit)
21
+ - Engagement ratio (high engagement = community-validated content)
22
+ - Specificity score (mentions specific model features/versions vs generic)
23
+
24
+ Output: each text gets a `quality_score` (0-1) that multiplies its sentiment weight.
25
+ Texts scoring < 0.3 are flagged as low-quality and excluded from scoring.
26
+
27
+ Usage:
28
+ python -m scoring.data_quality — score all texts
29
+ python -m scoring.data_quality --stats — print quality distribution
30
+ """
31
+
32
+ import re
33
+ import math
34
+ import json
35
+ import logging
36
+ import hashlib
37
+ from collections import defaultdict, Counter
38
+ from pathlib import Path
39
+ import sys
40
+
41
+ sys.path.insert(0, str(Path(__file__).parent.parent))
42
+ from db.schema import get_connection, db
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+
47
+ # ═══════════════════════════════════════════════════════════════════════════════
48
+ # SCHEMA
49
+ # ═══════════════════════════════════════════════════════════════════════════════
50
+
51
+ def init_quality_tables():
52
+ with db() as conn:
53
+ conn.executescript("""
54
+ CREATE TABLE IF NOT EXISTS data_quality (
55
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
56
+ source TEXT NOT NULL,
57
+ source_id INTEGER NOT NULL,
58
+ model_slug TEXT NOT NULL,
59
+
60
+ -- Quality sub-scores (0-1, higher = better quality)
61
+ uniqueness REAL, -- 1.0 = totally unique, 0.0 = exact duplicate
62
+ bot_score REAL, -- 1.0 = definitely human, 0.0 = likely bot
63
+ credibility REAL, -- 1.0 = high-credibility source, 0.0 = low
64
+ specificity REAL, -- 1.0 = very specific about model, 0.0 = generic
65
+
66
+ -- Composite
67
+ quality_score REAL, -- weighted average of sub-scores
68
+ is_flagged INTEGER DEFAULT 0, -- 1 = excluded from scoring
69
+
70
+ -- Metadata
71
+ duplicate_of INTEGER, -- source_id of the original if duplicate
72
+ flag_reasons TEXT, -- JSON list of reasons
73
+
74
+ computed_at TEXT NOT NULL DEFAULT (datetime('now')),
75
+ UNIQUE(source, source_id, model_slug)
76
+ );
77
+ CREATE INDEX IF NOT EXISTS idx_dq_model ON data_quality(model_slug);
78
+ CREATE INDEX IF NOT EXISTS idx_dq_quality ON data_quality(quality_score);
79
+ """)
80
+
81
+
82
+ # ═══════════════════════════════════════════════════════════════════════════════
83
+ # 1. DUPLICATE DETECTION
84
+ # ═══════════════════════════════════════════════════════════════════════════════
85
+
86
+ def _text_hash(text: str) -> str:
87
+ """Normalize and hash text for exact duplicate detection."""
88
+ normalized = re.sub(r'\s+', ' ', text.lower().strip())
89
+ normalized = re.sub(r'https?://\S+', '', normalized)
90
+ normalized = re.sub(r'@\w+', '', normalized)
91
+ return hashlib.md5(normalized.encode()).hexdigest()
92
+
93
+
94
+ def _trigram_set(text: str) -> set:
95
+ """Character trigrams for near-duplicate detection."""
96
+ text = re.sub(r'\s+', ' ', text.lower().strip())
97
+ if len(text) < 3:
98
+ return set()
99
+ return {text[i:i+3] for i in range(len(text) - 2)}
100
+
101
+
102
+ def _jaccard_similarity(set_a: set, set_b: set) -> float:
103
+ if not set_a or not set_b:
104
+ return 0.0
105
+ intersection = len(set_a & set_b)
106
+ union = len(set_a | set_b)
107
+ return intersection / union if union > 0 else 0.0
108
+
109
+
110
+ def compute_uniqueness(texts: list[dict]) -> dict[tuple, float]:
111
+ """
112
+ Score uniqueness for each text.
113
+ Returns {(source, source_id, model_slug): uniqueness_score}
114
+ """
115
+ # Build hash → first occurrence map
116
+ hash_map: dict[str, tuple] = {} # hash → (source, source_id, model_slug)
117
+ trigram_map: dict[tuple, set] = {}
118
+ results = {}
119
+
120
+ for t in texts:
121
+ key = (t["source"], t["source_id"], t["model_slug"])
122
+ text = t["text"] or ""
123
+ h = _text_hash(text)
124
+ trigrams = _trigram_set(text)
125
+ trigram_map[key] = trigrams
126
+
127
+ if h in hash_map:
128
+ # Exact duplicate
129
+ results[key] = 0.0
130
+ else:
131
+ hash_map[h] = key
132
+ results[key] = 1.0 # provisional — check near-duplicates below
133
+
134
+ # Near-duplicate check (only for texts that passed exact duplicate check)
135
+ # Sample-based for performance — check against last 500 unique texts
136
+ unique_keys = [k for k, v in results.items() if v > 0]
137
+ recent = unique_keys[-500:]
138
+
139
+ for i, key in enumerate(unique_keys):
140
+ if results[key] == 0.0:
141
+ continue
142
+ tri_a = trigram_map.get(key, set())
143
+ if not tri_a:
144
+ continue
145
+
146
+ max_sim = 0
147
+ for other_key in recent[max(0, i-50):i]: # check 50 nearest
148
+ if other_key == key:
149
+ continue
150
+ tri_b = trigram_map.get(other_key, set())
151
+ sim = _jaccard_similarity(tri_a, tri_b)
152
+ max_sim = max(max_sim, sim)
153
+
154
+ if max_sim > 0.85:
155
+ results[key] = 1.0 - max_sim # near-duplicate: reduce score
156
+ else:
157
+ results[key] = 1.0
158
+
159
+ return results
160
+
161
+
162
+ # ═══════════════════════════════════════════════════════════════════════════════
163
+ # 2. BOT / SPAM DETECTION
164
+ # ═══════════════════════════════════════════════════════════════════════════════
165
+
166
+ GENERIC_PATTERNS = [
167
+ r"^.{0,15}$", # too short
168
+ r"(check out|click here|visit|buy now|discount|promo)", # spam
169
+ r"^(yes|no|true|false|ok|thanks|same|agreed|this)\.?$", # zero-content
170
+ r"(.)\1{5,}", # repeated characters
171
+ r"([\U0001F600-\U0001F9FF]){4,}", # emoji spam
172
+ ]
173
+
174
+ BOT_TEMPLATES = [
175
+ r"i asked (chatgpt|claude|gemini) (to|about)", # templated prompt sharing
176
+ r"here'?s what .+ said",
177
+ r"^thread:?\s*\d+/", # automated thread numbering
178
+ ]
179
+
180
+
181
+ def compute_bot_scores(texts: list[dict]) -> dict[tuple, float]:
182
+ """Score how likely each text is from a real human (1.0) vs bot (0.0)."""
183
+ # Track per-author posting frequency
184
+ author_posts: dict[str, list] = defaultdict(list)
185
+ for t in texts:
186
+ author = t.get("author") or "anonymous"
187
+ author_posts[author].append(t)
188
+
189
+ results = {}
190
+ for t in texts:
191
+ key = (t["source"], t["source_id"], t["model_slug"])
192
+ text = t["text"] or ""
193
+ author = t.get("author") or "anonymous"
194
+ score = 1.0
195
+ reasons = []
196
+
197
+ # Generic content check
198
+ for pattern in GENERIC_PATTERNS:
199
+ if re.search(pattern, text.lower()):
200
+ score -= 0.3
201
+ reasons.append("generic_content")
202
+ break
203
+
204
+ # Bot template check
205
+ for pattern in BOT_TEMPLATES:
206
+ if re.search(pattern, text.lower()):
207
+ score -= 0.2
208
+ reasons.append("bot_template")
209
+ break
210
+
211
+ # Author posting frequency (>20 posts in our data = suspicious)
212
+ author_count = len(author_posts.get(author, []))
213
+ if author_count > 50:
214
+ score -= 0.4
215
+ reasons.append("high_frequency_author")
216
+ elif author_count > 20:
217
+ score -= 0.2
218
+ reasons.append("frequent_author")
219
+
220
+ # Text length — very short texts have less signal
221
+ if len(text) < 30:
222
+ score -= 0.15
223
+ reasons.append("very_short")
224
+
225
+ results[key] = max(score, 0.0)
226
+
227
+ return results
228
+
229
+
230
+ # ═══════════════════════════════════════════════════════════════════════════════
231
+ # 3. SOURCE CREDIBILITY SCORING
232
+ # ═══════════════════════════════════════════════════════════════════════════════
233
+
234
+ # Base credibility by platform (higher = more rigorous community)
235
+ PLATFORM_CREDIBILITY = {
236
+ "stackoverflow": 0.90, # heavily moderated, technical
237
+ "hn": 0.85, # curated, technical community
238
+ "github_disc": 0.85, # developer context
239
+ "devto": 0.70, # developer blogs, some SEO spam
240
+ "mastodon": 0.65, # smaller but genuine community
241
+ "lemmy": 0.65, # niche, genuine
242
+ "v2ex": 0.70, # chinese dev community, active moderation
243
+ "reddit": 0.60, # large, noisy, some bots
244
+ "bluesky": 0.55, # social media, high noise
245
+ }
246
+
247
+
248
+ def compute_credibility(texts: list[dict]) -> dict[tuple, float]:
249
+ """Score source credibility per text."""
250
+ results = {}
251
+ for t in texts:
252
+ key = (t["source"], t["source_id"], t["model_slug"])
253
+ base = PLATFORM_CREDIBILITY.get(t["source"], 0.5)
254
+
255
+ # Engagement bonus: highly engaged content is community-validated
256
+ engagement = t.get("engagement", 0)
257
+ if engagement > 5:
258
+ base = min(base + 0.1, 1.0)
259
+ elif engagement > 20:
260
+ base = min(base + 0.2, 1.0)
261
+
262
+ results[key] = base
263
+
264
+ return results
265
+
266
+
267
+ # ═══════════════════════════════════════════════════════════════════════════════
268
+ # 4. SPECIFICITY SCORING
269
+ # ═══════════════════════════════════════════════════════════════════════════════
270
+
271
+ SPECIFIC_TERMS = [
272
+ # Model-specific technical terms
273
+ r"(context window|token|latency|throughput|ttft|tps)",
274
+ r"(api|endpoint|rate limit|pricing|cost per|million tokens)",
275
+ r"(benchmark|eval|score|elo|mmlu|humaneval|arena)",
276
+ r"(hallucin|accuracy|quality|performance|speed|slow|fast)",
277
+ r"(fine-?tun|rlhf|dpo|rag|function call|tool use)",
278
+ r"(version|update|release|v\d|model card)",
279
+ r"(parameter|weight|quantiz|gguf|fp16|int8)",
280
+ r"\b\d+[bB]\b", # model sizes like "70B"
281
+ r"\$[\d.]+", # pricing mentions
282
+ ]
283
+
284
+
285
+ def compute_specificity(texts: list[dict]) -> dict[tuple, float]:
286
+ """Score how specific each text is about LLM details (vs generic chatter)."""
287
+ results = {}
288
+ for t in texts:
289
+ key = (t["source"], t["source_id"], t["model_slug"])
290
+ text = t["text"] or ""
291
+ text_lower = text.lower()
292
+
293
+ matches = sum(1 for p in SPECIFIC_TERMS if re.search(p, text_lower))
294
+ # 0 matches = 0.3 (generic), 3+ matches = 1.0 (very specific)
295
+ score = min(0.3 + matches * 0.25, 1.0)
296
+ results[key] = score
297
+
298
+ return results
299
+
300
+
301
+ # ═══════════════════════════════════════════════════════════════════════════════
302
+ # MAIN: Score all texts
303
+ # ═══════════════════════════════════════════════════════════════════════════════
304
+
305
+ def run_quality_scoring() -> dict:
306
+ conn = get_connection()
307
+ init_quality_tables()
308
+
309
+ # Load all scored texts
310
+ rows = conn.execute("""
311
+ SELECT source, source_id, model_slug, text_preview, engagement_weight
312
+ FROM sentiment_scores
313
+ """).fetchall()
314
+
315
+ texts = [{"source": r[0], "source_id": r[1], "model_slug": r[2],
316
+ "text": r[3], "engagement": r[4] or 0} for r in rows]
317
+
318
+ if not texts:
319
+ conn.close()
320
+ return {"total": 0}
321
+
322
+ logger.info("[quality] scoring %d texts...", len(texts))
323
+
324
+ # Compute all sub-scores
325
+ uniqueness = compute_uniqueness(texts)
326
+ bot_scores = compute_bot_scores(texts)
327
+ credibility = compute_credibility(texts)
328
+ specificity = compute_specificity(texts)
329
+
330
+ # Composite quality score
331
+ WEIGHTS = {"uniqueness": 0.30, "bot": 0.25, "credibility": 0.25, "specificity": 0.20}
332
+ flagged = 0
333
+ total = 0
334
+
335
+ with db() as wconn:
336
+ batch = []
337
+ for t in texts:
338
+ key = (t["source"], t["source_id"], t["model_slug"])
339
+ u = uniqueness.get(key, 1.0)
340
+ b = bot_scores.get(key, 1.0)
341
+ c = credibility.get(key, 0.5)
342
+ s = specificity.get(key, 0.5)
343
+
344
+ quality = (u * WEIGHTS["uniqueness"] +
345
+ b * WEIGHTS["bot"] +
346
+ c * WEIGHTS["credibility"] +
347
+ s * WEIGHTS["specificity"])
348
+
349
+ is_flagged = 1 if quality < 0.3 else 0
350
+ if is_flagged:
351
+ flagged += 1
352
+
353
+ reasons = []
354
+ if u < 0.3: reasons.append("duplicate")
355
+ if b < 0.5: reasons.append("bot_suspected")
356
+ if s < 0.4: reasons.append("too_generic")
357
+
358
+ batch.append((
359
+ t["source"], t["source_id"], t["model_slug"],
360
+ u, b, c, s, quality, is_flagged,
361
+ json.dumps(reasons) if reasons else None,
362
+ ))
363
+ total += 1
364
+
365
+ if len(batch) >= 200:
366
+ wconn.executemany("""
367
+ INSERT OR REPLACE INTO data_quality
368
+ (source, source_id, model_slug,
369
+ uniqueness, bot_score, credibility, specificity,
370
+ quality_score, is_flagged, flag_reasons)
371
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
372
+ """, batch)
373
+ batch = []
374
+
375
+ if batch:
376
+ wconn.executemany("""
377
+ INSERT OR REPLACE INTO data_quality
378
+ (source, source_id, model_slug,
379
+ uniqueness, bot_score, credibility, specificity,
380
+ quality_score, is_flagged, flag_reasons)
381
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
382
+ """, batch)
383
+
384
+ conn.close()
385
+ logger.info("[quality] scored %d texts, flagged %d (%.1f%%) as low-quality",
386
+ total, flagged, flagged / max(total, 1) * 100)
387
+
388
+ return {"total": total, "flagged": flagged, "flagged_pct": flagged / max(total, 1) * 100}
389
+
390
+
391
+ if __name__ == "__main__":
392
+ logging.basicConfig(level=logging.INFO,
393
+ format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
394
+
395
+ import argparse
396
+ parser = argparse.ArgumentParser()
397
+ parser.add_argument("--stats", action="store_true")
398
+ args = parser.parse_args()
399
+
400
+ result = run_quality_scoring()
401
+ print(f"\nScored {result['total']} texts, flagged {result['flagged']} ({result['flagged_pct']:.1f}%)")
402
+
403
+ if args.stats:
404
+ conn = get_connection()
405
+ print("\n=== Quality Distribution ===")
406
+ for bucket in ["0.0-0.3 (flagged)", "0.3-0.5 (low)", "0.5-0.7 (medium)", "0.7-0.9 (good)", "0.9-1.0 (excellent)"]:
407
+ lo, hi = float(bucket.split("-")[0]), float(bucket.split("-")[1].split(" ")[0])
408
+ n = conn.execute("SELECT COUNT(*) FROM data_quality WHERE quality_score >= ? AND quality_score < ?", (lo, hi)).fetchone()[0]
409
+ print(f" {bucket}: {n}")
410
+
411
+ print("\n=== Flagged by reason ===")
412
+ for r in conn.execute("""
413
+ SELECT flag_reasons, COUNT(*) FROM data_quality
414
+ WHERE is_flagged = 1 AND flag_reasons IS NOT NULL
415
+ GROUP BY flag_reasons ORDER BY COUNT(*) DESC LIMIT 10
416
+ """).fetchall():
417
+ print(f" {r[0]}: {r[1]}")
418
+
419
+ print("\n=== Quality by source ===")
420
+ for r in conn.execute("""
421
+ SELECT source, COUNT(*), ROUND(AVG(quality_score),3),
422
+ SUM(is_flagged), ROUND(SUM(is_flagged)*100.0/COUNT(*),1)
423
+ FROM data_quality GROUP BY source ORDER BY AVG(quality_score) DESC
424
+ """).fetchall():
425
+ print(f" {r[0]:<20} n={r[1]:<5} avg_quality={r[2]} flagged={r[3]} ({r[4]}%)")
main.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AgentPulse — pipeline entrypoint.
2
+
3
+ Usage:
4
+ python main.py # Run the full collect → score → write loop once
5
+ python main.py --collect-only # Run collectors, skip scoring
6
+ python main.py --score-only # Recompute scores from existing signals
7
+ python main.py --reproduce # Reproduce the paper's headline result (Table 3)
8
+ """
9
+
10
+ import argparse
11
+ import logging
12
+ import sys
13
+
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
17
+ )
18
+ log = logging.getLogger("agentpulse")
19
+
20
+
21
+ def collect():
22
+ """Collect 18 signals across the agent registry."""
23
+ from collectors.agent_signals import AgentSignalCollector
24
+ from collectors.agent_benchmarks import AgentBenchmarkCollector
25
+
26
+ log.info("Collecting agent benchmark signals…")
27
+ AgentBenchmarkCollector().collect()
28
+ log.info("Collecting agent multi-source signals…")
29
+ AgentSignalCollector().collect()
30
+
31
+
32
+ def score():
33
+ """Aggregate raw signals into the four-factor composite (Section 3)."""
34
+ from scoring.agent_scoring_v2 import compute_agent_scores
35
+ log.info("Computing four-factor composite scores…")
36
+ compute_agent_scores()
37
+
38
+
39
+ def reproduce():
40
+ """Reproduce the paper's headline cross-factor predictive validity result."""
41
+ from scoring.agent_scoring_v2 import reproduce_table_3
42
+ reproduce_table_3()
43
+
44
+
45
+ def main():
46
+ parser = argparse.ArgumentParser(
47
+ description="AgentPulse — continuous multi-signal evaluation of AI agents"
48
+ )
49
+ parser.add_argument("--collect-only", action="store_true",
50
+ help="Only run collectors; skip scoring")
51
+ parser.add_argument("--score-only", action="store_true",
52
+ help="Only recompute scores from existing signals")
53
+ parser.add_argument("--reproduce", action="store_true",
54
+ help="Reproduce the paper's Table 3 headline result")
55
+ args = parser.parse_args()
56
+
57
+ if args.reproduce:
58
+ reproduce()
59
+ return
60
+
61
+ if args.score_only:
62
+ score()
63
+ return
64
+
65
+ collect()
66
+ if not args.collect_only:
67
+ score()
68
+
69
+
70
+ if __name__ == "__main__":
71
+ sys.exit(main() or 0)
recompute_all_stats.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recompute every statistic referenced in the paper from the released CSV
2
+ snapshot. Single source of truth for paper updates.
3
+
4
+ Outputs:
5
+ - Spearman rho_s + two-sided p for Stars / VS Code installs / SO questions
6
+ - Pearson r on log-targets (Appendix robustness check 2)
7
+ - Leave-one-out range on the GitHub-stars correlation (robustness check 1)
8
+ - Single- vs combined-factor sub-composite (robustness check 3)
9
+ - Dirichlet bootstrap (1000 draws from Dir(3.5, 2.5, 2.0, 2.0))
10
+ - Inter-factor Spearman matrix on n=50
11
+ """
12
+
13
+ import csv, json, math, random, sys
14
+ from pathlib import Path
15
+ from reproduce_table3 import (
16
+ spearman, two_sided_p,
17
+ load_latest_scores, load_latest_signals, load_registry,
18
+ benchmark_sentiment_subcomposite,
19
+ )
20
+
21
+
22
+ def pearson(xs, ys):
23
+ n = len(xs)
24
+ mx, my = sum(xs)/n, sum(ys)/n
25
+ num = sum((xs[i]-mx)*(ys[i]-my) for i in range(n))
26
+ dx = math.sqrt(sum((xs[i]-mx)**2 for i in range(n)))
27
+ dy = math.sqrt(sum((ys[i]-my)**2 for i in range(n)))
28
+ return num/(dx*dy) if dx and dy else float("nan")
29
+
30
+
31
+ def main():
32
+ csv_dir = Path(__file__).parent.parent / "data" / "csv"
33
+ scores = load_latest_scores(csv_dir)
34
+ signals = load_latest_signals(csv_dir)
35
+ registry = load_registry(csv_dir)
36
+
37
+ eligible = [n for n, c in registry.items() if c.get("github_repo") and n in scores and n in signals]
38
+ print(f"\n=== Sample size ===")
39
+ print(f"50 agents in registry, n = {len(eligible)} have github_repo + scores + signals")
40
+
41
+ bs, stars_log, installs_log, so_q = [], [], [], []
42
+ for name in eligible:
43
+ s = signals[name]
44
+ bs.append(benchmark_sentiment_subcomposite(scores[name], s))
45
+ stars_log.append(math.log10((s.get("github_stars") or 0) + 1))
46
+ installs_log.append(math.log10((s.get("vscode_installs") or 0) + 1))
47
+ so_q.append(s.get("so_questions") or 0)
48
+
49
+ # --- Table 3 (Spearman) ---
50
+ print(f"\n=== Table 3: Spearman correlations (n={len(bs)}) ===")
51
+ for label, ys in [("GitHub stars (log)", stars_log),
52
+ ("VS Code installs (log)", installs_log),
53
+ ("Stack Overflow question volume", so_q)]:
54
+ rho = spearman(bs, ys)
55
+ p = two_sided_p(rho, len(bs))
56
+ sig = "p<0.001" if p<0.001 else f"p={p:.3f}"
57
+ print(f" {label:<32} rho_s={rho:+.3f} {sig}")
58
+
59
+ # --- Pearson on log targets (Appendix Robustness check 2) ---
60
+ so_log = [math.log10(q + 1) for q in so_q]
61
+ print(f"\n=== Robustness check 2: Pearson on log targets ===")
62
+ for label, ys in [("GitHub stars (log)", stars_log),
63
+ ("VS Code installs (log)", installs_log),
64
+ ("Stack Overflow questions (log)", so_log)]:
65
+ r = pearson(bs, ys)
66
+ print(f" {label:<32} r={r:+.3f}")
67
+
68
+ # --- Robustness check 3: alternative sub-composites ---
69
+ print(f"\n=== Robustness check 3: alternative sub-composites vs stars ===")
70
+ bench_only, sent_only = [], []
71
+ for name in eligible:
72
+ sub = json.loads(scores[name].get("sub_scores") or "[0.5, 0, 0]")
73
+ bench_only.append(sub[0] if sub else 0.5)
74
+ sent_raw = float(scores[name].get("sentiment") or 0.0)
75
+ sent_only.append(max(0.0, min(1.0, (sent_raw + 1.0) / 2.0)))
76
+ print(f" Benchmark only: rho_s={spearman(bench_only, stars_log):+.3f}")
77
+ print(f" Sentiment only: rho_s={spearman(sent_only, stars_log):+.3f}")
78
+ print(f" B+S combined: rho_s={spearman(bs, stars_log):+.3f}")
79
+
80
+ # --- Robustness check 1: leave-one-out ---
81
+ print(f"\n=== Robustness check 1: leave-one-out (GitHub stars) ===")
82
+ rhos = []
83
+ for i in range(len(bs)):
84
+ bs_loo = bs[:i] + bs[i+1:]
85
+ sl_loo = stars_log[:i] + stars_log[i+1:]
86
+ rhos.append(spearman(bs_loo, sl_loo))
87
+ print(f" n iterations: {len(rhos)}")
88
+ print(f" range: [{min(rhos):.3f}, {max(rhos):.3f}]")
89
+ print(f" median: {sorted(rhos)[len(rhos)//2]:.3f}")
90
+ full = spearman(bs, stars_log)
91
+ print(f" full sample: {full:.3f}")
92
+ print(f" max |delta from full|: {max(abs(r-full) for r in rhos):.3f}")
93
+
94
+ # --- Dirichlet bootstrap ---
95
+ print(f"\n=== Dirichlet bootstrap (1000 draws from Dir(3.5,2.5,2.0,2.0)) ===")
96
+ # We perturb the four-factor weights, then re-derive a B+S sub-composite using
97
+ # the perturbed B and S weights renormalized to sum to 1 over {B, S}.
98
+ random.seed(12345)
99
+
100
+ def dirichlet(alphas):
101
+ ys = [random.gammavariate(a, 1.0) for a in alphas]
102
+ s = sum(ys)
103
+ return [y/s for y in ys]
104
+
105
+ rho_samples = []
106
+ for _ in range(1000):
107
+ w_B, w_A, w_S, w_E = dirichlet([3.5, 2.5, 2.0, 2.0])
108
+ # Resampled B+S sub-composite, renormalized over {B, S}
109
+ denom = w_B + w_S
110
+ if denom == 0:
111
+ continue
112
+ wb, ws = w_B / denom, w_S / denom
113
+ bs_pert = [wb * bench_only[i] + ws * sent_only[i] for i in range(len(eligible))]
114
+ rho_samples.append(spearman(bs_pert, stars_log))
115
+ rho_samples.sort()
116
+ lo, hi = rho_samples[25], rho_samples[975] # 95% interval
117
+ median = rho_samples[len(rho_samples)//2]
118
+ print(f" 95% interval: [{lo:.3f}, {hi:.3f}]")
119
+ print(f" median: {median:.3f}")
120
+ print(f" min, max: [{min(rho_samples):.3f}, {max(rho_samples):.3f}]")
121
+ print(f" fraction >0: {sum(1 for r in rho_samples if r>0)/len(rho_samples):.3f}")
122
+
123
+ # --- Inter-factor Spearman on n=50 (Table 2) ---
124
+ print(f"\n=== Table 2: inter-factor Spearman correlations (n=50) ===")
125
+ # Build per-agent factor vectors
126
+ all_agents = [n for n in registry if n in scores]
127
+ Bs, Ss, As, Es = [], [], [], []
128
+ for name in all_agents:
129
+ sub = json.loads(scores[name].get("sub_scores") or "[0.5, 0, 0]")
130
+ Bs.append(sub[0] if len(sub) > 0 else 0.5)
131
+ sent_raw = float(scores[name].get("sentiment") or 0.0)
132
+ Ss.append(max(0.0, min(1.0, (sent_raw + 1.0) / 2.0)))
133
+ As.append(float(scores[name].get("adoption") or 0))
134
+ Es.append(float(scores[name].get("reliability") or 0))
135
+ pairs = [("B-A", Bs, As), ("B-S", Bs, Ss), ("B-E", Bs, Es),
136
+ ("A-S", As, Ss), ("A-E", As, Es), ("S-E", Ss, Es)]
137
+ for label, x, y in pairs:
138
+ print(f" {label}: rho={spearman(x, y):+.3f}")
139
+ print(f" n = {len(all_agents)}")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
reproduce_table3.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproduce Table 3 (cross-factor predictive validity) from the paper.
2
+
3
+ Reads only the released CSVs — no DB, no network.
4
+
5
+ Expected output (paper, n=35):
6
+ GitHub stars (log) rho_s = 0.52 p < 0.01
7
+ VS Code installs (log) rho_s = 0.44 p < 0.05
8
+ Stack Overflow question volume rho_s = 0.49 p < 0.01
9
+
10
+ Usage:
11
+ python reproduce_table3.py [--csv-dir ../data/csv]
12
+ """
13
+
14
+ import argparse
15
+ import csv
16
+ import json
17
+ import math
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Dict, List, Tuple
21
+
22
+
23
+ # ───────────────────────────────────────────────────────────────────────────────
24
+ # Tiny stats utilities (avoid scipy/pandas dependency for reviewer reproducibility)
25
+ # ───────────────────────────────────────────────────────────────────────────────
26
+ def _rank(values: List[float]) -> List[float]:
27
+ """Average-rank a sequence, handling ties."""
28
+ indexed = sorted(enumerate(values), key=lambda kv: kv[1])
29
+ ranks = [0.0] * len(values)
30
+ i = 0
31
+ while i < len(indexed):
32
+ j = i
33
+ while j + 1 < len(indexed) and indexed[j + 1][1] == indexed[i][1]:
34
+ j += 1
35
+ avg = (i + j) / 2.0 + 1.0 # 1-indexed average rank
36
+ for k in range(i, j + 1):
37
+ ranks[indexed[k][0]] = avg
38
+ i = j + 1
39
+ return ranks
40
+
41
+
42
+ def spearman(xs: List[float], ys: List[float]) -> float:
43
+ rx, ry = _rank(xs), _rank(ys)
44
+ n = len(xs)
45
+ mx, my = sum(rx) / n, sum(ry) / n
46
+ num = sum((rx[i] - mx) * (ry[i] - my) for i in range(n))
47
+ dx = math.sqrt(sum((rx[i] - mx) ** 2 for i in range(n)))
48
+ dy = math.sqrt(sum((ry[i] - my) ** 2 for i in range(n)))
49
+ return num / (dx * dy) if dx and dy else float("nan")
50
+
51
+
52
+ def two_sided_p(rho: float, n: int) -> float:
53
+ """Approximate two-sided p-value via the t-distribution approximation."""
54
+ if abs(rho) >= 1.0 or n < 4:
55
+ return 0.0 if abs(rho) >= 1.0 else 1.0
56
+ t = rho * math.sqrt((n - 2) / (1 - rho * rho))
57
+ df = n - 2
58
+ # Survival of |t| via Student-t CDF approx (good enough at df ≥ 10)
59
+ x = df / (df + t * t)
60
+ # Regularized incomplete beta via continued fraction
61
+ return _student_t_sf(t, df) * 2
62
+
63
+
64
+ def _student_t_sf(t: float, df: int) -> float:
65
+ """One-sided survival function of Student-t (|t|)."""
66
+ t = abs(t)
67
+ a = df / 2.0
68
+ b = 0.5
69
+ x = df / (df + t * t)
70
+ return 0.5 * _betai(a, b, x)
71
+
72
+
73
+ def _betai(a: float, b: float, x: float) -> float:
74
+ if x <= 0.0:
75
+ return 0.0
76
+ if x >= 1.0:
77
+ return 1.0
78
+ bt = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
79
+ + a * math.log(x) + b * math.log(1.0 - x))
80
+ if x < (a + 1.0) / (a + b + 2.0):
81
+ return bt * _betacf(a, b, x) / a
82
+ return 1.0 - bt * _betacf(b, a, 1.0 - x) / b
83
+
84
+
85
+ def _betacf(a: float, b: float, x: float, max_iter: int = 200, eps: float = 1e-12) -> float:
86
+ qab, qap, qam = a + b, a + 1.0, a - 1.0
87
+ c, d = 1.0, 1.0 - qab * x / qap
88
+ if abs(d) < 1e-30: d = 1e-30
89
+ d, h = 1.0 / d, 1.0 / d
90
+ for m in range(1, max_iter + 1):
91
+ m2 = 2 * m
92
+ aa = m * (b - m) * x / ((qam + m2) * (a + m2))
93
+ d = 1.0 + aa * d
94
+ if abs(d) < 1e-30: d = 1e-30
95
+ c = 1.0 + aa / c
96
+ if abs(c) < 1e-30: c = 1e-30
97
+ d = 1.0 / d
98
+ h *= d * c
99
+ aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
100
+ d = 1.0 + aa * d
101
+ if abs(d) < 1e-30: d = 1e-30
102
+ c = 1.0 + aa / c
103
+ if abs(c) < 1e-30: c = 1e-30
104
+ d = 1.0 / d
105
+ delta = d * c
106
+ h *= delta
107
+ if abs(delta - 1.0) < eps:
108
+ return h
109
+ return h
110
+
111
+
112
+ # ───────────────────────────────────────────────────────────────────────────────
113
+ # Load inputs
114
+ # ───────────────────────────────────────────────────────────────────────────────
115
+ def load_latest_scores(csv_dir: Path) -> Dict[str, dict]:
116
+ """Latest agent_scores row per agent_name."""
117
+ rows: Dict[str, dict] = {}
118
+ with (csv_dir / "agent_scores.csv").open() as f:
119
+ for r in csv.DictReader(f):
120
+ ts = r["computed_at"]
121
+ cur = rows.get(r["agent_name"])
122
+ if cur is None or ts > cur["computed_at"]:
123
+ rows[r["agent_name"]] = r
124
+ return rows
125
+
126
+
127
+ def load_latest_signals(csv_dir: Path) -> Dict[str, dict]:
128
+ """Latest signals_json row per agent_name (parsed)."""
129
+ rows: Dict[str, dict] = {}
130
+ with (csv_dir / "agent_signals_raw.csv").open() as f:
131
+ for r in csv.DictReader(f):
132
+ ts = r["collected_at"]
133
+ cur = rows.get(r["agent_name"])
134
+ if cur is None or ts > cur["collected_at"]:
135
+ rows[r["agent_name"]] = r
136
+ out: Dict[str, dict] = {}
137
+ for name, row in rows.items():
138
+ try:
139
+ out[name] = json.loads(row["signals_json"])
140
+ except Exception:
141
+ out[name] = {}
142
+ return out
143
+
144
+
145
+ def load_registry(csv_dir: Path) -> Dict[str, dict]:
146
+ out: Dict[str, dict] = {}
147
+ with (csv_dir / "agent_registry.csv").open() as f:
148
+ for r in csv.DictReader(f):
149
+ out[r["name"]] = r
150
+ return out
151
+
152
+
153
+ # ───────────────────────────────────────────────────────────────────────────────
154
+ # Sub-composite construction (paper Section 5.2)
155
+ # ───────────────────────────────────────────────────────────────────────────────
156
+ def benchmark_sentiment_subcomposite(score_row: dict, signals: dict) -> float:
157
+ """Benchmark + Sentiment only, normalized to weights summing to 1.
158
+
159
+ Default paper weights: w_B=0.35, w_S=0.20. Renormalized: 0.6364 B + 0.3636 S.
160
+ Excludes Adoption and Ecosystem to break GitHub-signal circularity.
161
+ """
162
+ sub = json.loads(score_row.get("sub_scores") or "[0.5, 0, 0]")
163
+ b = sub[0] if sub else 0.5
164
+ sent_raw = float(score_row.get("sentiment") or 0.0)
165
+ # Paper S(a) is in [0,1]; raw sentiment is in [-1,1]. Linear remap:
166
+ s_norm = max(0.0, min(1.0, (sent_raw + 1.0) / 2.0))
167
+ return 0.6364 * b + 0.3636 * s_norm
168
+
169
+
170
+ # ───────────────────────────────────────────────────────────────────────────────
171
+ # Main
172
+ # ───────────────────────────────────────────────────────────────────────────────
173
+ def main():
174
+ parser = argparse.ArgumentParser(description=__doc__)
175
+ parser.add_argument("--csv-dir", default="../data/csv",
176
+ help="Directory containing the released CSVs")
177
+ args = parser.parse_args()
178
+ csv_dir = Path(args.csv_dir).resolve()
179
+ if not csv_dir.exists():
180
+ print(f"error: csv-dir {csv_dir} does not exist", file=sys.stderr)
181
+ return 1
182
+
183
+ scores = load_latest_scores(csv_dir)
184
+ signals = load_latest_signals(csv_dir)
185
+ registry = load_registry(csv_dir)
186
+
187
+ # The paper's n=35 subset: agents with a public GitHub repo.
188
+ public_repo_agents = [
189
+ name for name, cfg in registry.items()
190
+ if cfg.get("github_repo")
191
+ ]
192
+ print(f"Agents with public GitHub repos in registry: {len(public_repo_agents)}")
193
+
194
+ # Restrict to those with both a score row and a signals row
195
+ eligible = [a for a in public_repo_agents if a in scores and a in signals]
196
+ print(f"Of those, with scoring and signal data: {len(eligible)}\n")
197
+
198
+ bs = []
199
+ stars_log = []
200
+ installs_log = []
201
+ so_q = []
202
+ for name in eligible:
203
+ s = signals[name]
204
+ bs.append(benchmark_sentiment_subcomposite(scores[name], s))
205
+ stars_log.append(math.log10((s.get("github_stars") or 0) + 1))
206
+ installs_log.append(math.log10((s.get("vscode_installs") or 0) + 1))
207
+ so_q.append(s.get("so_questions") or 0)
208
+
209
+ n = len(bs)
210
+ print(f"{'External signal':<32} {'rho_s':>8} {'p (two-sided)':>15}")
211
+ print("-" * 60)
212
+ for label, ys in [("GitHub stars (log)", stars_log),
213
+ ("VS Code installs (log)", installs_log),
214
+ ("Stack Overflow question volume", so_q)]:
215
+ rho = spearman(bs, ys)
216
+ p = two_sided_p(rho, n)
217
+ print(f"{label:<32} {rho:>8.3f} {p:>15.4g}")
218
+ print(f"\nn = {n}")
219
+ print("\nPaper-reported values (Table 3, n=35):")
220
+ print(" GitHub stars (log) rho_s = 0.52 p < 0.01")
221
+ print(" VS Code installs (log) rho_s = 0.44 p < 0.05 (illustrative; 11/35 non-zero)")
222
+ print(" Stack Overflow question volume rho_s = 0.49 p < 0.01")
223
+ return 0
224
+
225
+
226
+ if __name__ == "__main__":
227
+ sys.exit(main())
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ httpx>=0.27
2
+ apscheduler>=3.10
3
+ python-dotenv>=1.0
4
+ fastapi>=0.110
5
+ uvicorn>=0.29
6
+ atproto>=0.0.55
7
+ vaderSentiment>=3.3
8
+ textblob>=0.18
9
+ numpy>=1.24
10
+ pytrends>=4.9
11
+ arxiv>=2.1
12
+ praw>=7.7
13
+ psycopg2-binary>=2.9
14
+ statsmodels>=0.14
schema.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database schema and connection management.
3
+ Supports SQLite (local dev) and PostgreSQL (production).
4
+
5
+ Set AP_DB_URL in .env to use Postgres; otherwise falls back to SQLite.
6
+ """
7
+
8
+ import os
9
+ import re
10
+ import sqlite3
11
+ from pathlib import Path
12
+ from contextlib import contextmanager
13
+
14
+ # Try importing psycopg2 at module level (available if installed)
15
+ try:
16
+ import psycopg2
17
+ import psycopg2.extras
18
+ _HAS_PG = True
19
+ except ImportError:
20
+ _HAS_PG = False
21
+
22
+ # Lazy detection — check env var at connection time, not import time
23
+ _pg_checked = False
24
+ _USE_PG = False
25
+ _AP_DB_URL = ""
26
+
27
+ def _check_pg():
28
+ global _pg_checked, _USE_PG, _AP_DB_URL
29
+ if _pg_checked:
30
+ return
31
+ _pg_checked = True
32
+ _AP_DB_URL = os.getenv("AP_DB_URL", "")
33
+ if _AP_DB_URL and _HAS_PG:
34
+ _USE_PG = True
35
+ print(f"[db] Using PostgreSQL")
36
+ else:
37
+ from config import DB_PATH as _path
38
+ _USE_PG = False
39
+ print(f"[db] Using SQLite at {_path}")
40
+
41
+
42
+ _pg_conn_params = None
43
+
44
+ def get_connection():
45
+ """Get a database connection (SQLite or Postgres). Always call conn.close() when done."""
46
+ _check_pg()
47
+ if _USE_PG:
48
+ global _pg_conn_params
49
+ if _pg_conn_params is None:
50
+ db_url = _AP_DB_URL
51
+ m = re.match(r'postgresql://([^:]+):(.+)@([^:]+):(\d+)/(\S+)', db_url)
52
+ if m:
53
+ _pg_conn_params = dict(
54
+ dbname=m.group(5).strip(), user=m.group(1).strip(),
55
+ password=m.group(2), host=m.group(3).strip(),
56
+ port=int(m.group(4))
57
+ )
58
+ else:
59
+ _pg_conn_params = dict(dsn=db_url)
60
+ conn = psycopg2.connect(**_pg_conn_params, connect_timeout=10)
61
+ conn.autocommit = True
62
+ return _PgConnectionWrapper(conn)
63
+ else:
64
+ from config import DB_PATH
65
+ conn = sqlite3.connect(DB_PATH)
66
+ conn.row_factory = sqlite3.Row
67
+ conn.execute("PRAGMA journal_mode=WAL")
68
+ conn.execute("PRAGMA foreign_keys=ON")
69
+ return conn
70
+
71
+
72
+ class _PgConnectionWrapper:
73
+ """Wraps psycopg2 connection to provide sqlite3-like interface."""
74
+
75
+ def __init__(self, conn):
76
+ self._conn = conn
77
+ self._conn.autocommit = True
78
+
79
+ def execute(self, sql, params=None):
80
+ """Execute SQL, converting SQLite syntax to Postgres on the fly."""
81
+ sql = _adapt_sql(sql)
82
+ cur = self._conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
83
+ try:
84
+ cur.execute(sql, params or [])
85
+ except Exception as e:
86
+ # Don't raise on benign errors (e.g., table already exists)
87
+ if 'already exists' in str(e) or 'duplicate key' in str(e):
88
+ self._conn.rollback()
89
+ self._conn.autocommit = True
90
+ return _EmptyCursor()
91
+ raise
92
+ return _PgCursorWrapper(cur)
93
+
94
+ def executemany(self, sql, params_list):
95
+ """Execute SQL with many parameter sets."""
96
+ sql = _adapt_sql(sql)
97
+ cur = self._conn.cursor()
98
+ for params in params_list:
99
+ try:
100
+ cur.execute(sql, params)
101
+ except Exception as e:
102
+ if 'already exists' not in str(e) and 'duplicate key' not in str(e):
103
+ raise
104
+ return cur
105
+
106
+ def executescript(self, sql):
107
+ """Execute multiple SQL statements (Postgres doesn't have executescript)."""
108
+ sql = _adapt_sql(sql)
109
+ # Split on semicolons but handle edge cases
110
+ statements = [s.strip() for s in sql.split(';') if s.strip()]
111
+ cur = self._conn.cursor()
112
+ for stmt in statements:
113
+ if not stmt:
114
+ continue
115
+ try:
116
+ cur.execute(stmt)
117
+ except Exception as e:
118
+ if 'already exists' not in str(e):
119
+ print(f"[db] SQL warning: {str(e).split(chr(10))[0][:80]}")
120
+ self._conn.rollback()
121
+ self._conn.autocommit = True
122
+ return cur
123
+
124
+ def commit(self):
125
+ pass # autocommit mode
126
+
127
+ def rollback(self):
128
+ pass
129
+
130
+ def close(self):
131
+ try:
132
+ self._conn.close()
133
+ except Exception:
134
+ pass
135
+
136
+ def __enter__(self):
137
+ return self
138
+
139
+ def __exit__(self, *args):
140
+ self.close()
141
+
142
+ def __del__(self):
143
+ self.close()
144
+
145
+
146
+ class _PgCursorWrapper:
147
+ """Wraps psycopg2 cursor to return dict-like rows (like sqlite3.Row)."""
148
+
149
+ def __init__(self, cur):
150
+ self._cur = cur
151
+
152
+ @property
153
+ def description(self):
154
+ return self._cur.description
155
+
156
+ def fetchall(self):
157
+ try:
158
+ rows = self._cur.fetchall()
159
+ # Convert RealDictRow to support both dict and index access
160
+ return [_DictRow(r) for r in rows]
161
+ except psycopg2.ProgrammingError:
162
+ return []
163
+
164
+ def fetchone(self):
165
+ try:
166
+ r = self._cur.fetchone()
167
+ return _DictRow(r) if r else None
168
+ except psycopg2.ProgrammingError:
169
+ return None
170
+
171
+ @property
172
+ def rowcount(self):
173
+ return self._cur.rowcount
174
+
175
+
176
+ class _DictRow:
177
+ """Row that supports both dict-style and index-style access."""
178
+
179
+ def __init__(self, data):
180
+ self._data = dict(data) if data else {}
181
+ self._keys = list(self._data.keys())
182
+
183
+ def __getitem__(self, key):
184
+ if isinstance(key, int):
185
+ return self._data[self._keys[key]]
186
+ return self._data[key]
187
+
188
+ def __contains__(self, key):
189
+ return key in self._data
190
+
191
+ def keys(self):
192
+ return self._keys
193
+
194
+ def __iter__(self):
195
+ return iter(self._data.values())
196
+
197
+ def __len__(self):
198
+ return len(self._data)
199
+
200
+
201
+ class _EmptyCursor:
202
+ """Dummy cursor for failed-but-benign operations."""
203
+
204
+ def fetchall(self):
205
+ return []
206
+
207
+ def fetchone(self):
208
+ return None
209
+
210
+ @property
211
+ def rowcount(self):
212
+ return 0
213
+
214
+
215
+ def _adapt_sql(sql):
216
+ """Convert SQLite-specific SQL to Postgres-compatible SQL."""
217
+ # ? → %s (parameter placeholders)
218
+ sql = sql.replace('?', '%s')
219
+ # INSERT OR REPLACE → INSERT ... ON CONFLICT DO NOTHING (safe default)
220
+ # INSERT OR IGNORE → INSERT ... ON CONFLICT DO NOTHING
221
+ if 'INSERT OR REPLACE' in sql.upper():
222
+ sql = sql.replace('INSERT OR REPLACE INTO', 'INSERT INTO')
223
+ sql = sql.replace('insert or replace into', 'INSERT INTO')
224
+ # Add ON CONFLICT DO NOTHING at the end (before any trailing whitespace)
225
+ sql = sql.rstrip().rstrip(';') + ' ON CONFLICT DO NOTHING'
226
+ if 'INSERT OR IGNORE' in sql.upper():
227
+ sql = sql.replace('INSERT OR IGNORE INTO', 'INSERT INTO')
228
+ sql = sql.replace('insert or ignore into', 'INSERT INTO')
229
+ sql = sql.rstrip().rstrip(';') + ' ON CONFLICT DO NOTHING'
230
+ # AUTOINCREMENT → remove
231
+ sql = sql.replace('AUTOINCREMENT', '')
232
+ # INTEGER PRIMARY KEY → SERIAL PRIMARY KEY
233
+ sql = sql.replace('INTEGER PRIMARY KEY', 'SERIAL PRIMARY KEY')
234
+ # datetime('now') → NOW()
235
+ sql = sql.replace("datetime('now')", "NOW()")
236
+ sql = sql.replace("(datetime('now'))", "NOW()")
237
+ # REAL → DOUBLE PRECISION (only in CREATE statements)
238
+ if 'CREATE TABLE' in sql.upper():
239
+ sql = sql.replace(' REAL', ' DOUBLE PRECISION')
240
+ # GROUP_CONCAT → STRING_AGG
241
+ sql = sql.replace('GROUP_CONCAT(', 'STRING_AGG(')
242
+ return sql
243
+
244
+
245
+ @contextmanager
246
+ def db():
247
+ """Context manager for database connections."""
248
+ _check_pg()
249
+ conn = get_connection()
250
+ try:
251
+ yield conn
252
+ if not _USE_PG:
253
+ conn.commit()
254
+ except Exception:
255
+ if not _USE_PG:
256
+ conn.rollback()
257
+ raise
258
+ finally:
259
+ conn.close()
260
+
261
+
262
+ def init_db():
263
+ """Initialize database tables."""
264
+ _check_pg()
265
+ if _USE_PG:
266
+ # For Postgres, tables should already exist from migration
267
+ # Just verify connectivity
268
+ conn = get_connection()
269
+ try:
270
+ result = conn.execute("SELECT COUNT(*) FROM models")
271
+ row = result.fetchone()
272
+ count = row[0] if row else 0
273
+ print(f"[db] Postgres connected, {count} models in DB")
274
+ except Exception:
275
+ print("[db] Postgres connected, initializing tables...")
276
+ _init_pg_tables(conn)
277
+ conn.close()
278
+ else:
279
+ # SQLite: create tables from schema
280
+ with db() as conn:
281
+ conn.executescript(_SQLITE_SCHEMA)
282
+ from config import DB_PATH as _dbp
283
+ print(f"[db] Initialized SQLite at {_dbp}")
284
+
285
+
286
+ def _init_pg_tables(conn):
287
+ """Create tables in Postgres (used only if migration hasn't run)."""
288
+ # Convert SQLite schema to Postgres and execute
289
+ pg_schema = _adapt_sql(_SQLITE_SCHEMA)
290
+ conn.executescript(pg_schema)
291
+
292
+
293
+ _SQLITE_SCHEMA = """
294
+ CREATE TABLE IF NOT EXISTS models (
295
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
296
+ slug TEXT UNIQUE NOT NULL,
297
+ display_name TEXT NOT NULL,
298
+ provider TEXT NOT NULL,
299
+ tier TEXT,
300
+ active INTEGER DEFAULT 1,
301
+ created_at TEXT DEFAULT (datetime('now'))
302
+ );
303
+
304
+ CREATE TABLE IF NOT EXISTS openrouter_signals (
305
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
306
+ model_slug TEXT NOT NULL,
307
+ context_length INTEGER,
308
+ prompt_price REAL,
309
+ completion_price REAL,
310
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
311
+ FOREIGN KEY (model_slug) REFERENCES models(slug)
312
+ );
313
+
314
+ CREATE TABLE IF NOT EXISTS github_signals (
315
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
316
+ model_slug TEXT NOT NULL,
317
+ repo TEXT NOT NULL,
318
+ stars INTEGER,
319
+ forks INTEGER,
320
+ open_issues INTEGER,
321
+ pushed_at TEXT,
322
+ commits_24h INTEGER,
323
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
324
+ FOREIGN KEY (model_slug) REFERENCES models(slug)
325
+ );
326
+
327
+ CREATE TABLE IF NOT EXISTS twitter_signals (
328
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
329
+ model_slug TEXT NOT NULL,
330
+ query TEXT NOT NULL,
331
+ tweet_id TEXT,
332
+ text TEXT,
333
+ author TEXT,
334
+ likes INTEGER DEFAULT 0,
335
+ retweets INTEGER DEFAULT 0,
336
+ replies INTEGER DEFAULT 0,
337
+ created_at TEXT,
338
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
339
+ FOREIGN KEY (model_slug) REFERENCES models(slug)
340
+ );
341
+
342
+ CREATE TABLE IF NOT EXISTS reddit_signals (
343
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
344
+ model_slug TEXT NOT NULL,
345
+ subreddit TEXT NOT NULL,
346
+ post_id TEXT UNIQUE,
347
+ title TEXT,
348
+ score INTEGER,
349
+ num_comments INTEGER,
350
+ upvote_ratio REAL,
351
+ created_at TEXT,
352
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
353
+ FOREIGN KEY (model_slug) REFERENCES models(slug)
354
+ );
355
+
356
+ CREATE TABLE IF NOT EXISTS huggingface_signals (
357
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
358
+ model_slug TEXT NOT NULL,
359
+ hf_model_id TEXT NOT NULL,
360
+ downloads_30d INTEGER,
361
+ downloads_7d INTEGER,
362
+ likes INTEGER,
363
+ trending_score REAL,
364
+ trending_rank INTEGER,
365
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
366
+ FOREIGN KEY (model_slug) REFERENCES models(slug)
367
+ );
368
+
369
+ CREATE TABLE IF NOT EXISTS hn_signals (
370
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
371
+ model_slug TEXT NOT NULL,
372
+ story_id TEXT NOT NULL,
373
+ title TEXT,
374
+ score INTEGER,
375
+ num_comments INTEGER,
376
+ author TEXT,
377
+ created_at TEXT,
378
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
379
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
380
+ UNIQUE(story_id, model_slug)
381
+ );
382
+
383
+ CREATE TABLE IF NOT EXISTS latency_signals (
384
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
385
+ model_slug TEXT NOT NULL,
386
+ provider_name TEXT,
387
+ provider_tag TEXT,
388
+ latency_30m REAL,
389
+ throughput_30m REAL,
390
+ uptime_5m REAL,
391
+ uptime_30m REAL,
392
+ uptime_1d REAL,
393
+ endpoint_count INTEGER,
394
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
395
+ FOREIGN KEY (model_slug) REFERENCES models(slug)
396
+ );
397
+
398
+ CREATE TABLE IF NOT EXISTS sdk_signals (
399
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
400
+ package TEXT NOT NULL,
401
+ registry TEXT NOT NULL,
402
+ provider TEXT NOT NULL,
403
+ downloads_day INTEGER,
404
+ downloads_week INTEGER,
405
+ downloads_month INTEGER,
406
+ collected_at TEXT NOT NULL DEFAULT (datetime('now'))
407
+ );
408
+
409
+ CREATE TABLE IF NOT EXISTS stackoverflow_signals (
410
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
411
+ model_slug TEXT NOT NULL,
412
+ question_id INTEGER NOT NULL,
413
+ title TEXT,
414
+ score INTEGER,
415
+ answer_count INTEGER,
416
+ view_count INTEGER,
417
+ is_answered INTEGER,
418
+ tags TEXT,
419
+ created_at TEXT,
420
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
421
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
422
+ UNIQUE(question_id, model_slug)
423
+ );
424
+
425
+ CREATE TABLE IF NOT EXISTS devto_signals (
426
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
427
+ model_slug TEXT NOT NULL,
428
+ article_id INTEGER NOT NULL,
429
+ title TEXT,
430
+ reactions INTEGER,
431
+ comments INTEGER,
432
+ reading_time INTEGER,
433
+ tags TEXT,
434
+ published_at TEXT,
435
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
436
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
437
+ UNIQUE(article_id, model_slug)
438
+ );
439
+
440
+ CREATE TABLE IF NOT EXISTS lobsters_signals (
441
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
442
+ model_slug TEXT NOT NULL,
443
+ short_id TEXT NOT NULL,
444
+ title TEXT,
445
+ url TEXT,
446
+ score INTEGER,
447
+ flags INTEGER,
448
+ comment_count INTEGER,
449
+ tags TEXT,
450
+ created_at TEXT,
451
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
452
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
453
+ UNIQUE(short_id, model_slug)
454
+ );
455
+
456
+ CREATE TABLE IF NOT EXISTS bluesky_signals (
457
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
458
+ model_slug TEXT NOT NULL,
459
+ query TEXT NOT NULL,
460
+ post_uri TEXT NOT NULL,
461
+ text TEXT,
462
+ author TEXT,
463
+ likes INTEGER DEFAULT 0,
464
+ reposts INTEGER DEFAULT 0,
465
+ replies INTEGER DEFAULT 0,
466
+ created_at TEXT,
467
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
468
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
469
+ UNIQUE(post_uri, model_slug)
470
+ );
471
+
472
+ CREATE TABLE IF NOT EXISTS github_discussions_signals (
473
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
474
+ model_slug TEXT NOT NULL,
475
+ discussion_id INTEGER NOT NULL,
476
+ title TEXT,
477
+ body_preview TEXT,
478
+ comments INTEGER DEFAULT 0,
479
+ reactions INTEGER DEFAULT 0,
480
+ author TEXT,
481
+ repo TEXT,
482
+ created_at TEXT,
483
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
484
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
485
+ UNIQUE(discussion_id, model_slug)
486
+ );
487
+
488
+ CREATE TABLE IF NOT EXISTS mastodon_signals (
489
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
490
+ model_slug TEXT NOT NULL,
491
+ post_uri TEXT NOT NULL,
492
+ instance TEXT,
493
+ text TEXT,
494
+ author TEXT,
495
+ favourites INTEGER DEFAULT 0,
496
+ boosts INTEGER DEFAULT 0,
497
+ replies INTEGER DEFAULT 0,
498
+ created_at TEXT,
499
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
500
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
501
+ UNIQUE(post_uri, model_slug)
502
+ );
503
+
504
+ CREATE TABLE IF NOT EXISTS v2ex_signals (
505
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
506
+ model_slug TEXT NOT NULL,
507
+ topic_id INTEGER NOT NULL,
508
+ title TEXT,
509
+ content_preview TEXT,
510
+ replies INTEGER DEFAULT 0,
511
+ node TEXT,
512
+ author TEXT,
513
+ created_at TEXT,
514
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
515
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
516
+ UNIQUE(topic_id, model_slug)
517
+ );
518
+
519
+ CREATE TABLE IF NOT EXISTS lemmy_signals (
520
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
521
+ model_slug TEXT NOT NULL,
522
+ post_ap_id TEXT NOT NULL,
523
+ community TEXT,
524
+ instance TEXT,
525
+ title TEXT,
526
+ body_preview TEXT,
527
+ score INTEGER DEFAULT 0,
528
+ comments INTEGER DEFAULT 0,
529
+ upvotes INTEGER DEFAULT 0,
530
+ downvotes INTEGER DEFAULT 0,
531
+ created_at TEXT,
532
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
533
+ FOREIGN KEY (model_slug) REFERENCES models(slug),
534
+ UNIQUE(post_ap_id, model_slug)
535
+ );
536
+
537
+ CREATE TABLE IF NOT EXISTS google_trends_signals (
538
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
539
+ model_slug TEXT NOT NULL,
540
+ search_term TEXT,
541
+ interest INTEGER,
542
+ timestamp TEXT,
543
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
544
+ UNIQUE(model_slug, search_term, timestamp)
545
+ );
546
+
547
+ CREATE TABLE IF NOT EXISTS arxiv_signals (
548
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
549
+ model_slug TEXT NOT NULL,
550
+ paper_id TEXT NOT NULL,
551
+ title TEXT,
552
+ abstract_preview TEXT,
553
+ categories TEXT,
554
+ authors_count INTEGER,
555
+ published_at TEXT,
556
+ collected_at TEXT NOT NULL DEFAULT (datetime('now')),
557
+ UNIQUE(paper_id, model_slug)
558
+ );
559
+
560
+ CREATE TABLE IF NOT EXISTS lmsys_signals (
561
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
562
+ model_slug TEXT NOT NULL,
563
+ lmsys_name TEXT,
564
+ elo_rating REAL,
565
+ num_battles INTEGER,
566
+ ci_lower REAL,
567
+ ci_upper REAL,
568
+ collected_at TEXT NOT NULL DEFAULT (datetime('now'))
569
+ );
570
+
571
+ CREATE TABLE IF NOT EXISTS devtools_signals (
572
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
573
+ tool_type TEXT NOT NULL,
574
+ tool_id TEXT NOT NULL,
575
+ tool_name TEXT,
576
+ provider TEXT,
577
+ installs INTEGER,
578
+ rating REAL,
579
+ rating_count INTEGER,
580
+ collected_at TEXT NOT NULL DEFAULT (datetime('now'))
581
+ );
582
+
583
+ CREATE INDEX IF NOT EXISTS idx_or_model_time ON openrouter_signals(model_slug, collected_at);
584
+ CREATE INDEX IF NOT EXISTS idx_gh_model_time ON github_signals(model_slug, collected_at);
585
+ CREATE INDEX IF NOT EXISTS idx_tw_model_time ON twitter_signals(model_slug, collected_at);
586
+ CREATE INDEX IF NOT EXISTS idx_rd_model_time ON reddit_signals(model_slug, collected_at);
587
+ CREATE INDEX IF NOT EXISTS idx_hf_model_time ON huggingface_signals(model_slug, collected_at);
588
+ CREATE INDEX IF NOT EXISTS idx_hn_model_time ON hn_signals(model_slug, collected_at);
589
+ CREATE INDEX IF NOT EXISTS idx_lat_model_time ON latency_signals(model_slug, collected_at);
590
+ CREATE INDEX IF NOT EXISTS idx_sdk_pkg_time ON sdk_signals(package, collected_at);
591
+ CREATE INDEX IF NOT EXISTS idx_bs_model_time ON bluesky_signals(model_slug, collected_at);
592
+ CREATE INDEX IF NOT EXISTS idx_so_model_time ON stackoverflow_signals(model_slug, collected_at);
593
+ CREATE INDEX IF NOT EXISTS idx_dt_model_time ON devto_signals(model_slug, collected_at);
594
+ CREATE INDEX IF NOT EXISTS idx_lb_model_time ON lobsters_signals(model_slug, collected_at);
595
+ CREATE INDEX IF NOT EXISTS idx_ghd_model_time ON github_discussions_signals(model_slug, collected_at);
596
+ CREATE INDEX IF NOT EXISTS idx_mst_model_time ON mastodon_signals(model_slug, collected_at);
597
+ CREATE INDEX IF NOT EXISTS idx_v2x_model_time ON v2ex_signals(model_slug, collected_at);
598
+ CREATE INDEX IF NOT EXISTS idx_lmy_model_time ON lemmy_signals(model_slug, collected_at);
599
+ """
sentiment.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multi-layered NLP sentiment scoring engine.
3
+
4
+ Produces 12 sentiment dimensions per text, aggregated into composite scores per model.
5
+ Designed for time-series analysis of LLM perception across social/developer platforms.
6
+
7
+ Architecture:
8
+ Layer 1 — Lexicon-based (VADER + TextBlob): fast, interpretable, baseline
9
+ Layer 2 — Transformer-based (FinBERT / distilbert-sst2): nuanced financial + general sentiment
10
+ Layer 3 — Domain-specific aspect extraction: LLM performance dimensions
11
+ Layer 4 — Engagement-weighted scoring: likes/upvotes amplify signal strength
12
+ Layer 5 — Time-series indicators: momentum, volatility, z-scores
13
+ """
14
+
15
+ import re
16
+ import math
17
+ import logging
18
+ from dataclasses import dataclass, field, asdict
19
+ from datetime import datetime, timezone
20
+
21
+ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
22
+ from textblob import TextBlob
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # ── Layer 1: Lexicon Scorers ──────────────────────────────────────────────────
27
+
28
+ _vader = SentimentIntensityAnalyzer()
29
+
30
+ def vader_scores(text: str) -> dict:
31
+ """VADER: optimised for social media (handles emojis, slang, caps, punctuation)."""
32
+ vs = _vader.polarity_scores(text)
33
+ return {
34
+ "vader_compound": vs["compound"], # -1 to +1 overall
35
+ "vader_pos": vs["pos"], # 0-1 proportion positive
36
+ "vader_neg": vs["neg"], # 0-1 proportion negative
37
+ "vader_neu": vs["neu"], # 0-1 proportion neutral
38
+ }
39
+
40
+ def textblob_scores(text: str) -> dict:
41
+ """TextBlob: pattern-based, captures polarity + subjectivity."""
42
+ blob = TextBlob(text)
43
+ return {
44
+ "tb_polarity": blob.sentiment.polarity, # -1 to +1
45
+ "tb_subjectivity": blob.sentiment.subjectivity, # 0 (objective) to 1 (subjective)
46
+ }
47
+
48
+ # ── Layer 2: Transformer Scorers ─────────────────────────────────────────────
49
+
50
+ _finbert = None
51
+ _distilbert = None
52
+
53
+ def _get_finbert():
54
+ global _finbert
55
+ if _finbert is None:
56
+ from transformers import pipeline
57
+ _finbert = pipeline("sentiment-analysis", model="ProsusAI/finbert",
58
+ truncation=True, max_length=512)
59
+ logger.info("[sentiment] FinBERT loaded")
60
+ return _finbert
61
+
62
+ def _get_distilbert():
63
+ global _distilbert
64
+ if _distilbert is None:
65
+ from transformers import pipeline
66
+ _distilbert = pipeline("sentiment-analysis",
67
+ model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
68
+ truncation=True, max_length=512)
69
+ logger.info("[sentiment] DistilBERT-SST2 loaded")
70
+ return _distilbert
71
+
72
+ def finbert_scores(text: str) -> dict:
73
+ """FinBERT: financial sentiment (positive / negative / neutral)."""
74
+ try:
75
+ result = _get_finbert()(text[:512])[0]
76
+ label = result["label"].lower() # positive, negative, neutral
77
+ score = result["score"]
78
+ # Convert to -1 to +1 scale
79
+ if label == "positive":
80
+ finbert_val = score
81
+ elif label == "negative":
82
+ finbert_val = -score
83
+ else:
84
+ finbert_val = 0.0
85
+ return {"finbert_sentiment": finbert_val, "finbert_confidence": score}
86
+ except Exception as e:
87
+ logger.debug("finbert error: %s", e)
88
+ return {"finbert_sentiment": 0.0, "finbert_confidence": 0.0}
89
+
90
+ def distilbert_scores(text: str) -> dict:
91
+ """DistilBERT SST-2: general positive/negative sentiment."""
92
+ try:
93
+ result = _get_distilbert()(text[:512])[0]
94
+ label = result["label"] # POSITIVE or NEGATIVE
95
+ score = result["score"]
96
+ val = score if label == "POSITIVE" else -score
97
+ return {"distilbert_sentiment": val, "distilbert_confidence": score}
98
+ except Exception as e:
99
+ logger.debug("distilbert error: %s", e)
100
+ return {"distilbert_sentiment": 0.0, "distilbert_confidence": 0.0}
101
+
102
+
103
+ # ── Layer 3: Domain-Specific Aspect Extraction ────────────────────────────────
104
+ #
105
+ # Instead of general "positive/negative", detect LLM-specific dimensions:
106
+ # - Performance perception (speed, quality, accuracy)
107
+ # - Reliability perception (downtime, errors, hallucinations)
108
+ # - Cost perception (expensive, cheap, value)
109
+ # - Innovation perception (breakthrough, impressive, game-changer)
110
+ # - Adoption signal (using, switched to, migrated, building with)
111
+ # - Complaint signal (broken, worse, degraded, disappointed)
112
+
113
+ ASPECT_LEXICONS = {
114
+ "performance": {
115
+ "positive": ["fast", "quick", "impressive", "excellent", "powerful", "capable",
116
+ "accurate", "smart", "intelligent", "brilliant", "amazing",
117
+ "best", "superior", "outperforms", "crushes", "dominates",
118
+ "state-of-the-art", "sota", "benchmark", "top", "leading"],
119
+ "negative": ["slow", "dumb", "stupid", "terrible", "awful", "poor",
120
+ "inaccurate", "wrong", "garbage", "useless", "mediocre",
121
+ "worse", "inferior", "disappointing", "underwhelming"],
122
+ },
123
+ "reliability": {
124
+ "positive": ["reliable", "stable", "consistent", "dependable", "solid",
125
+ "robust", "uptime", "available", "works well"],
126
+ "negative": ["hallucinate", "hallucination", "unreliable", "inconsistent",
127
+ "broken", "crash", "error", "bug", "fail", "down", "outage",
128
+ "degraded", "throttled", "timeout", "429", "500", "rate limit"],
129
+ },
130
+ "cost": {
131
+ "positive": ["cheap", "affordable", "value", "cost-effective", "free",
132
+ "fair price", "reasonable", "bargain", "open source", "open-source"],
133
+ "negative": ["expensive", "overpriced", "costly", "ripoff", "pricey",
134
+ "not worth", "waste of money", "too much", "$$$"],
135
+ },
136
+ "innovation": {
137
+ "positive": ["breakthrough", "revolutionary", "game-changer", "innovative",
138
+ "novel", "impressive", "exciting", "next-gen", "frontier",
139
+ "leap", "paradigm", "unprecedented"],
140
+ "negative": ["incremental", "nothing new", "overhyped", "hype", "marketing",
141
+ "same old", "rehash", "disappointed"],
142
+ },
143
+ "adoption": {
144
+ "positive": ["using", "switched to", "migrated", "building with", "deployed",
145
+ "adopted", "integrated", "love using", "recommend", "try it",
146
+ "my go-to", "daily driver", "production"],
147
+ "negative": ["stopped using", "switched away", "abandoned", "dropped",
148
+ "going back to", "unsubscribed", "cancelled"],
149
+ },
150
+ }
151
+
152
+ def aspect_scores(text: str) -> dict:
153
+ """Score text along domain-specific LLM perception dimensions."""
154
+ text_lower = text.lower()
155
+ scores = {}
156
+
157
+ for aspect, lexicon in ASPECT_LEXICONS.items():
158
+ pos_count = sum(1 for w in lexicon["positive"] if w in text_lower)
159
+ neg_count = sum(1 for w in lexicon["negative"] if w in text_lower)
160
+ total = pos_count + neg_count
161
+
162
+ if total == 0:
163
+ scores[f"aspect_{aspect}"] = 0.0
164
+ scores[f"aspect_{aspect}_intensity"] = 0.0
165
+ else:
166
+ # Score: -1 (all negative mentions) to +1 (all positive)
167
+ scores[f"aspect_{aspect}"] = (pos_count - neg_count) / total
168
+ # Intensity: how much does this text discuss this aspect? (0 = not at all)
169
+ scores[f"aspect_{aspect}_intensity"] = min(total / 5.0, 1.0)
170
+
171
+ return scores
172
+
173
+
174
+ # ── Layer 4: Engagement-Weighted Scoring ──────────────────────────────────────
175
+
176
+ def engagement_weight(likes: int = 0, reposts: int = 0, replies: int = 0,
177
+ score: int = 0, views: int = 0) -> float:
178
+ """
179
+ Compute an engagement multiplier that amplifies high-signal posts.
180
+ Uses log-scale to prevent viral posts from dominating.
181
+ Returns a weight in [0.1, 5.0] range.
182
+ """
183
+ raw = (likes or 0) + (reposts or 0) * 2 + (replies or 0) * 0.5 + (score or 0) + (views or 0) * 0.01
184
+ if raw <= 0:
185
+ return 0.1
186
+ # log-scale: 1 engagement → 0.1, 10 → ~1.1, 100 → ~2.1, 1000 → ~3.1
187
+ return min(0.1 + math.log10(max(raw, 1)), 5.0)
188
+
189
+
190
+ # ── Composite Scorer ──────────────────────────────────────────────────────────
191
+
192
+ @dataclass
193
+ class SentimentResult:
194
+ """All sentiment dimensions for a single text."""
195
+ # Layer 1: Lexicon
196
+ vader_compound: float = 0.0
197
+ vader_pos: float = 0.0
198
+ vader_neg: float = 0.0
199
+ vader_neu: float = 0.0
200
+ tb_polarity: float = 0.0
201
+ tb_subjectivity: float = 0.0
202
+
203
+ # Layer 2: Transformer
204
+ finbert_sentiment: float = 0.0
205
+ finbert_confidence: float = 0.0
206
+ distilbert_sentiment: float = 0.0
207
+ distilbert_confidence: float = 0.0
208
+
209
+ # Layer 3: Aspects
210
+ aspect_performance: float = 0.0
211
+ aspect_performance_intensity: float = 0.0
212
+ aspect_reliability: float = 0.0
213
+ aspect_reliability_intensity: float = 0.0
214
+ aspect_cost: float = 0.0
215
+ aspect_cost_intensity: float = 0.0
216
+ aspect_innovation: float = 0.0
217
+ aspect_innovation_intensity: float = 0.0
218
+ aspect_adoption: float = 0.0
219
+ aspect_adoption_intensity: float = 0.0
220
+
221
+ # Layer 4: Engagement
222
+ engagement_weight: float = 0.1
223
+
224
+ # Composites
225
+ composite_sentiment: float = 0.0 # weighted average of all sentiment layers
226
+ composite_quality: float = 0.0 # performance + reliability aspects
227
+ composite_buzz: float = 0.0 # innovation + adoption + engagement
228
+
229
+ def to_dict(self) -> dict:
230
+ return asdict(self)
231
+
232
+
233
+ def score_text(text: str, likes: int = 0, reposts: int = 0, replies: int = 0,
234
+ score: int = 0, views: int = 0,
235
+ use_transformers: bool = True) -> SentimentResult:
236
+ """
237
+ Score a single text across all sentiment dimensions.
238
+
239
+ Args:
240
+ text: the post/title text
241
+ likes/reposts/replies/score/views: engagement metrics from the platform
242
+ use_transformers: if False, skip FinBERT + DistilBERT (faster, CPU-only)
243
+
244
+ Returns:
245
+ SentimentResult with all 20+ dimensions populated
246
+ """
247
+ if not text or not text.strip():
248
+ return SentimentResult()
249
+
250
+ # Clean text
251
+ text = re.sub(r'https?://\S+', '', text) # remove URLs
252
+ text = re.sub(r'@\w+', '', text) # remove @mentions
253
+ text = text.strip()
254
+ if len(text) < 5:
255
+ return SentimentResult()
256
+
257
+ # Layer 1
258
+ v = vader_scores(text)
259
+ t = textblob_scores(text)
260
+
261
+ # Layer 2
262
+ f = {"finbert_sentiment": 0.0, "finbert_confidence": 0.0}
263
+ d = {"distilbert_sentiment": 0.0, "distilbert_confidence": 0.0}
264
+ if use_transformers:
265
+ f = finbert_scores(text)
266
+ d = distilbert_scores(text)
267
+
268
+ # Layer 3
269
+ a = aspect_scores(text)
270
+
271
+ # Layer 4
272
+ ew = engagement_weight(likes, reposts, replies, score, views)
273
+
274
+ # ── Composites ────────────────────────────────────────────────────────
275
+
276
+ # Composite sentiment: weighted blend of all sentiment signals
277
+ # VADER is best for social media, FinBERT for financial framing, DistilBERT for general
278
+ composite_sentiment = (
279
+ v["vader_compound"] * 0.30 +
280
+ t["tb_polarity"] * 0.10 +
281
+ f["finbert_sentiment"] * 0.35 +
282
+ d["distilbert_sentiment"] * 0.25
283
+ )
284
+
285
+ # Composite quality perception: performance + reliability aspects
286
+ perf = a.get("aspect_performance", 0) * a.get("aspect_performance_intensity", 0)
287
+ reli = a.get("aspect_reliability", 0) * a.get("aspect_reliability_intensity", 0)
288
+ composite_quality = (perf + reli) / 2
289
+
290
+ # Composite buzz: innovation + adoption + engagement amplification
291
+ inno = a.get("aspect_innovation", 0) * a.get("aspect_innovation_intensity", 0)
292
+ adop = a.get("aspect_adoption", 0) * a.get("aspect_adoption_intensity", 0)
293
+ composite_buzz = (inno + adop) / 2 * ew
294
+
295
+ return SentimentResult(
296
+ **v, **t, **f, **d, **a,
297
+ engagement_weight=ew,
298
+ composite_sentiment=composite_sentiment,
299
+ composite_quality=composite_quality,
300
+ composite_buzz=composite_buzz,
301
+ )