Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add SWE-bench and LiveCodeBench benchmark source sync to model comparison

Adam Eivy58bdc2a6434b
diff --git a/client/src/components/models/ModelComparison.jsx b/client/src/components/models/ModelComparison.jsx
index 4644803ae5..6af2ad7863 100644
--- a/client/src/components/models/ModelComparison.jsx
+++ b/client/src/components/models/ModelComparison.jsx
@@ -28,7 +28,7 @@ import {
getModelComparison,
importModelComparison,
discoverComparisonModels,
- syncArtificialAnalysis,
+ syncBenchmarkSource,
} from '../../services/apiModelComparison';
import Modal from '../ui/Modal';
import toast from '../ui/Toast';
@@ -107,6 +107,7 @@ export default function ModelComparison() {
const [scenario, setScenario] = useState({ input: 10000, output: 500, reasoning: 0, tasks: 100 });
const [modelSearch, setModelSearch] = useState('');
const [syncModalOpen, setSyncModalOpen] = useState(false);
+ const [syncSource, setSyncSource] = useState('artificial-analysis');
const [syncKey, setSyncKey] = useState('');
const [syncStatus, setSyncStatus] = useState('');
const [syncError, setSyncError] = useState('');
@@ -284,11 +285,23 @@ export default function ModelComparison() {
.finally(() => setBusy(false));
};
- const handleSyncAA = () => {
+ // A newer server answers with the full source list; an older one offered
+ // only Artificial Analysis, so fall back to it rather than offering a sync
+ // the server would reject.
+ const syncSources = catalog?.syncSources?.length
+ ? catalog.syncSources
+ : [{ id: 'artificial-analysis', label: 'Artificial Analysis', requiresKey: true }];
+ const selectedSyncSource = syncSources.find(s => s.id === syncSource) || syncSources[0];
+
+ const handleSync = () => {
setSyncing(true);
setSyncError('');
- setSyncStatus('Connecting to Artificial Analysis and syncing models…');
- syncArtificialAnalysis({ ...(syncKey.trim() ? { apiKey: syncKey.trim() } : {}) }, { silent: true })
+ setSyncStatus(`Connecting to ${selectedSyncSource.label} and syncing…`);
+ syncBenchmarkSource(
+ selectedSyncSource.id,
+ { ...(selectedSyncSource.requiresKey && syncKey.trim() ? { apiKey: syncKey.trim() } : {}) },
+ { silent: true }
+ )
.then(res => {
// The sync is done and the catalog is reloading behind it — the dialog
// has nothing left to ask for, so it closes itself and the result is
@@ -320,11 +333,12 @@ export default function ModelComparison() {
setSyncStatus('');
};
- // A configured key makes the dialog a pure speed bump — sync straight away and
- // only prompt when there is nothing stored to sync with.
- const startSyncAA = () => {
- if (catalog?.artificialAnalysisKeyConfigured) {
- handleSyncAA();
+ // A configured key makes the Artificial Analysis dialog a pure speed bump —
+ // sync straight away and only prompt when there is nothing stored to sync
+ // with. Every other source needs no key and opens the dialog to be picked.
+ const startSync = () => {
+ if (selectedSyncSource.id === 'artificial-analysis' && catalog?.artificialAnalysisKeyConfigured) {
+ handleSync();
return;
}
setSyncError('');
@@ -642,11 +656,11 @@ export default function ModelComparison() {
<button
type="button"
className="inline-flex items-center gap-2 px-3 py-1.5 text-xs bg-port-card border border-port-border rounded-lg hover:border-port-accent disabled:opacity-50 transition-colors"
- onClick={startSyncAA}
+ onClick={startSync}
disabled={syncing}
>
<CloudDownload size={14} aria-hidden="true" className={`text-port-accent-text ${syncing ? 'animate-pulse' : ''}`} />
- {syncing ? 'Syncing…' : 'Sync from Artificial Analysis'}
+ {syncing ? 'Syncing…' : 'Sync benchmark data'}
</button>
<button
type="button"
@@ -683,30 +697,61 @@ export default function ModelComparison() {
>
<div className="bg-port-card border border-port-border rounded-xl shadow-2xl p-5 space-y-4">
<h3 id="aa-sync-title" className="text-base font-semibold tracking-tight">
- Sync Artificial Analysis data
+ Sync benchmark data
</h3>
- <p className="text-xs text-port-text-muted leading-relaxed">
- Fetch the latest benchmark evaluations, pricing, response times, and reasoning effort measurements from the
- Artificial Analysis Free API. {catalog.artificialAnalysisKeyConfigured
- ? 'The saved key did not work — enter a replacement below.'
- : 'This install has no key yet, so enter one below.'} A key entered here is saved privately after
- authentication succeeds, and later syncs run without asking. Manage it in Settings → Credentials.
- </p>
<div className="space-y-1.5">
- <label htmlFor="aa-api-key" className="text-xs font-medium text-port-text-muted">
- Artificial Analysis API Key
+ <label htmlFor="sync-source" className="text-xs font-medium text-port-text-muted">
+ Source
</label>
- <input
- id="aa-api-key"
- type="password"
- placeholder="aa-…"
- aria-label="Artificial Analysis API Key"
- className="w-full bg-port-bg text-port-text border border-port-border rounded-lg p-2.5 text-sm font-mono"
- value={syncKey}
- onChange={e => setSyncKey(e.target.value)}
+ <select
+ id="sync-source"
+ aria-label="Sync source"
+ className="w-full bg-port-bg text-port-text border border-port-border rounded-lg p-2.5 text-sm"
+ value={selectedSyncSource.id}
+ onChange={e => { setSyncSource(e.target.value); setSyncError(''); }}
disabled={syncing}
- />
+ >
+ {syncSources.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
+ </select>
</div>
+ {selectedSyncSource.id === 'artificial-analysis' ? (
+ <>
+ <p className="text-xs text-port-text-muted leading-relaxed">
+ Fetch the latest benchmark evaluations, pricing, response times, and reasoning effort measurements from the
+ Artificial Analysis Free API. {catalog.artificialAnalysisKeyConfigured
+ ? 'The saved key did not work — enter a replacement below.'
+ : 'This install has no key yet, so enter one below.'} A key entered here is saved privately after
+ authentication succeeds, and later syncs run without asking. Manage it in Settings → Credentials.
+ </p>
+ <div className="space-y-1.5">
+ <label htmlFor="aa-api-key" className="text-xs font-medium text-port-text-muted">
+ Artificial Analysis API Key
+ </label>
+ <input
+ id="aa-api-key"
+ type="password"
+ placeholder="aa-…"
+ aria-label="Artificial Analysis API Key"
+ className="w-full bg-port-bg text-port-text border border-port-border rounded-lg p-2.5 text-sm font-mono"
+ value={syncKey}
+ onChange={e => setSyncKey(e.target.value)}
+ disabled={syncing}
+ />
+ </div>
+ </>
+ ) : selectedSyncSource.id === 'swebench' ? (
+ <p className="text-xs text-port-text-muted leading-relaxed">
+ Fetch the SWE-bench leaderboard results — resolved-task pass@1 percentages and agent-run costs per instance,
+ grouped by agent scaffold across the Verified, Lite, Multilingual and Multimodal tracks. No key needed; the
+ leaderboard page is fetched directly and each run is kept as its own observation.
+ </p>
+ ) : (
+ <p className="text-xs text-port-text-muted leading-relaxed">
+ Fetch LiveCodeBench's published generation-split results and aggregate pass@1 per model across the full
+ date window. No key needed; picking up newly added problems starts a new window series rather than mixing
+ different ones.
+ </p>
+ )}
{syncStatus && <p className="text-xs text-port-accent-text">{syncStatus}</p>}
{syncError && <p role="alert" className="text-xs text-port-error">{syncError}</p>}
<div className="flex justify-end gap-2 pt-2">
@@ -721,8 +766,8 @@ export default function ModelComparison() {
<button
type="button"
className="px-4 py-1.5 text-sm bg-port-accent text-port-on-accent rounded-lg font-medium hover:opacity-90 disabled:opacity-50"
- onClick={handleSyncAA}
- disabled={syncing || (!syncKey.trim() && !catalog.artificialAnalysisKeyConfigured)}
+ onClick={handleSync}
+ disabled={syncing || (selectedSyncSource.requiresKey && !syncKey.trim() && !catalog.artificialAnalysisKeyConfigured)}
>
{syncing ? 'Syncing…' : 'Start Sync'}
</button>
diff --git a/client/src/components/models/ModelComparison.test.jsx b/client/src/components/models/ModelComparison.test.jsx
index 554cedb0a4..d5bbd0cb1a 100644
--- a/client/src/components/models/ModelComparison.test.jsx
+++ b/client/src/components/models/ModelComparison.test.jsx
@@ -10,7 +10,7 @@ vi.mock('../../services/apiModelComparison', () => ({
getModelComparison: vi.fn(),
importModelComparison: vi.fn(),
discoverComparisonModels: vi.fn(),
- syncArtificialAnalysis: vi.fn(),
+ syncBenchmarkSource: vi.fn(),
}));
vi.mock('../../services/apiProviders', () => ({ getProviders: vi.fn().mockResolvedValue({ providers: [{ id: 'example', name: 'Example research', models: ['example-model', 'other-model'] }] }) }));
vi.mock('../../services/apiAgents', () => ({ getCosSchedule: vi.fn(), updateCosTaskInterval: vi.fn(), triggerCosOnDemandTask: vi.fn() }));
@@ -121,32 +121,32 @@ it('connects reasoning effort points with line and allows toggling line style an
});
it('prompts for a key when none is stored and closes the modal once the sync lands', async () => {
- api.syncArtificialAnalysis.mockResolvedValue({ success: true, observations: 636, total: 636 });
+ api.syncBenchmarkSource.mockResolvedValue({ success: true, observations: 636, total: 636 });
render(<MemoryRouter><ModelComparison /></MemoryRouter>);
await act(async () => {});
- fireEvent.click(screen.getByRole('button', { name: /Sync from Artificial Analysis/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
expect(screen.getByLabelText(/Artificial Analysis API Key/i)).toBeTruthy();
expect(screen.getByRole('button', { name: 'Start Sync' })).toBeDisabled();
fireEvent.change(screen.getByLabelText(/Artificial Analysis API Key/i), { target: { value: 'test-key-123' } });
fireEvent.click(screen.getByRole('button', { name: 'Start Sync' }));
- await waitFor(() => expect(api.syncArtificialAnalysis).toHaveBeenCalledWith({ apiKey: 'test-key-123' }, { silent: true }));
+ await waitFor(() => expect(api.syncBenchmarkSource).toHaveBeenCalledWith('artificial-analysis', { apiKey: 'test-key-123' }, { silent: true }));
await waitFor(() => expect(screen.queryByLabelText(/Artificial Analysis API Key/i)).toBeNull());
});
it('syncs straight away without a key prompt when one is already configured', async () => {
api.getModelComparison.mockResolvedValue({ schemaVersion: 1, observations: [observation], inventory: [], artificialAnalysisKeyConfigured: true });
- api.syncArtificialAnalysis.mockResolvedValue({ success: true, observations: 636, total: 636 });
+ api.syncBenchmarkSource.mockResolvedValue({ success: true, observations: 636, total: 636 });
render(<MemoryRouter><ModelComparison /></MemoryRouter>);
await act(async () => {});
- fireEvent.click(screen.getByRole('button', { name: /Sync from Artificial Analysis/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
- await waitFor(() => expect(api.syncArtificialAnalysis).toHaveBeenCalledWith({}, { silent: true }));
+ await waitFor(() => expect(api.syncBenchmarkSource).toHaveBeenCalledWith('artificial-analysis', {}, { silent: true }));
expect(screen.queryByLabelText(/Artificial Analysis API Key/i)).toBeNull();
});
@@ -154,28 +154,64 @@ it('discards a typed key when the prompt is cancelled', async () => {
render(<MemoryRouter><ModelComparison /></MemoryRouter>);
await act(async () => {});
- fireEvent.click(screen.getByRole('button', { name: /Sync from Artificial Analysis/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
fireEvent.change(screen.getByLabelText(/Artificial Analysis API Key/i), { target: { value: 'abandoned-key' } });
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
- fireEvent.click(screen.getByRole('button', { name: /Sync from Artificial Analysis/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
expect(screen.getByLabelText(/Artificial Analysis API Key/i)).toHaveValue('');
- expect(api.syncArtificialAnalysis).not.toHaveBeenCalled();
+ expect(api.syncBenchmarkSource).not.toHaveBeenCalled();
});
it('falls back to the key prompt when a sync with the stored key is rejected', async () => {
api.getModelComparison.mockResolvedValue({ schemaVersion: 1, observations: [observation], inventory: [], artificialAnalysisKeyConfigured: true });
- api.syncArtificialAnalysis.mockRejectedValue(new Error('Artificial Analysis API failed (401): Unauthorized'));
+ api.syncBenchmarkSource.mockRejectedValue(new Error('Artificial Analysis API failed (401): Unauthorized'));
render(<MemoryRouter><ModelComparison /></MemoryRouter>);
await act(async () => {});
- fireEvent.click(screen.getByRole('button', { name: /Sync from Artificial Analysis/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
await screen.findByText(/Artificial Analysis API failed \(401\)/);
expect(screen.getByLabelText(/Artificial Analysis API Key/i)).toBeTruthy();
});
+it('offers the server sync sources and syncs a keyless source without a key prompt', async () => {
+ api.getModelComparison.mockResolvedValue({
+ schemaVersion: 1, observations: [observation], inventory: [],
+ syncSources: [
+ { id: 'artificial-analysis', label: 'Artificial Analysis', requiresKey: true },
+ { id: 'swebench', label: 'SWE-bench leaderboards', requiresKey: false },
+ { id: 'livecodebench', label: 'LiveCodeBench', requiresKey: false },
+ ],
+ });
+ api.syncBenchmarkSource.mockResolvedValue({ success: true, observations: 2, total: 2 });
+
+ render(<MemoryRouter><ModelComparison /></MemoryRouter>);
+ await act(async () => {});
+
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
+ fireEvent.change(screen.getByLabelText('Sync source'), { target: { value: 'swebench' } });
+
+ // A keyless source needs no key input, and Start Sync is enabled without one.
+ expect(screen.queryByLabelText(/Artificial Analysis API Key/i)).toBeNull();
+ expect(screen.getByRole('button', { name: 'Start Sync' })).not.toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Start Sync' }));
+ await waitFor(() => expect(api.syncBenchmarkSource).toHaveBeenCalledWith('swebench', {}, { silent: true }));
+ await waitFor(() => expect(screen.queryByLabelText('Sync source')).toBeNull());
+});
+
+it('falls back to Artificial Analysis only when the server offers no source list', async () => {
+ render(<MemoryRouter><ModelComparison /></MemoryRouter>);
+ await act(async () => {});
+
+ fireEvent.click(screen.getByRole('button', { name: /Sync benchmark data/i }));
+ const sourceSelect = screen.getByLabelText('Sync source');
+ expect(sourceSelect).toHaveValue('artificial-analysis');
+ expect(sourceSelect.querySelectorAll('option')).toHaveLength(1);
+});
+
it('opens on a log cost axis and scopes the chart to the providers models', async () => {
const scoped = [
{ ...observation, id: 'mine', model: 'claude-opus-5', effort: 'max', quality: metric(54), costPerTask: metric(4.2) },
diff --git a/client/src/services/apiModelComparison.js b/client/src/services/apiModelComparison.js
index 1f2afda5af..a5919dadb1 100644
--- a/client/src/services/apiModelComparison.js
+++ b/client/src/services/apiModelComparison.js
@@ -8,6 +8,6 @@ export const discoverComparisonModels = (providerId, options) => request('/provi
method: 'POST', body: JSON.stringify({ providerId }), ...options,
});
-export const syncArtificialAnalysis = (data, options) => request('/providers/comparison/sync-aa', {
+export const syncBenchmarkSource = (source, data, options) => request(`/providers/comparison/sync/${source}`, {
method: 'POST', body: JSON.stringify(data || {}), ...options,
});
diff --git a/docs/API.md b/docs/API.md
index 03d286abc0..f9d24a29b3 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -763,7 +763,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/standardize` | App PM2 standardizer |
| `/api/stacker-news`, `/api/x` | Social integrations |
| `/api/model-personality` | LLM personality tests |
-| `/api/providers/comparison` | Provider/model comparison catalog — discover, import, and Artificial Analysis sync (see [MODEL-COMPARISON.md](./MODEL-COMPARISON.md)) |
+| `/api/providers/comparison` | Provider/model comparison catalog — discover, import, and benchmark source sync (Artificial Analysis, SWE-bench, LiveCodeBench; see [MODEL-COMPARISON.md](./MODEL-COMPARISON.md)) |
| `/api/browser` | Managed Chromium |
| `/api/creative-commission` | Creative commissions |
| `/api/midi-runtime` | MIDI runtime |
diff --git a/docs/MODEL-COMPARISON.md b/docs/MODEL-COMPARISON.md
index e1fe1fa8b1..864e5edeef 100644
--- a/docs/MODEL-COMPARISON.md
+++ b/docs/MODEL-COMPARISON.md
@@ -31,7 +31,8 @@ Endpoints (relative to the configured PortOS API origin):
- `GET /api/providers/comparison` → `{ schemaVersion: 1, observations, inventory }`. Inventory contains only provider IDs/names/types, discovery capability, model IDs, supported effort labels, and each model's `catalogModel` — the public benchmark-index name the endpoint ID normalizes to, or `null`. No credentials or endpoints. `catalogModel` is derived server-side by `catalogSlugForProviderModel`, so the coverage list and the chart's default scope cannot disagree about whether a model has evidence; never re-derive it in the client.
- `POST /api/providers/comparison/discover` with `{ "providerId": "example-provider" }` → current `{ providerId, models: [{ model, efforts }] }`. Explicit discovery only; failures remain visible.
- `POST /api/providers/comparison/import` accepts `{ schemaVersion: 1, observations: [...] }`. GET's `inventory` field is not an import field. The UI also accepts this JSON as a file.
-- `POST /api/providers/comparison/sync-aa` with optional `{ "apiKey": "..." }` → fetches model metadata directly from the Artificial Analysis API, normalizes observations, and imports them. The API-reported `intelligence_index_version` determines observation IDs, benchmark labels and metric methodology. Missing/invalid versions, malformed/empty pages, or a version change during pagination fail before import; new benchmark versions never overwrite older-version evidence.
+- `POST /api/providers/comparison/sync-aa` with optional `{ "apiKey": "..." }` → fetches model metadata directly from the Artificial Analysis API, normalizes observations, and imports them. The API-reported `intelligence_index_version` determines observation IDs, benchmark labels and metric methodology. Missing/invalid versions, malformed/empty pages, or a version change during pagination fail before import; new benchmark versions never overwrite older-version evidence. Back-compat alias for the generalized source sync below.
+- `POST /api/providers/comparison/sync/:source` with an optional `{ "apiKey": "..." }` (used only by `artificial-analysis`) → the same import contract for any declared source. `GET` reports the selectable list as `syncSources: [{ id, label, requiresKey }]`. Built-in sources: `artificial-analysis`, `swebench`, and `livecodebench` — see "Benchmark source sync" below.
Use the actual configured origin, optional authentication and trusted local HTTP mirror described in `PORTS.md`; do not hardcode an install address. Never put credentials in a catalog, command argument, source URL, output report or repository file. Existing authenticated PortOS tooling can perform the POST. Direct local file replacement bypasses import preservation checks and is not the research workflow.
@@ -62,6 +63,14 @@ Then POST the validated JSON using the normal authenticated API client and GET t
Partial source refreshes cannot erase old evidence. To retract incorrect data, an operator must deliberately repair the local catalog while preserving a recovery copy; autonomous research does not delete observations. A future schema migration must explicitly preserve installed evidence and source provenance.
+## Benchmark source sync
+
+Artificial Analysis is not the only source the page can pull: **Models → Comparison → Sync benchmark data** offers every source `GET /api/providers/comparison` lists as `syncSources`. Each sync is an explicit user action (or an explicitly scheduled task run) — never a boot-time or background call. All sources share the import contract above: server-side fetch, schema validation, and per-metric merge keyed by stable observation ID. No seed ships for any synced source — the fetch happens on demand into this install's catalog, so nothing is bundled or redistributed by PortOS itself; the source's own publication terms govern the data it serves.
+
+- **SWE-bench** (`swebench`) — fetches [swebench.com](https://www.swebench.com/) and reads the `leaderboard-data` JSON the site renders from. Each scored-track submission becomes one observation: benchmark `SWE-bench <track> (pass@1, <agent>)` — the scaffold is part of the name, and several submissions one model+agent pair carries stay distinct — with the resolved-task percentage as quality and the mean USD cost per instance as `costPerTask`. The observation ID keys on the submission folder, so leaderboard row order never changes an identity and a re-submission under the same folder refreshes in place. The site's `Test` tab (a system-test playground, not a scored leaderboard) and rows without an attributable model identity (`Undisclosed`, `Multi`-vendor lineups) stay absent rather than becoming a fake series. No key required.
+- **LiveCodeBench** (`livecodebench`) — fetches LiveCodeBench's published `performances_generation.json` and aggregates pass@1 per model across the full date window. The window span is part of the benchmark name — `LiveCodeBench (generation, pass@1, <start> to <end>)` — so a sync that picks up newly added problems starts a new series instead of mixing different windows. The serving family (`model_style`) names the provider where it is unambiguous; unrecognized families stay `Unknown` with the style in notes. Costs, throughput and quota are not published by this source. No key required.
+
+
## Selectable axes and free Zen coverage
Both axes offer benchmark score, cost per task, speed (output tokens/s), response time (seconds), and input/output token prices. `xAxis` and `yAxis` are bookmarkable and saved with the other chart settings. Changing either clears zoom bounds and selects linear scaling. The X scale can still be logarithmic; zero prices are excluded on log scale and counted explicitly. Missing selected metrics stay in the evidence table, whose quality/cost columns retain their original units regardless of chart axes. Speed and latency remain measurements of their source workloads, not the selected quality benchmark.
@@ -101,8 +110,8 @@ Research checked September 6, 2026. These are candidate adapters and metrics, no
| Skill | Primary source / metrics | Interpretation and ingestion requirements |
| --- | --- | --- |
-| Software coding: repository work | [SWE-bench](https://www.swebench.com/): resolved-task percentage, Verified / Pro / Multimodal tracks | Record track, dataset revision, agent scaffold, tools, budget and model effort. A full agent's result is not a model-only score; keep different scaffolds separate. Public leaderboard/repository artifacts are candidates for a reviewed snapshot importer. |
-| Software coding: code generation | [LiveCodeBench](https://livecodebench.github.io/): generation, self-repair, execution and test-output prediction | Its date-windowed contest problems address contamination. Pin release, date window and sampling/pass@k configuration; do not compare different windows. Public code/data and leaderboard are linked by the project. |
+| Software coding: repository work | [SWE-bench](https://www.swebench.com/): resolved-task percentage, Verified / Pro / Multimodal tracks | Record track, dataset revision, agent scaffold, tools, budget and model effort. A full agent's result is not a model-only score; keep different scaffolds separate. The live leaderboard sync (`swebench`) imports the scored tracks on demand; the site's `Test` tab stays excluded. |
+| Software coding: code generation | [LiveCodeBench](https://livecodebench.github.io/): generation, self-repair, execution and test-output prediction | Its date-windowed contest problems address contamination. Pin release, date window and sampling/pass@k configuration; do not compare different windows. The live sync (`livecodebench`) imports the generation split aggregated per model with the window span in the benchmark name; the other splits are candidates for the same adapter. |
| Creative writing | [EQ-Bench Creative Writing v3](https://eqbench.com/creative_writing.html): rubric score, Elo, repetition and slop frequency | LLM-judged results carry judge/prompt bias. Elo is relative to a participant pool; repetition/slop are diagnostics, not a substitute for human editorial judgment. Pin judge version, rubric and leaderboard snapshot. Inspect linked repository data rather than scraping an empty JavaScript-rendered table. |
| Image analysis | [MMMU](https://mmmu-benchmark.github.io/): multimodal subject accuracy; MMMU-Pro as a separate benchmark | Measures image-grounded academic understanding, not image generation quality. Pin original/Pro, split, image resolution, prompting and tool access. Report aggregate plus subject coverage; model support for images alone is not an accuracy measurement. |
| Tool use | [Berkeley Function Calling Leaderboard V4](https://gorilla.cs.berkeley.edu/leaderboard.html): function-calling and agentic task accuracy | Preserve version and category (single/parallel calls, multi-turn, agentic) with tool schemas and execution setup. A syntactically valid call does not prove task success. Use project-published evaluation artifacts and keep different categories distinct. |
diff --git a/server/routes/modelComparison.js b/server/routes/modelComparison.js
index 6f629fe007..4d22e55eba 100644
--- a/server/routes/modelComparison.js
+++ b/server/routes/modelComparison.js
@@ -3,11 +3,21 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, modelComparisonImportSchema, modelComparisonDiscoverySchema, modelComparisonSyncSchema } from '../lib/validation.js';
import { getModelComparison, importModelComparison } from '../services/modelComparison.js';
import { hasArtificialAnalysisKey, syncArtificialAnalysisCatalog } from '../services/artificialAnalysis.js';
+import { syncSwebenchCatalog } from '../services/swebenchBenchmarks.js';
+import { syncLiveCodeBenchCatalog } from '../services/livecodebenchBenchmarks.js';
import { canRefreshModels } from '../lib/aiToolkit/internal/modelFetchers.js';
import { effortLevelsForProvider, filterSelectableModels } from '../lib/providerModels.js';
import { catalogSlugForProviderModel } from '../lib/comparisonModelScope.js';
import { applyModelAccess } from '../lib/aiToolkit/internal/modelAccess.js';
+// The sync sources the page offers, keyed by the route parameter. The AA key
+// presence travels separately on GET — never the key itself.
+const BENCHMARK_SYNC_SOURCES = Object.freeze({
+ 'artificial-analysis': { label: 'Artificial Analysis', requiresKey: true, sync: syncArtificialAnalysisCatalog },
+ swebench: { label: 'SWE-bench leaderboards', requiresKey: false, sync: () => syncSwebenchCatalog() },
+ livecodebench: { label: 'LiveCodeBench', requiresKey: false, sync: () => syncLiveCodeBenchCatalog() },
+});
+
// The endpoint id plus the benchmark-index name it normalizes to. Both travel,
// because the page needs them for different things: the executable id labels
// the row, and the slug is what a catalog observation is keyed by. Deriving the
@@ -40,6 +50,7 @@ export function createModelComparisonRoutes(providerService) {
...catalog, inventory, availableModels: [...new Set(inventory.flatMap(p => p.models.map(m => m.catalogModel).filter(Boolean)))].sort(),
// Presence only, never the key — the page skips its key prompt when set.
artificialAnalysisKeyConfigured,
+ syncSources: Object.entries(BENCHMARK_SYNC_SOURCES).map(([id, source]) => ({ id, label: source.label, requiresKey: source.requiresKey })),
});
}));
// Explicit read-only catalog discovery: no model inference or provider writes.
@@ -63,5 +74,13 @@ export function createModelComparisonRoutes(providerService) {
const { apiKey } = validateRequest(modelComparisonSyncSchema, req.body || {});
res.json(await syncArtificialAnalysisCatalog({ apiKey }));
}));
+ // Generalized benchmark source sync. /sync-aa stays as a back-compat alias —
+ // other installs' UIs and scripts call it directly.
+ router.post('/sync/:source', asyncHandler(async (req, res) => {
+ const source = BENCHMARK_SYNC_SOURCES[req.params.source];
+ if (!source) throw new ServerError(`Unknown benchmark sync source: ${req.params.source}`, { status: 404 });
+ const { apiKey } = validateRequest(modelComparisonSyncSchema, req.body || {});
+ res.json(await source.sync({ apiKey }));
+ }));
return router;
}
diff --git a/server/routes/modelComparison.test.js b/server/routes/modelComparison.test.js
index 5b51dff0bd..f734478f30 100644
--- a/server/routes/modelComparison.test.js
+++ b/server/routes/modelComparison.test.js
@@ -187,3 +187,65 @@ it('scopes the chart inventory — and a fresh discovery — to the provider mod
const discovery = await request(app).post('/comparison/discover').send({ providerId: 'nvidia-nim' });
expect(discovery.body.models.map(m => m.model)).toEqual(['meta/llama-3.1-8b-instruct']);
});
+
+it('exposes the sync sources and syncs each keyless source without a key', async () => {
+ const listed = (await request(app).get('/comparison')).body.syncSources;
+ expect(listed).toEqual([
+ { id: 'artificial-analysis', label: 'Artificial Analysis', requiresKey: true },
+ { id: 'swebench', label: 'SWE-bench leaderboards', requiresKey: false },
+ { id: 'livecodebench', label: 'LiveCodeBench', requiresKey: false },
+ ]);
+ expect((await request(app).post('/comparison/sync/unknown-source').send({})).status).toBe(404);
+
+ const originalFetch = globalThis.fetch;
+ const swebenchPage = {
+ name: 'Verified',
+ results: [{
+ agent: 'mini-SWE-agent', agent_org: 'Example Org', date: '2026-02-13',
+ folder: '20260213_mini-v2.0.0a0_example-model', instance_cost: 0.35,
+ model_display: 'Example Model', model_org: 'Example Org', name: 'Example Model',
+ reasoning_effort: null, resolved: 52.62, tags: [], warning: null,
+ }],
+ };
+ const lcbData = {
+ performances: [
+ { question_id: '1_A', model: 'Example-Model', date: Date.parse('2024-01-01'), difficulty: 'easy', 'pass@1': 100.0 },
+ { question_id: '2_A', model: 'Example-Model', date: Date.parse('2024-06-01'), difficulty: 'hard', 'pass@1': 50.0 },
+ ],
+ models: [{ model_name: 'example-model', model_repr: 'Example-Model', model_style: 'OpenAIChat', release_date: 1, link: 'https://example.com/model' }],
+ };
+ const spy = vi.spyOn(globalThis, 'fetch').mockImplementation((url, opts) => {
+ if (typeof url === 'string' && url.includes('swebench.com')) {
+ return Promise.resolve({
+ ok: true,
+ text: async () => `<html><script type="application/json" id="leaderboard-data">${JSON.stringify([swebenchPage])}</script></html>`,
+ });
+ }
+ if (typeof url === 'string' && url.includes('livecodebench.github.io')) {
+ return Promise.resolve({ ok: true, json: async () => lcbData });
+ }
+ return originalFetch(url, opts);
+ });
+
+ try {
+ const swe = await request(app).post('/comparison/sync/swebench').send({});
+ expect(swe.status).toBe(200);
+ expect(swe.body.success).toBe(true);
+ expect(swe.body.observations).toBe(1);
+
+ const lcb = await request(app).post('/comparison/sync/livecodebench').send({});
+ expect(lcb.status).toBe(200);
+ expect(lcb.body.success).toBe(true);
+ expect(lcb.body.observations).toBe(1);
+
+ const stored = (await request(app).get('/comparison')).body.observations;
+ expect(stored.find(row => row.id.startsWith('swebench-'))).toMatchObject({
+ benchmark: 'SWE-bench Verified (pass@1, mini-SWE-agent)', billing: 'api',
+ });
+ expect(stored.find(row => row.id.startsWith('lcb-generation-'))).toMatchObject({
+ benchmark: 'LiveCodeBench (generation, pass@1, 2024-01-01 to 2024-06-01)', provider: 'OpenAI',
+ });
+ } finally {
+ spy.mockRestore();
+ }
+});
diff --git a/server/services/livecodebenchBenchmarks.js b/server/services/livecodebenchBenchmarks.js
new file mode 100644
index 0000000000..0ed7b32085
--- /dev/null
+++ b/server/services/livecodebenchBenchmarks.js
@@ -0,0 +1,131 @@
+/** LiveCodeBench generation-split sync for the model comparison catalog; see docs/MODEL-COMPARISON.md. */
+import { ServerError } from '../lib/errorHandler.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { modelComparisonImportSchema } from '../lib/validation.js';
+import { importModelComparison } from './modelComparison.js';
+import { parseModelNameAndEffort } from './artificialAnalysis.js';
+
+const LCB_LEADERBOARD_URL = 'https://livecodebench.github.io/leaderboard.html';
+const LCB_DATA_URL = 'https://livecodebench.github.io/performances_generation.json';
+const LCB_REQUEST_TIMEOUT_MS = 30_000;
+
+// model_style is LiveCodeBench's serving-family tag — it names the API family
+// that evaluated the model. Families outside this table stay 'Unknown' with
+// the style carried in notes; never a guessed org.
+const LCB_PROVIDER_BY_STYLE = new Map([
+ ['openaichat', 'OpenAI'],
+ ['openaireason', 'OpenAI'],
+ ['claude3', 'Anthropic'],
+ ['claude3thinking', 'Anthropic'],
+ ['deepseekapi', 'DeepSeek'],
+ ['deepseekr1', 'DeepSeek'],
+ ['geminithinking', 'Google'],
+ ['grok', 'xAI'],
+ ['codeqweninstruct', 'Qwen'],
+ ['exaone', 'LG AI'],
+]);
+
+const isoDay = ms => new Date(ms).toISOString().slice(0, 10);
+
+export async function fetchLiveCodeBenchPerformances() {
+ let res;
+ try {
+ res = await fetchWithTimeout(LCB_DATA_URL, {}, LCB_REQUEST_TIMEOUT_MS);
+ } catch (error) {
+ if (error?.name === 'AbortError') {
+ throw new ServerError('LiveCodeBench request timed out; retry sync', { status: 502 });
+ }
+ throw error;
+ }
+ if (!res.ok) {
+ throw new ServerError(`LiveCodeBench request failed (${res.status}): ${res.statusText || 'request rejected'}`, { status: 502 });
+ }
+ const payload = await res.json();
+ if (!payload || !Array.isArray(payload.performances) || !payload.performances.length || !Array.isArray(payload.models)) {
+ throw new ServerError('LiveCodeBench returned invalid performance data; retry sync', { status: 502 });
+ }
+ return payload;
+}
+
+export function transformLiveCodeBenchToObservations(payload, { retrievedAt = new Date().toISOString() } = {}) {
+ const dates = payload.performances.map(row => row?.date).filter(Number.isFinite);
+ if (!dates.length) {
+ throw new ServerError('LiveCodeBench returned no dated problems; retry sync', { status: 502 });
+ }
+ const start = isoDay(Math.min(...dates));
+ const end = isoDay(Math.max(...dates));
+ const windowLabel = `${start} to ${end}`;
+ const benchmark = `LiveCodeBench (generation, pass@1, ${windowLabel})`;
+
+ const providerByModel = new Map();
+ for (const m of payload.models) {
+ if (m && typeof m.model_repr === 'string' && !providerByModel.has(m.model_repr)) {
+ providerByModel.set(m.model_repr, m);
+ }
+ }
+
+ // Aggregate per normalized model+effort, not per raw repr — two reprs can
+ // normalize to one series, and one observation per series is the contract.
+ const groups = new Map();
+ for (const row of payload.performances) {
+ if (!row || typeof row.model !== 'string' || !row.model) continue;
+ const passAt1 = Number.isFinite(row['pass@1']) ? row['pass@1'] : null;
+ if (passAt1 === null) continue;
+ const { modelSlug, effort, configDetail } = parseModelNameAndEffort(row.model);
+ const key = `${modelSlug}::${effort}`;
+ if (!groups.has(key)) {
+ groups.set(key, { modelSlug, effort, configDetail, repr: row.model, scores: [] });
+ }
+ groups.get(key).scores.push(passAt1);
+ }
+
+ const observations = [];
+ for (const { modelSlug, effort, configDetail, repr, scores } of groups.values()) {
+ const style = providerByModel.get(repr)?.model_style;
+ const provider = LCB_PROVIDER_BY_STYLE.get(String(style || '').toLowerCase()) || 'Unknown';
+ const mean = scores.reduce((sum, value) => sum + value, 0) / scores.length;
+ observations.push({
+ // The window span is part of the benchmark name — LiveCodeBench's
+ // date-windowed problems address contamination, so a sync that picks up
+ // new problems starts a new series instead of mixing windows.
+ id: `lcb-generation-${start}--${end}-${modelSlug}-${effort}`,
+ provider,
+ model: modelSlug,
+ effort,
+ configuration: configDetail || 'Full generation split, all difficulties',
+ billing: 'api',
+ benchmark,
+ quality: {
+ value: Math.round(mean * 10) / 10,
+ source: {
+ url: LCB_LEADERBOARD_URL,
+ retrievedAt,
+ methodology: `LiveCodeBench generation split, pass@1 mean over ${scores.length} problems, full window ${windowLabel}.`,
+ },
+ },
+ costPerTask: null,
+ inputPerMillion: null,
+ outputPerMillion: null,
+ reasoningPerMillion: null,
+ responseSeconds: null,
+ tokensPerSecond: null,
+ quota: null,
+ notes: `Sourced from LiveCodeBench (${repr}); serving style ${style || 'unknown'}. Costs, throughput and quota are not published by this source.`,
+ });
+ }
+ return observations;
+}
+
+export async function syncLiveCodeBenchCatalog() {
+ const payload = await fetchLiveCodeBenchPerformances();
+ const observations = transformLiveCodeBenchToObservations(payload);
+ const validated = modelComparisonImportSchema.parse({ schemaVersion: 1, observations });
+ const updated = await importModelComparison(validated);
+ return {
+ success: true,
+ fetched: payload.performances.length,
+ observations: observations.length,
+ total: updated.observations.length,
+ catalog: updated,
+ };
+}
diff --git a/server/services/livecodebenchBenchmarks.test.js b/server/services/livecodebenchBenchmarks.test.js
new file mode 100644
index 0000000000..2ceec35275
--- /dev/null
+++ b/server/services/livecodebenchBenchmarks.test.js
@@ -0,0 +1,142 @@
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})), updateSettingsWith: vi.fn() }));
+import { describe, expect, it, vi } from 'vitest';
+import {
+ fetchLiveCodeBenchPerformances,
+ transformLiveCodeBenchToObservations,
+ syncLiveCodeBenchCatalog,
+} from './livecodebenchBenchmarks.js';
+import * as modelComparison from './modelComparison.js';
+
+const day = date => Date.parse(date);
+const payload = {
+ performances: [
+ { question_id: '1_A', model: 'Example-Model', date: day('2024-01-01'), difficulty: 'easy', 'pass@1': 100.0, platform: 'codeforces' },
+ { question_id: '2_A', model: 'Example-Model', date: day('2024-06-01'), difficulty: 'hard', 'pass@1': 50.0, platform: 'leetcode' },
+ { question_id: '1_A', model: 'Other-Model (High)', date: day('2024-01-01'), difficulty: 'easy', 'pass@1': 80.0, platform: 'codeforces' },
+ { question_id: '2_A', model: 'NoScore-Model', date: day('2024-01-01'), difficulty: 'easy', 'pass@1': 30.0, platform: 'codeforces' },
+ { question_id: '3_A', model: 'Skipped-Model', date: day('2024-01-01'), difficulty: 'easy', 'pass@1': null, platform: 'codeforces' },
+ ],
+ models: [
+ { model_name: 'example-model', model_repr: 'Example-Model', model_style: 'OpenAIChat', release_date: 1, link: 'https://example.com/model' },
+ { model_name: 'other-model', model_repr: 'Other-Model (High)', model_style: 'OpenAIReason', release_date: 1, link: 'https://example.com/other' },
+ { model_name: 'noscore', model_repr: 'NoScore-Model', model_style: 'XBai', release_date: 1, link: 'https://example.com/x' },
+ { model_name: 'skipped', model_repr: 'Skipped-Model', model_style: 'XBai', release_date: 1, link: 'https://example.com/s' },
+ ],
+ date_marks: [],
+};
+
+describe('livecodebenchBenchmarks service', () => {
+ describe('transformLiveCodeBenchToObservations', () => {
+ it('aggregates pass@1 per model over the full window and names the window in the benchmark', () => {
+ const obs = transformLiveCodeBenchToObservations(payload, { retrievedAt: '2026-09-17T00:00:00Z' });
+ expect(obs).toHaveLength(3);
+ const example = obs.find(o => o.model === 'example-model');
+ expect(example).toMatchObject({
+ id: 'lcb-generation-2024-01-01--2024-06-01-example-model-unspecified',
+ provider: 'OpenAI',
+ effort: 'unspecified',
+ billing: 'api',
+ benchmark: 'LiveCodeBench (generation, pass@1, 2024-01-01 to 2024-06-01)',
+ });
+ expect(example.quality.value).toBe(75.0);
+ expect(example.quality.source.methodology).toContain('pass@1 mean over 2 problems');
+ expect(example.costPerTask).toBeNull();
+ expect(example.responseSeconds).toBeNull();
+ });
+
+ it('parses the parenthetical effort and its serving family', () => {
+ const obs = transformLiveCodeBenchToObservations(payload);
+ const other = obs.find(o => o.model === 'other-model');
+ expect(other.effort).toBe('high');
+ expect(other.configuration).toBe('High');
+ expect(other.id).toBe('lcb-generation-2024-01-01--2024-06-01-other-model-high');
+ expect(other.provider).toBe('OpenAI');
+ });
+
+ it('keeps an unmapped serving family as Unknown with the style in notes, and skips models with no numeric pass@1', () => {
+ const obs = transformLiveCodeBenchToObservations(payload);
+ expect(obs.some(o => o.model === 'skipped-model')).toBe(false);
+ const unknown = obs.find(o => o.model === 'noscore-model');
+ expect(unknown.provider).toBe('Unknown');
+ expect(unknown.notes).toContain('serving style XBai');
+ });
+
+ it('refuses rows without any dated problem', () => {
+ expect(() => transformLiveCodeBenchToObservations({
+ performances: [{ question_id: '1_A', model: 'Example-Model', date: null, difficulty: 'easy', 'pass@1': 50.0 }],
+ models: [],
+ })).toThrow(/no dated problems/);
+ });
+
+ it('merges two reprs that normalize to one model+effort series', () => {
+ const merged = transformLiveCodeBenchToObservations({
+ performances: [
+ { question_id: '1_A', model: 'Example-Model', date: day('2024-01-01'), difficulty: 'easy', 'pass@1': 100.0 },
+ { question_id: '2_A', model: 'Example-Model', date: day('2024-01-01'), difficulty: 'easy', 'pass@1': 60.0 },
+ ],
+ models: [{ model_name: 'example', model_repr: 'Example-Model', model_style: 'OpenAIChat' }],
+ });
+ expect(merged).toHaveLength(1);
+ expect(merged[0].quality.value).toBe(80.0);
+ expect(merged[0].quality.source.methodology).toContain('over 2 problems');
+ });
+ });
+
+ describe('fetchLiveCodeBenchPerformances', () => {
+ it('maps a non-ok response to a 502', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, statusText: 'missing' })));
+ try {
+ await expect(fetchLiveCodeBenchPerformances()).rejects.toMatchObject({ name: 'ServerError', status: 502 });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it.each([
+ ['missing performances', { models: [] }],
+ ['empty performances', { performances: [], models: [] }],
+ ['missing models', { performances: [{ question_id: '1_A', model: 'Example-Model', date: 1, 'pass@1': 50 }] }],
+ ])('refuses %s without importing', async (_label, body) => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => body })));
+ try {
+ await expect(fetchLiveCodeBenchPerformances()).rejects.toThrow(/invalid performance data/);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+ });
+
+ describe('syncLiveCodeBenchCatalog', () => {
+ it('syncs and imports aggregated observations without a key', async () => {
+ const importSpy = vi.spyOn(modelComparison, 'importModelComparison').mockResolvedValue({
+ schemaVersion: 1, observations: [{ id: 'obs-1' }],
+ });
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => payload })));
+ try {
+ const res = await syncLiveCodeBenchCatalog();
+ expect(res.success).toBe(true);
+ expect(res.fetched).toBe(5);
+ expect(res.observations).toBe(3);
+ expect(importSpy.mock.calls[0][0].observations[0].benchmark).toContain('LiveCodeBench (generation, pass@1,');
+ } finally {
+ vi.unstubAllGlobals();
+ importSpy.mockRestore();
+ }
+ });
+
+ it('refuses a sync whose window spans no dated problems', async () => {
+ const importSpy = vi.spyOn(modelComparison, 'importModelComparison');
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: true, status: 200,
+ json: async () => ({ performances: [{ question_id: '1_A', model: 'Example-Model', date: null, 'pass@1': 50.0 }], models: [] }),
+ })));
+ try {
+ await expect(syncLiveCodeBenchCatalog()).rejects.toThrow(/no dated problems/);
+ expect(importSpy).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllGlobals();
+ importSpy.mockRestore();
+ }
+ });
+ });
+});
diff --git a/server/services/swebenchBenchmarks.js b/server/services/swebenchBenchmarks.js
new file mode 100644
index 0000000000..9dbbc8dfbb
--- /dev/null
+++ b/server/services/swebenchBenchmarks.js
@@ -0,0 +1,122 @@
+/** SWE-bench leaderboard sync for the model comparison catalog; see docs/MODEL-COMPARISON.md. */
+import { ServerError } from '../lib/errorHandler.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { modelComparisonImportSchema } from '../lib/validation.js';
+import { importModelComparison } from './modelComparison.js';
+import { slugify, KNOWN_EFFORTS } from './artificialAnalysis.js';
+
+const SWEBENCH_URL = 'https://www.swebench.com/';
+const SWEBENCH_REQUEST_TIMEOUT_MS = 30_000;
+// Scored tracks only — "Test" is the site's system-test playground tab, not a
+// leaderboard an operator compares within.
+const SWEBENCH_TRACKS = new Set(['Verified', 'Lite', 'Multilingual', 'Multimodal']);
+// No attributable model identity — a run of an undisclosed or multi-vendor
+// lineup cannot be plotted as one model, so the row stays absent.
+const UNATTRIBUTABLE_MODELS = new Set(['undisclosed', 'multiple', '']);
+
+export async function fetchSwebenchLeaderboards() {
+ let res;
+ try {
+ res = await fetchWithTimeout(SWEBENCH_URL, {}, SWEBENCH_REQUEST_TIMEOUT_MS);
+ } catch (error) {
+ if (error?.name === 'AbortError') {
+ throw new ServerError('SWE-bench request timed out; retry sync', { status: 502 });
+ }
+ throw error;
+ }
+ if (!res.ok) {
+ throw new ServerError(`SWE-bench request failed (${res.status}): ${res.statusText || 'request rejected'}`, { status: 502 });
+ }
+ const html = await res.text();
+ const script = String(html || '').match(/<script type="application\/json" id="leaderboard-data">([\s\S]*?)<\/script>/);
+ if (!script) {
+ throw new ServerError('SWE-bench page returned no leaderboard data; retry sync', { status: 502 });
+ }
+ const leaderboards = JSON.parse(script[1]);
+ if (!Array.isArray(leaderboards) || !leaderboards.length) {
+ throw new ServerError('SWE-bench returned invalid leaderboard data; retry sync', { status: 502 });
+ }
+ return leaderboards;
+}
+
+export function transformSwebenchResultsToObservations(leaderboards, { retrievedAt = new Date().toISOString() } = {}) {
+ const observations = [];
+ for (const board of leaderboards) {
+ if (!board || !board.name || !Array.isArray(board.results)) continue;
+ const track = board.name;
+ if (!SWEBENCH_TRACKS.has(track)) continue;
+ const trackSlug = slugify(track);
+ for (const result of board.results) {
+ if (!result) continue;
+ const modelDisplay = typeof result.model_display === 'string' ? result.model_display.trim() : '';
+ const modelSlug = slugify(modelDisplay);
+ if (UNATTRIBUTABLE_MODELS.has(modelSlug)) continue;
+ const resolved = Number.isFinite(result.resolved) ? result.resolved : null;
+ const instanceCost = Number.isFinite(result.instance_cost) ? result.instance_cost : null;
+ if (resolved === null && instanceCost === null) continue;
+ const agent = typeof result.agent === 'string' && result.agent.trim() ? result.agent.trim() : 'unspecified';
+ const agentSlug = slugify(agent);
+ const folder = typeof result.folder === 'string' && result.folder ? result.folder : `${result.date || 'undated'}-${agent}-${modelDisplay}`;
+ const effort = typeof result.reasoning_effort === 'string' && KNOWN_EFFORTS.includes(result.reasoning_effort) ? result.reasoning_effort : 'unspecified';
+ const notes = [
+ `SWE-bench ${track} submission (${folder}); agent scaffold ${agent}.`,
+ ...(Array.isArray(result.tags) && result.tags.length ? [result.tags.join('; ') + '.'] : []),
+ ...(result.warning ? [`Leaderboard warning: ${result.warning}.`] : []),
+ ].join(' ');
+
+ observations.push({
+ // The submission folder IS the run identity — it is stable across syncs
+ // regardless of leaderboard row order, and it disambiguates the several
+ // submissions one model+agent pair can carry.
+ id: `swebench-${trackSlug}-${modelSlug}-${agentSlug}-${slugify(folder)}`,
+ provider: typeof result.model_org === 'string' && result.model_org.trim() ? result.model_org.trim() : 'Unknown',
+ model: modelSlug,
+ effort,
+ configuration: `${agent}; SWE-bench submission ${folder}`.slice(0, 500),
+ billing: instanceCost !== null ? 'api' : 'unknown',
+ benchmark: `SWE-bench ${track} (pass@1, ${agent})`,
+ quality: resolved !== null ? {
+ value: Math.round(resolved * 100) / 100,
+ source: {
+ url: SWEBENCH_URL,
+ retrievedAt,
+ methodology: `SWE-bench ${track} pass@1 resolved-task percentage; agent scaffold ${agent}.`,
+ },
+ } : null,
+ costPerTask: instanceCost !== null ? {
+ value: Math.round(instanceCost * 10000) / 10000,
+ source: {
+ url: SWEBENCH_URL,
+ retrievedAt,
+ methodology: `SWE-bench ${track} agent run, mean USD cost per instance.`,
+ },
+ } : null,
+ inputPerMillion: null,
+ outputPerMillion: null,
+ reasoningPerMillion: null,
+ responseSeconds: null,
+ tokensPerSecond: null,
+ quota: null,
+ notes: notes.slice(0, 2000),
+ });
+ }
+ }
+ return observations;
+}
+
+export async function syncSwebenchCatalog() {
+ const leaderboards = await fetchSwebenchLeaderboards();
+ const observations = transformSwebenchResultsToObservations(leaderboards);
+ if (!observations.length) {
+ throw new ServerError('SWE-bench returned no attributable observations; retry sync', { status: 502 });
+ }
+ const validated = modelComparisonImportSchema.parse({ schemaVersion: 1, observations });
+ const updated = await importModelComparison(validated);
+ return {
+ success: true,
+ fetched: leaderboards.reduce((sum, board) => sum + (Array.isArray(board?.results) ? board.results.length : 0), 0),
+ observations: observations.length,
+ total: updated.observations.length,
+ catalog: updated,
+ };
+}
diff --git a/server/services/swebenchBenchmarks.test.js b/server/services/swebenchBenchmarks.test.js
new file mode 100644
index 0000000000..154856e933
--- /dev/null
+++ b/server/services/swebenchBenchmarks.test.js
@@ -0,0 +1,154 @@
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})), updateSettingsWith: vi.fn() }));
+import { describe, expect, it, vi } from 'vitest';
+import {
+ fetchSwebenchLeaderboards,
+ transformSwebenchResultsToObservations,
+ syncSwebenchCatalog,
+} from './swebenchBenchmarks.js';
+import * as modelComparison from './modelComparison.js';
+
+const leaderboard = (name, results) => ({ name, results });
+const result = overrides => ({
+ agent: 'mini-SWE-agent', agent_org: 'Example Org', checked: true,
+ cost: 10, date: '2026-02-13', folder: '20260213_mini-v2.0.0a0_example-model',
+ instance_calls: 50, instance_cost: 0.35, model_display: 'Example Model',
+ model_org: 'Example Org', name: 'Example Model', os_model: false, os_system: true,
+ reasoning_effort: null, resolved: 52.62, tags: ['Model: example-model', 'Org: Example Org'], warning: null,
+ ...overrides,
+});
+
+describe('swebenchBenchmarks service', () => {
+ describe('transformSwebenchResultsToObservations', () => {
+ it('maps a scored-track submission into a scaffold-scoped observation', () => {
+ const obs = transformSwebenchResultsToObservations([leaderboard('Verified', [result()])], { retrievedAt: '2026-09-17T00:00:00Z' });
+ expect(obs).toHaveLength(1);
+ expect(obs[0]).toMatchObject({
+ id: 'swebench-verified-example-model-mini-swe-agent-20260213-mini-v2.0.0a0-example-model',
+ provider: 'Example Org',
+ model: 'example-model',
+ effort: 'unspecified',
+ billing: 'api',
+ benchmark: 'SWE-bench Verified (pass@1, mini-SWE-agent)',
+ });
+ expect(obs[0].quality.value).toBe(52.62);
+ expect(obs[0].quality.source.methodology).toContain('agent scaffold mini-SWE-agent');
+ expect(obs[0].costPerTask.value).toBe(0.35);
+ expect(obs[0].costPerTask.source.methodology).toContain('mean USD cost per instance');
+ expect(obs[0].inputPerMillion).toBeNull();
+ expect(obs[0].responseSeconds).toBeNull();
+ });
+
+ it('excludes the Test playground track and rows without an attributable model', () => {
+ const obs = transformSwebenchResultsToObservations([
+ leaderboard('Test', [result()]),
+ leaderboard('Verified', [result({ model_display: 'Undisclosed' }), result({ folder: '20260213_b_example-model' })]),
+ leaderboard('Lite', [result({ model_display: 'Multiple' })]),
+ leaderboard('Multimodal', [result()]),
+ ]);
+ expect(obs).toHaveLength(2);
+ expect(obs.map(o => o.benchmark).sort()).toEqual([
+ 'SWE-bench Multimodal (pass@1, mini-SWE-agent)', 'SWE-bench Verified (pass@1, mini-SWE-agent)',
+ ]);
+ });
+
+ it('keeps a run without published cost as unknown billing and skips rows with no sourced metric', () => {
+ const obs = transformSwebenchResultsToObservations([leaderboard('Verified', [
+ result({ instance_cost: null, cost: null }),
+ result({ resolved: null, instance_cost: null }),
+ ])]);
+ expect(obs).toHaveLength(1);
+ expect(obs[0].billing).toBe('unknown');
+ expect(obs[0].costPerTask).toBeNull();
+ expect(obs[0].quality.value).toBe(52.62);
+ });
+
+ it('keeps duplicate runs of one model+agent as distinct observations under one series', () => {
+ const obs = transformSwebenchResultsToObservations([leaderboard('Verified', [
+ result(),
+ result({ folder: '20260101_mini-v2.0.0a0_example-model', date: '2026-01-01' }),
+ ])]);
+ expect(obs).toHaveLength(2);
+ expect(new Set(obs.map(o => o.id)).size).toBe(2);
+ expect(new Set(obs.map(o => o.benchmark)).size).toBe(1);
+ });
+
+ it('maps a recognized reasoning effort and keeps a leaderboard warning in notes', () => {
+ const obs = transformSwebenchResultsToObservations([leaderboard('Verified', [
+ result({ reasoning_effort: 'high', warning: 'Older submission' }),
+ result({ reasoning_effort: 'unrecognized-effort' }),
+ ])]);
+ expect(obs.map(o => o.effort)).toEqual(['high', 'unspecified']);
+ expect(obs[0].notes).toContain('Leaderboard warning: Older submission');
+ });
+ });
+
+ describe('fetchSwebenchLeaderboards', () => {
+ it('maps a non-ok response to a 502', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 500, statusText: 'boom' })));
+ try {
+ await expect(fetchSwebenchLeaderboards()).rejects.toMatchObject({ name: 'ServerError', status: 502 });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('refuses a page without the leaderboard data script', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, text: async () => '<html><body>empty</body></html>' })));
+ try {
+ await expect(fetchSwebenchLeaderboards()).rejects.toThrow(/no leaderboard data/);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('extracts the inline leaderboard JSON', async () => {
+ const data = [leaderboard('Verified', [result()])];
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: true, status: 200,
+ text: async () => `<html><script type="application/json" id="leaderboard-data">${JSON.stringify(data)}</script></html>`,
+ })));
+ try {
+ expect(await fetchSwebenchLeaderboards()).toEqual(data);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+ });
+
+ describe('syncSwebenchCatalog', () => {
+ it('syncs and imports observations without a key', async () => {
+ const importSpy = vi.spyOn(modelComparison, 'importModelComparison').mockResolvedValue({
+ schemaVersion: 1, observations: [{ id: 'obs-1' }],
+ });
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: true, status: 200,
+ text: async () => `<html><script type="application/json" id="leaderboard-data">${JSON.stringify([leaderboard('Verified', [result()])])}</script></html>`,
+ })));
+ try {
+ const res = await syncSwebenchCatalog();
+ expect(res.success).toBe(true);
+ expect(res.fetched).toBe(1);
+ expect(res.observations).toBe(1);
+ expect(importSpy.mock.calls[0][0].observations[0].benchmark).toBe('SWE-bench Verified (pass@1, mini-SWE-agent)');
+ } finally {
+ vi.unstubAllGlobals();
+ importSpy.mockRestore();
+ }
+ });
+
+ it('refuses a sync that produces no attributable observations', async () => {
+ const importSpy = vi.spyOn(modelComparison, 'importModelComparison');
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: true, status: 200,
+ text: async () => `<html><script type="application/json" id="leaderboard-data">${JSON.stringify([leaderboard('Test', [result()])])}</script></html>`,
+ })));
+ try {
+ await expect(syncSwebenchCatalog()).rejects.toThrow(/no attributable observations/);
+ expect(importSpy).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllGlobals();
+ importSpy.mockRestore();
+ }
+ });
+ });
+});