File size: 12,245 Bytes
306ab7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""
Agent Scoring V2 — based on real collected signals only.

Produces a composite score per agent from:
  - Benchmark performance (SWE-bench, GAIA, WebArena, HumanEval+) — 35%
  - Adoption signals (GitHub stars, downloads, VS Code installs) — 25%
  - Community sentiment (from NLP pipeline) — 20%
  - Ecosystem health (contributors, issue close rate, freshness) — 20%

Time-series: each hourly scoring run reads the latest signals and produces
one data point. The time-series builds naturally from repeated runs —
no simulation needed.
"""

import math
import json
import logging
from datetime import datetime, timezone
from collections import defaultdict
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).parent.parent))
from db.schema import get_connection, db

logger = logging.getLogger(__name__)


def _safe_log(x):
    if x is None or x <= 0: return 0
    return math.log10(x + 1)


def init_agent_tables():
    with db() as conn:
        conn.executescript("""
        CREATE TABLE IF NOT EXISTS agent_scores (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            agent_name TEXT NOT NULL,
            category TEXT NOT NULL,
            provider TEXT,
            score REAL,
            sentiment REAL,
            mention_count INTEGER,
            adoption REAL,
            reliability REAL,
            sub_scores TEXT,
            computed_at TEXT NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_as_agent ON agent_scores(agent_name, category, computed_at);

        CREATE TABLE IF NOT EXISTS agent_forecasts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            agent_name TEXT NOT NULL,
            category TEXT NOT NULL,
            step INTEGER NOT NULL,
            score REAL,
            lower_80 REAL,
            upper_80 REAL,
            forecast_time TEXT NOT NULL
        );
        """)


# Agent → provider mapping (57 agents)
PROVIDERS = {
    "Claude Code": "Anthropic", "Cursor": "Anysphere", "OpenAI Codex": "OpenAI",
    "GitHub Copilot": "GitHub", "Windsurf": "Codeium", "Gemini CLI": "Google",
    "Cline": "Cline", "Devin": "Cognition", "Replit Agent": "Replit",
    "OpenHands": "OpenHands", "SWE-agent": "Princeton",
    "Aider": "Aider", "Bolt": "StackBlitz", "Continue": "Continue",
    "Amazon Q Developer": "Amazon", "Tabnine": "Tabnine",
    "Sourcegraph Cody": "Sourcegraph", "Supermaven": "Supermaven",
    "OpenAI Deep Research": "OpenAI", "Perplexity Research": "Perplexity",
    "Manus": "Manus AI", "NotebookLM": "Google", "Kimi Researcher": "Moonshot",
    "Genspark": "Genspark", "Gemini Deep Research": "Google",
    "OpenClaw": "Anthropic", "Operator": "OpenAI",
    "Browser Use": "Browser Use", "Wingman": "Wingman", "NanoBot": "NanoBot",
    "Adept ACT-2": "Adept", "Multion": "Multion",
    "LangGraph": "LangChain", "CrewAI": "CrewAI",
    "Microsoft AutoGen": "Microsoft", "OpenAI Agents SDK": "OpenAI",
    "Claude MCP": "Anthropic", "LlamaIndex": "LlamaIndex", "PydanticAI": "Pydantic",
    "Semantic Kernel": "Microsoft", "DSPy": "Stanford", "Haystack": "deepset",
    "Composio": "Composio",
    "ChatGPT": "OpenAI", "Claude": "Anthropic", "AutoGPT": "AutoGPT", "MetaGPT": "MetaGPT",
    "Lovable": "Lovable", "v0": "Vercel", "Pieces": "Pieces",
}

# Agent → categories mapping (57 agents)
CATEGORIES = {
    "Claude Code": ["coding","copilot","swe","tool","memory","enterprise"],
    "Cursor": ["coding","copilot","enterprise"],
    "OpenAI Codex": ["coding","swe"],
    "GitHub Copilot": ["coding","copilot","enterprise"],
    "Windsurf": ["coding","copilot"],
    "Gemini CLI": ["coding","copilot"],
    "Cline": ["coding","copilot"],
    "Devin": ["coding","swe","memory"],
    "Replit Agent": ["coding"],
    "OpenHands": ["coding","swe"],
    "SWE-agent": ["swe"],
    "Aider": ["coding","swe"],
    "Bolt": ["coding","general"],
    "Continue": ["coding","copilot"],
    "Amazon Q Developer": ["coding","copilot","enterprise"],
    "Tabnine": ["coding","copilot","enterprise"],
    "Sourcegraph Cody": ["coding","copilot","enterprise"],
    "Supermaven": ["coding","copilot"],
    "OpenAI Deep Research": ["research","enterprise"],
    "Perplexity Research": ["research"],
    "Manus": ["research","general","browser"],
    "NotebookLM": ["research","data"],
    "Kimi Researcher": ["research"],
    "Genspark": ["research"],
    "Gemini Deep Research": ["research"],
    "OpenClaw": ["browser","general"],
    "Operator": ["browser","consumer"],
    "Browser Use": ["browser"],
    "Wingman": ["browser","general"],
    "NanoBot": ["browser"],
    "Adept ACT-2": ["browser"],
    "Multion": ["browser"],
    "LangGraph": ["multi"],
    "CrewAI": ["multi","enterprise"],
    "Microsoft AutoGen": ["multi","enterprise"],
    "OpenAI Agents SDK": ["multi"],
    "Claude MCP": ["multi","tool"],
    "LlamaIndex": ["multi"],
    "PydanticAI": ["multi"],
    "Semantic Kernel": ["multi","enterprise"],
    "DSPy": ["multi","research"],
    "Haystack": ["multi","enterprise"],
    "Composio": ["multi","tool"],
    "ChatGPT": ["general","consumer","data"],
    "Claude": ["general","data"],
    "AutoGPT": ["general"],
    "MetaGPT": ["general"],
    "Lovable": ["coding","general"],
    "v0": ["coding","general"],
    "Pieces": ["coding","copilot"],
}


def compute_agent_scores():
    conn = get_connection()
    init_agent_tables()
    now_ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

    # Load latest signals for each agent, with carry-forward for missing data.
    # When an API call fails, the latest row may have zeros for GitHub signals.
    # We carry forward the last known good value to avoid score spikes.
    GITHUB_KEYS = {"github_stars", "github_forks", "github_open_issues", "github_watchers",
                   "github_contributors", "issue_close_rate", "days_since_update"}

    agent_signals = {}
    for r in conn.execute("""
        SELECT agent_name, signals_json FROM agent_signals_raw
        WHERE id IN (SELECT MAX(id) FROM agent_signals_raw GROUP BY agent_name)
    """).fetchall():
        latest = json.loads(r[1]) if r[1] else {}

        # If GitHub signals are missing (API failure), carry forward from previous row
        if latest.get("github_stars", 0) == 0 and any(k in latest for k in ("bench_swebench", "bench_humaneval", "sentiment_avg")):
            try:
                prev_rows = conn.execute("""
                    SELECT signals_json FROM agent_signals_raw
                    WHERE agent_name = ? AND id < (SELECT MAX(id) FROM agent_signals_raw WHERE agent_name = ?)
                    ORDER BY id DESC LIMIT 5
                """, (r[0], r[0])).fetchall()
                for prev_r in prev_rows:
                    prev = json.loads(prev_r[0]) if prev_r[0] else {}
                    if prev.get("github_stars", 0) > 0:
                        for k in GITHUB_KEYS:
                            if k in prev and latest.get(k, 0) == 0:
                                latest[k] = prev[k]
                        break
            except Exception:
                pass

        agent_signals[r[0]] = latest

    if not agent_signals:
        logger.warning("[agent_scoring_v2] no signals found — run agent_signals collector first")
        conn.close()
        return 0

    # Compute composite scores
    all_scores = {}
    for agent_name, signals in agent_signals.items():
        # ── 1. Benchmark (35%) — normalized to 0-1 ──
        bench_scores = []
        for key in ["bench_swebench", "bench_gaia", "bench_webarena", "bench_humaneval", "bench_tau"]:
            if key in signals:
                bench_scores.append(signals[key] / 100.0)
        benchmark = sum(bench_scores) / len(bench_scores) if bench_scores else 0.5  # default mid if no benchmarks

        # ── 2. Adoption (25%) — log-normalized ──
        stars = _safe_log(signals.get("github_stars", 0)) / 5.5  # 100k stars ≈ 1.0
        downloads = max(
            _safe_log(signals.get("pypi_downloads_week", 0)) / 7,
            _safe_log(signals.get("npm_downloads_week", 0)) / 7,
        )
        vscode = _safe_log(signals.get("vscode_installs", 0)) / 8  # 100M ≈ 1.0
        adoption = min(stars * 0.4 + downloads * 0.35 + vscode * 0.25, 1.0)

        # ── 3. Community sentiment (20%) ──
        sentiment = signals.get("sentiment_avg", 0.02)
        sentiment_score = max(min(sentiment * 2.5 + 0.5, 1.0), 0.0)
        mention_count = signals.get("sentiment_count", 0)

        # ── 4. Ecosystem health (20%) ──
        contributors = min(_safe_log(signals.get("github_contributors", 0)) / 3, 1.0)
        close_rate = signals.get("issue_close_rate", 0.5)
        freshness = max(1.0 - (signals.get("days_since_update", 30) / 60), 0.0)
        vscode_rating = (signals.get("vscode_rating", 3.5) - 2.0) / 3.0  # 2-5 → 0-1
        ecosystem = contributors * 0.3 + close_rate * 0.2 + freshness * 0.3 + max(min(vscode_rating, 1.0), 0.0) * 0.2

        # ── Composite ──
        composite = (
            benchmark * 0.35 +
            adoption * 0.25 +
            sentiment_score * 0.20 +
            ecosystem * 0.20
        )
        composite = max(min(composite, 1.0), 0.05)

        all_scores[agent_name] = {
            "score": composite,
            "benchmark": benchmark,
            "adoption": adoption,
            "sentiment": sentiment,
            "sentiment_score": sentiment_score,
            "ecosystem": ecosystem,
            "mention_count": mention_count,
            "sub_scores": [benchmark, adoption, ecosystem],
        }

    # Write scores for each agent in each category
    for agent_name, sc in all_scores.items():
        categories = CATEGORIES.get(agent_name, ["general"])
        provider = PROVIDERS.get(agent_name, "Unknown")

        for cat in categories:
            conn.execute("""
                INSERT INTO agent_scores
                    (agent_name, category, provider, score, sentiment,
                     mention_count, adoption, reliability, sub_scores, computed_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, (
                agent_name, cat, provider,
                sc["score"], sc["sentiment"], sc["mention_count"],
                sc["adoption"], sc["ecosystem"],
                json.dumps(sc["sub_scores"]),
                now_ts,
            ))

    # Forecast: mean-reversion toward cross-sectional mean
    cs_mean = sum(s["score"] for s in all_scores.values()) / len(all_scores) if all_scores else 0.5
    for agent_name, sc in all_scores.items():
        categories = CATEGORIES.get(agent_name, ["general"])
        for cat in categories:
            # Get recent history
            hist = conn.execute("""
                SELECT score FROM agent_scores
                WHERE agent_name = ? AND category = ?
                ORDER BY computed_at DESC LIMIT 10
            """, (agent_name, cat)).fetchall()
            scores = [r[0] for r in hist if r[0] is not None]

            if len(scores) < 2:
                base = sc["score"]
                vol = 0.015
            else:
                base = scores[0]
                diffs = [scores[i] - scores[i+1] for i in range(len(scores)-1)]
                vol = max(sum(abs(d) for d in diffs) / len(diffs), 0.008)

            for step in range(1, 73):
                # Mean-revert toward cross-sectional mean
                fc = base + 0.003 * (cs_mean - base) * step
                fc = max(0.05, min(0.98, fc))
                spread = vol * math.sqrt(step) * 1.28

                conn.execute("""
                    INSERT OR REPLACE INTO agent_forecasts
                        (agent_name, category, step, score, lower_80, upper_80, forecast_time)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                """, (agent_name, cat, step, fc, fc - spread, fc + spread, now_ts))

    conn.commit()
    conn.close()
    logger.info("[agent_scoring_v2] scored %d agents", len(all_scores))
    return len(all_scores)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
    n = compute_agent_scores()
    print(f"Scored {n} agents")