From bdf75542fc21e45e8b5a275d6dd41085b4cee03c Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 25 Nov 2026 17:27:46 +0100 Subject: [PATCH 1/3] feat(compare): add leaderboard scoring foundations --- AGENTS.md | 1 + app/nullius/leaderboard/__init__.py | 1 + app/nullius/leaderboard/board.py | 133 +++++++++++++++++++++++ app/nullius/leaderboard/configuration.py | 121 +++++++++++++++++++++ app/nullius/leaderboard/scoring.py | 129 ++++++++++++++++++++++ app/nullius/leaderboard/weights.py | 36 ++++++ app/tests/test_leaderboard_board.py | 96 ++++++++++++++++ app/tests/test_leaderboard_scoring.py | 121 +++++++++++++++++++++ app/tests/test_leaderboard_weights.py | 120 ++++++++++++++++++++ pyproject.toml | 2 +- 10 files changed, 759 insertions(+), 1 deletion(-) create mode 100644 app/nullius/leaderboard/__init__.py create mode 100644 app/nullius/leaderboard/board.py create mode 100644 app/nullius/leaderboard/configuration.py create mode 100644 app/nullius/leaderboard/scoring.py create mode 100644 app/nullius/leaderboard/weights.py create mode 100644 app/tests/test_leaderboard_board.py create mode 100644 app/tests/test_leaderboard_scoring.py create mode 100644 app/tests/test_leaderboard_weights.py diff --git a/AGENTS.md b/AGENTS.md index ad99e5e7..a25288ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,6 +59,7 @@ is: `grep -m1 '"""' app/nullius/*.py app/nullius/runs/*.py`. | --- | --- | | `app/nullius/` itself | What all share: settings, paths, providers, hosts, running a recipe | | `app/nullius/runs/`, `traces/`, `compare/` | Reading one job tree, a trial's trace, several runs | +| `app/nullius/leaderboard/` | Composite scoring, selected task evidence and profile scoring documents | | `app/nullius/catalogue/` | A folder per entry under `benchmarks/`, `agents/`, `capabilities/`: its definition and code | | `app/nullius/recipes/`, `harbor/` | What the builder offers and saves; the Harbor a recipe pins | | `app/nullius/importers/`, `judge/` | Foreign results in; questions to a judge model | diff --git a/app/nullius/leaderboard/__init__.py b/app/nullius/leaderboard/__init__.py new file mode 100644 index 00000000..e2b637ea --- /dev/null +++ b/app/nullius/leaderboard/__init__.py @@ -0,0 +1 @@ +"""Workspace agent scores and their selected task evidence.""" diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py new file mode 100644 index 00000000..63cab7bd --- /dev/null +++ b/app/nullius/leaderboard/board.py @@ -0,0 +1,133 @@ +"""One workspace's composite scores, evidence, coverage and rank requirements.""" +from __future__ import annotations + +import hashlib +import json +from math import isfinite + +from . import configuration, scoring, weights + + +def row_identity(job): + identity = job.identity + limits = {k: v for k, v in identity.get("limits", {}).items() + if k not in ("repeat", "n_tasks", "task_names", "sample", "seed")} + return {"agent": identity.get("agent", job.agent_name), "version": identity.get("agent_version", job.agent_version), + "model": identity.get("model", job.model_name), "effort": job.reasoning_effort, + "provider": identity.get("provider"), "options": identity.get("agent_options"), + "backend": job.launch.get("environment"), "limits": limits} + + +def key_for(identity): + return hashlib.sha256(json.dumps(identity, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + + +def _empty_metrics(): + return {name: {"value": None, "count": 0} for name in ("time", "cost", "steps", "calls")} + + +def _entry_key(entry): + return tuple(entry.get(k, "") for k in ("benchmark", "dataset", "version", "metric")) + + +def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_open=True): + """Pure board projection. Inputs belong to a single workspace and profile.""" + config = configuration.validate(settings, benchmarks) + agents = [a for a in agents if not a.get("example") and a["key"] not in ("nop", "oracle")] + agents_by = {a["key"]: a for a in agents} + benchmarks_by = {(b["key"], b.get("_version", "")): b for b in benchmarks} + customs = {c["id"]: c for c in config["custom"]} + grouped, identities = {}, {} + for job in jobs: + identity = row_identity(job) + if not scoring.eligible(job) or identity["agent"] not in agents_by: + continue + key = key_for(identity) + grouped.setdefault(key, []).append(job) + identities[key] = identity + measured_agents = {identity["agent"] for identity in identities.values()} + for agent in agents: + if agent["key"] in measured_agents: + continue + identity = {"agent": agent["key"], "version": agent.get("_version", ""), "catalogue_only": True} + key = key_for(identity) + grouped[key], identities[key] = [], identity + rows = [] + for key, runs in grouped.items(): + identity = identities[key] + agent = agents_by[identity["agent"]] + row = {"key": key, "agent": identity["agent"], "name": agent["label"], "company": agent.get("company", ""), + "version": identity["version"], "identity": identity, "has_runs": bool(runs), "axes": {}, + "metrics": _empty_metrics(), "reasons": [], "custom_names": []} + trials = {} + for name in configuration.AXES: + axis = config["axes"][name] + entries = [] + for entry in axis["entries"]: + evidence = dict(entry, score=None, share=0, tasks=None, covered=0, runs=[], reason="not run", unverified=False, available=True) + if "custom" in entry: + custom = customs[entry["custom"]] + value = custom["scores"].get(key) + evidence.update(name=custom["name"], score=value / 100 if all_scores and value is not None else None, + reason="not verified" if all_scores and value is not None else "not run", + unverified=all_scores and value is not None and entry["weight"] > 0) + else: + bench = benchmarks_by.get((entry["benchmark"], entry["version"])) + evidence["name"] = bench["label"] if bench else entry["benchmark"] + evidence["available"] = bench is not None + if bench is None: + evidence["reason"] = "Benchmark version unavailable" + else: + manifests = {d["id"]: d.get("tasks") if isinstance(d.get("tasks"), dict) else None for d in bench.get("datasets", [])} + got = scoring.contribution(runs, benchmark=entry["benchmark"], version=entry["version"], datasets=manifests, + dataset=entry["dataset"], metric=entry["metric"], graded=bench.get("score", {}).get("kind") == "score") + evidence.update(score=got.score, tasks=got.total, covered=got.covered, excluded=got.excluded, + runs=list(got.run_ids), reason=got.reason, note=got.note) + if entry["weight"] > 0 and got.score is not None: + for run_id, _, attempts in got.tasks: + for trial in attempts: + if not trial.is_infra: + trials[(run_id, trial.trial_name)] = trial + entries.append(evidence) + score, shares = weights.combine((e["score"], e["weight"]) for e in entries) + for evidence, share in zip(entries, shares): + evidence["share"] = share + if evidence["unverified"] and evidence["name"] not in row["custom_names"]: + row["custom_names"].append(evidence["name"]) + row["axes"][name] = {"score": score, "weight": axis["weight"], "share": 0, "entries": entries, + "unverified": any(e["unverified"] and e["share"] > 0 for e in entries)} + row["overall"], shares = weights.combine((a["score"], a["weight"]) for a in row["axes"].values()) + for axis, share in zip(row["axes"].values(), shares): + axis["share"] = share + row["unverified"] = any(a["unverified"] and a["share"] > 0 for a in row["axes"].values()) + for metric, field in (("time", "dur_agent"), ("cost", "cost_usd")): + values = [getattr(t, field) for t in trials.values() if getattr(t, field) is not None and isfinite(getattr(t, field)) and getattr(t, field) >= 0] + row["metrics"][metric] = {"value": sum(values) / len(values) if values else None, "count": len(values)} + rows.append(row) + required = {name: {_entry_key(e) for row in rows for e in row["axes"][name]["entries"] + if "custom" not in e and e["available"] and e["weight"] > 0 and e["score"] is not None} + for name in configuration.AXES if config["axes"][name]["weight"] > 0} + for row in rows: + for name, entries in required.items(): + for entry in row["axes"][name]["entries"]: + if _entry_key(entry) not in entries or "custom" in entry: + continue + reason = (f"{entry['name']} not run" if entry["score"] is None else + f"{entry['name']} full task coverage unavailable" if entry["tasks"] is None else + f"{entry['name']} {entry['covered']} of {entry['tasks']} tasks" if entry["covered"] < entry["tasks"] else "") + if reason and reason not in row["reasons"]: + row["reasons"].append(reason) + for family, axes in (("capabilities", configuration.CAPABILITIES), ("domains", configuration.DOMAINS)): + needed = [a for a in axes if required.get(a)] + present = sum(row["axes"][a]["score"] is not None for a in needed) + if present < len(needed): + row["reasons"].append(f"{present} of {len(needed)} {family}") + rows = weights.rank(rows) + averages = {} + for name in configuration.AXES: + values = [r["axes"][name]["score"] for r in rows if r["axes"][name]["score"] is not None] + averages[name] = {"score": sum(values) / len(values) if values else None, "count": len(values)} + return {"rows": rows, "axes": list(configuration.AXES), "domains": list(configuration.DOMAINS), + "capabilities": list(configuration.CAPABILITIES), "averages": averages, + "selected": rows[0]["key"] if rows else None, "all_scores": all_scores, + "empty": "No workspace open" if not workspace_open else "No scored runs in this workspace" if not any(r["has_runs"] for r in rows) else ""} diff --git a/app/nullius/leaderboard/configuration.py b/app/nullius/leaderboard/configuration.py new file mode 100644 index 00000000..ccd44855 --- /dev/null +++ b/app/nullius/leaderboard/configuration.py @@ -0,0 +1,121 @@ +"""Complete, validated profile scoring documents, written atomically.""" +from __future__ import annotations + +import copy +import json +import math +from pathlib import Path + +from nullius import ondisk, paths + +DOMAINS = ("Travel", "Dining", "Shopping", "Money", "Health", "Home", "Work") +CAPABILITIES = ("Memory", "Safety", "Consistency", "Personalization", "Proactivity", "Retrieval", "Communication", "Execution") +AXES = CAPABILITIES + DOMAINS +OVERALL = (.12, .12, .08, .15, .15, .10, .08, .20, 0, 0, 0, 0, 0, 0, 0) +DEFAULT_ENTRIES = { + "Consistency": [("tau3-bench", "", "pass^3")], + "Retrieval": [("gaia", "", "Score"), ("tau3-bench", "banking_knowledge", "Score")], + "Communication": [("tau3-bench", "telecom", "Score")], + "Execution": [(k, "", "Score") for k in ("osworld1", "osworld2", "swe-bench-verified", "terminal-bench")], + "Travel": [("tau3-bench", "airline", "Score")], + "Shopping": [("tau3-bench", "retail", "Score")], + "Money": [("tau3-bench", "banking_knowledge", "Score")], + "Home": [("tau3-bench", "telecom", "Score"), ("osworld1", "os", "Score")], + "Work": [("osworld1", "office", "Score"), ("swe-bench-verified", "", "Score"), + ("terminal-bench", "", "Score"), ("open-telco", "teleqna-lite", "Score")], +} + + +def location(): + return Path(paths.config_dir()) / "scoring.json" + + +def defaults(benchmarks): + versions = {b["key"]: b.get("_version", "") for b in benchmarks + if b.get("_version") == b.get("_default")} + return {"schema": 1, "custom": [], "axes": { + axis: {"weight": weight, "entries": [ + {"benchmark": key, "dataset": dataset, "version": versions[key], "metric": metric, "weight": 1} + for key, dataset, metric in DEFAULT_ENTRIES.get(axis, []) if key in versions]} + for axis, weight in zip(AXES, OVERALL)}} + + +def _number(value, label, upper=None): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0 or (upper is not None and value > upper): + raise ValueError(f"{label}: enter a finite number between 0 and {upper}" if upper is not None else f"{label}: enter a finite nonnegative number") + + +def validate(document, benchmarks): + """Validate every field before a write; preserve removed catalogue references.""" + if not isinstance(document, dict) or set(document) != {"schema", "custom", "axes"} or document["schema"] != 1: + raise ValueError("Invalid scoring document") + doc = copy.deepcopy(document) + if not isinstance(doc["axes"], dict) or set(doc["axes"]) != set(AXES) or not isinstance(doc["custom"], list): + raise ValueError("Scoring requires all fifteen axes and a custom benchmark list") + ids, names = set(), set() + for custom in doc["custom"]: + if not isinstance(custom, dict) or set(custom) != {"id", "name", "scores"}: + raise ValueError("Invalid custom benchmark") + key, name = custom["id"], custom["name"] + if not isinstance(key, str) or not key or key in ids or not isinstance(name, str) or not name.strip() or name.strip().casefold() in names: + raise ValueError("Custom benchmarks need unique IDs and nonempty unique names") + custom["name"] = name.strip() + ids.add(key) + names.add(name.strip().casefold()) + if not isinstance(custom["scores"], dict) or not all(isinstance(k, str) and k for k in custom["scores"]): + raise ValueError("Custom scores require stable row keys") + for value in custom["scores"].values(): + if value is not None: + _number(value, "Custom score", 100) + available = {(b["key"], b.get("_version", "")): b for b in benchmarks} + for name, axis in doc["axes"].items(): + if not isinstance(axis, dict) or set(axis) != {"weight", "entries"} or not isinstance(axis["entries"], list): + raise ValueError(f"{name}: invalid axis") + _number(axis["weight"], name) + seen = set() + for entry in axis["entries"]: + if not isinstance(entry, dict): + raise ValueError(f"{name}: invalid entry") + _number(entry.get("weight"), f"{name} entry weight") + if "custom" in entry: + if set(entry) != {"custom", "weight"} or entry["custom"] not in ids: + raise ValueError("Unknown custom benchmark") + identity = ("custom", entry["custom"]) + else: + if set(entry) != {"benchmark", "dataset", "version", "metric", "weight"} or not all(isinstance(entry[k], str) for k in ("benchmark", "dataset", "version", "metric")) or not entry["benchmark"]: + raise ValueError("Invalid benchmark entry") + bench = available.get((entry["benchmark"], entry["version"])) + if entry["metric"] not in ("Score", "pass^3") or (entry["metric"] == "pass^3" and bench is not None and (bench.get("score") or {}).get("kind") != "pass"): + raise ValueError("Choose Score or supported pass^3") + identity = tuple(entry[k] for k in ("benchmark", "dataset", "version", "metric")) + if identity in seen: + raise ValueError(f"{name}: duplicate entry") + seen.add(identity) + if not any(axis["weight"] > 0 for axis in doc["axes"].values()): + raise ValueError("At least one Weight in Overall must be positive") + return doc + + +def remove_custom(document, key): + doc = copy.deepcopy(document) + doc["custom"] = [c for c in doc["custom"] if c["id"] != key] + for axis in doc["axes"].values(): + axis["entries"] = [e for e in axis["entries"] if e.get("custom") != key] + return doc + + +def load(path, benchmarks): + try: + return validate(json.loads(Path(path).read_text()), benchmarks), "" + except FileNotFoundError: + return defaults(benchmarks), "" + except (OSError, ValueError, TypeError): + return defaults(benchmarks), "Scoring settings could not be read; defaults are active." + + +def save(path, document, benchmarks): + doc = validate(document, benchmarks) + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + ondisk.write_whole(path, json.dumps(doc, ensure_ascii=False, indent=2, allow_nan=False) + "\n", mode=0o600) + return doc diff --git a/app/nullius/leaderboard/scoring.py b/app/nullius/leaderboard/scoring.py new file mode 100644 index 00000000..67023d7d --- /dev/null +++ b/app/nullius/leaderboard/scoring.py @@ -0,0 +1,129 @@ +"""Select one run per dataset and score distinct tasks with their recorded attempts. + +Dataset manifests map recorded task names to canonical identities. None means +identity/coverage is unknown; it never means an empty dataset. This module reads +no files and does not modify the jobs whose raw metrics other pages display. +""" +from __future__ import annotations + +from dataclasses import dataclass +from datetime import timezone +from math import isfinite +from typing import Mapping, Sequence + +from nullius.runs import attempts, classify +from nullius.runs.parse import Job, Trial + + +@dataclass(frozen=True) +class Contribution: + score: float | None = None + covered: int = 0 + total: int | None = None + excluded: int = 0 + run_ids: tuple[str, ...] = () + reason: str = "not run" + note: str = "" + # Selected task evidence, for efficiency deduplication and run links. + tasks: tuple[tuple[str, str, tuple[Trial, ...]], ...] = () + + +def eligible(job: Job) -> bool: + return bool(job.finished_at and not job.is_running and not job.is_preparing and not job.is_control) + + +def _groups(job, manifest=None): + result = {} + for trial in job.trials: + key = manifest.get(trial.task_name, trial.task_name) if manifest is not None else trial.task_name + result.setdefault(key, []).append(trial) + return result + + +def _precedence(job, manifest=None): + count = sum(bool(attempts.ran(ts)) for ts in _groups(job, manifest).values()) + at = job.finished_at + stamp = (at if at.tzinfo else at.replace(tzinfo=timezone.utc)).timestamp() + return -count, -stamp, job.job_id + + +def _score(ts, graded): + ran = attempts.ran(ts) + if not graded: + grouped = attempts.Attempts(tuple(ts)) + return grouped.rate if grouped.has_verdicts else None + values = [] + for t in ran: + if t.outcome == classify.AGENT_ERROR: + values.append((0, t.n_parts or 1)) + elif t.score is not None: + if isinstance(t.score, bool) or not isinstance(t.score, (int, float)) or not isfinite(t.score) or not 0 <= t.score <= 1: + raise ValueError("Unsupported score scale") + values.append((t.score, t.n_parts or 1)) + return sum(score * parts for score, parts in values) / sum(parts for _, parts in values) if values else None + + +def contribution(jobs: Sequence[Job], *, benchmark: str, version: str, + datasets: Mapping[str, Mapping[str, str] | None], dataset: str = "", + metric: str = "Score", graded: bool = False) -> Contribution: + """Select by coverage, finish and qualified run id, never by outcome. + +The caller passes one agent/version/setup row and qualified job ids. A selected +dataset reads only that dataset. Whole entries require explicit identities to +join several datasets; they cannot infer overlap from short task names. +""" + if metric not in ("Score", "pass^3") or (graded and metric != "Score"): + raise ValueError("Choose Score or supported pass^3") + scope = {dataset: datasets[dataset]} if dataset in datasets else ({} if dataset else dict(datasets)) + if not scope: + return Contribution(reason="Dataset unavailable") + manifests = list(scope.values()) + total = len({canonical for manifest in manifests for canonical in manifest.values()}) if all(m is not None for m in manifests) else None + pool = [j for j in jobs if eligible(j) and j.dataset in scope + and j.identity.get("benchmark") == benchmark + and j.identity.get("benchmark_version") == version] + sources = {source for j in pool for source in j.merged_from} + pool = [j for j in pool if j.job_id not in sources] + selected = {} + precedence = lambda j: _precedence(j, scope[j.dataset]) + for j in sorted(pool, key=precedence): + selected.setdefault(j.dataset, j) + ids = tuple(j.job_id for j in selected.values()) + if not selected: + return Contribution(total=total) + if len(selected) > 1 and any(scope[d] is None for d in selected): + return Contribution(total=total, run_ids=ids, reason="Task identity unavailable for aggregation") + union = {} + for j in sorted(selected.values(), key=precedence): + manifest = scope[j.dataset] + if manifest is not None and any(t.task_name not in manifest for t in j.trials): + return Contribution(total=total, run_ids=ids, reason="Task identity unavailable for aggregation") + for canonical, ts in _groups(j, manifest).items(): + union.setdefault(canonical, (j.job_id, canonical, tuple(attempts.ordered(ts)))) + tasks = tuple(union.values()) + groups = [ts for _, _, ts in tasks] + excluded = sum(not attempts.ran(ts) for ts in groups) + covered = sum(bool(attempts.ran(ts)) for ts in groups) + note = "" + if graded: + n_grades = sum(t.score is not None and not t.is_infra for ts in groups for t in ts) + crashes = sum(t.outcome == classify.AGENT_ERROR for ts in groups for t in ts) + note = f"{n_grades} graded, {crashes} agent crashes; crashes count as 0" + reason = "" + if metric == "pass^3": + estimate = attempts.for_tasks(groups) + score = estimate["hat"].get(3) if estimate else None + if score is None: + reason = "Three recorded attempts per eligible task required" + # An infra attempt makes the entire unit ineligible for pass^k. + covered = sum(bool(ts) and len(ts) >= 3 and not any(t.is_infra or t.outcome == classify.SCORED for t in ts) for ts in groups) + else: + try: + scores = [_score(ts, graded) for ts in groups] + measured = [v for v in scores if v is not None] + score = sum(measured) / len(measured) if measured else None + if score is None: + reason = "No measured outcomes" + except ValueError as error: + score, reason = None, str(error) + return Contribution(score, covered, total, excluded, ids, reason, note, tasks) diff --git a/app/nullius/leaderboard/weights.py b/app/nullius/leaderboard/weights.py new file mode 100644 index 00000000..575d4971 --- /dev/null +++ b/app/nullius/leaderboard/weights.py @@ -0,0 +1,36 @@ +"""Measured weight shares, percentage formatting and competition ranking.""" +from __future__ import annotations + + +def combine(values): + """A missing measurement has no effective share, including a positive weight.""" + values = list(values) + scale = max((w for score, w in values if score is not None and w > 0), default=0) + total = sum(w / scale for score, w in values if score is not None and w > 0) if scale else 0 + shares = [(w / scale) / total if total and score is not None and w > 0 else 0 for score, w in values] + return (sum(score * share for (score, _), share in zip(values, shares) if share) if total else None), shares + + +def percent(value): + return f"{100 * value:.1f}".rstrip("0").rstrip(".") + "%" if value is not None else "—" + + +def rank(rows, sort="overall", descending=True): + """Assign ranks from full precision, then sort within eligibility groups.""" + rows = [dict(row, rank=None) for row in rows] + eligible = sorted((r for r in rows if r["overall"] is not None and not r["reasons"]), + key=lambda r: (-r["overall"], r["name"], r["key"])) + previous, assigned = None, None + for i, row in enumerate(eligible, 1): + if row["overall"] != previous: + assigned = i + row["rank"], previous = assigned, row["overall"] + groups = [eligible, [r for r in rows if r["overall"] is not None and r["reasons"]], + [r for r in rows if r["overall"] is None]] + result = [] + for group in groups: + group.sort(key=lambda r: (r["name"], r["key"])) + present = [r for r in group if r.get(sort) is not None] + absent = [r for r in group if r.get(sort) is None] + result.extend(sorted(present, key=lambda r: r[sort], reverse=descending) + absent) + return result diff --git a/app/tests/test_leaderboard_board.py b/app/tests/test_leaderboard_board.py new file mode 100644 index 00000000..f01fdd50 --- /dev/null +++ b/app/tests/test_leaderboard_board.py @@ -0,0 +1,96 @@ +"""The composite view uses verified coverage and stable participant identities.""" +from dataclasses import replace +import unittest + +from tests.test_leaderboard_scoring import run +from nullius.leaderboard import board, configuration + + +class BoardExamples(unittest.TestCase): + def setUp(self): + self.agents = [{"key": key, "label": key, "_version": "1", "_default": "1", "company": "Maker"} + for key in ("A", "B", "C")] + self.benchmarks = [{"key": "gaia", "label": "GAIA", "_version": "v1", "_default": "v1", + "score": {"kind": "pass"}, "datasets": [{"id": "first", "tasks": {str(i): str(i) for i in range(100)}}]}] + self.config = configuration.defaults(self.benchmarks) + for axis in self.config["axes"].values(): + axis["weight"] = 0 + self.config["axes"]["Retrieval"]["weight"] = 1 + + def make_run(self, name, outcomes, **identity): + result = run(name, outcomes, agent_name=name) + result.identity.update(agent=name, agent_version="1", model="m", provider="p", **identity) + return result + + def build(self, jobs, all_scores=False): + return board.build(jobs, self.agents, self.benchmarks, self.config, all_scores=all_scores) + + def test_c6_partial_perfection_follows_complete_sixty_percent(self): + rows = self.build([self.make_run("A", ["resolved"]), self.make_run("B", ["resolved"] * 60 + ["agent_error"] * 40)])["rows"] + self.assertEqual([(r["name"], r["overall"], r["rank"]) for r in rows], [("B", .6, 1), ("A", 1, None), ("C", None, None)]) + self.assertIn("GAIA 1 of 100 tasks", rows[1]["reasons"]) + + def test_c21_verified_all_custom_exemption_and_average(self): + jobs = [self.make_run("A", ["resolved"] * 50 + ["agent_error"] * 50), self.make_run("B", ["resolved"] * 60 + ["agent_error"] * 40)] + a = next(r for r in self.build(jobs)["rows"] if r["name"] == "A") + self.config["custom"] = [{"id": "calendar", "name": "Family calendar test", "scores": {a["key"]: 100}}] + self.config["axes"]["Personalization"] = {"weight": 1, "entries": [{"custom": "calendar", "weight": 1}]} + verified = self.build(jobs) + self.assertEqual([(r["name"], r["overall"]) for r in verified["rows"][:2]], [("B", .6), ("A", .5)]) + all_scores = self.build(jobs, True) + self.assertEqual([(r["name"], r["overall"], r["rank"]) for r in all_scores["rows"][:2]], [("A", .75, 1), ("B", .6, 2)]) + self.assertEqual(all_scores["averages"]["Personalization"], {"score": 1, "count": 1}) + self.assertTrue(all_scores["rows"][0]["unverified"]) + self.assertEqual(all_scores["rows"][0]["custom_names"], ["Family calendar test"]) + + def test_c4_setup_and_version_isolation_sampling_not_setup(self): + base = self.make_run("A", ["resolved"]) + changed = replace(base, job_id="different", identity=base.identity | {"limits": {"max_turns": 20}}) + other = replace(base, job_id="other", identity=base.identity | {"limits": {"max_turns": 50}}) + version = replace(base, job_id="version", identity=base.identity | {"agent_version": "2"}) + self.assertEqual(len([r for r in self.build([base, changed, other, version])["rows"] if r["has_runs"]]), 4) + sample = replace(base, job_id="sample", n_tasks=30, identity=base.identity | {"limits": {"repeat": 3}}) + self.assertEqual(len([r for r in self.build([base, sample])["rows"] if r["has_runs"]]), 1) + + def test_c4_benchmark_options_do_not_split_the_participant(self): + base = self.make_run("A", ["resolved"]) + other = replace(base, job_id="other-benchmark", identity=base.identity | {"benchmark_options": {"temperature": "default"}}) + self.assertEqual(len([r for r in self.build([base, other])["rows"] if r["has_runs"]]), 1) + + def test_c17_efficiency_deduplicates_mappings_and_never_loads_trajectories(self): + base = self.make_run("A", ["resolved"]) + self.config["axes"]["Money"]["entries"] = self.config["axes"]["Retrieval"]["entries"] + row = next(r for r in self.build([base])["rows"] if r["has_runs"]) + self.assertEqual(row["metrics"]["time"], {"value": 40, "count": 1}) + self.assertEqual(row["metrics"]["cost"], {"value": 1, "count": 1}) + self.assertIsNone(row["metrics"]["steps"]["value"]) + + def test_c6_positive_domain_weights_gate_and_zero_weights_do_not(self): + self.config["axes"]["Travel"]["entries"] = [{"benchmark": "gaia", "version": "v1", "dataset": "second", "metric": "Score", "weight": 1}] + self.config["axes"]["Retrieval"]["entries"][0]["dataset"] = "first" + self.benchmarks[0]["datasets"].append({"id": "second", "tasks": {"0": "travel-0", "1": "travel-1"}}) + complete = self.make_run("A", ["resolved"] * 100) + partial = replace(self.make_run("A", ["resolved"]), job_id="travel", dataset="second") + self.assertEqual(self.build([complete, partial])["rows"][0]["rank"], 1) + self.config["axes"]["Travel"]["weight"] = 1 + row = self.build([complete, partial])["rows"][0] + self.assertIsNone(row["rank"]) + self.assertIn("GAIA 1 of 2 tasks", row["reasons"]) + + def test_c6_whole_entry_requires_full_union_not_a_full_small_dataset(self): + self.benchmarks[0]["datasets"].append({"id": "second", "tasks": {"0": "extra"}}) + row = self.build([self.make_run("A", ["resolved"] * 100)])["rows"][0] + self.assertIsNone(row["rank"]) + self.assertIn("GAIA 100 of 101 tasks", row["reasons"]) + + def test_c21_custom_only_rows_rank_without_verified_requirements(self): + catalogue = self.build([])["rows"] + self.config["custom"] = [{"id": "calendar", "name": "Family calendar test", "scores": {catalogue[0]["key"]: 72}}] + self.config["axes"]["Retrieval"]["entries"] = [{"custom": "calendar", "weight": 1}] + row = self.build([], True)["rows"][0] + self.assertEqual((row["overall"], row["rank"], row["has_runs"]), (.72, 1, False)) + self.assertEqual(row["metrics"]["cost"], {"value": None, "count": 0}) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_leaderboard_scoring.py b/app/tests/test_leaderboard_scoring.py new file mode 100644 index 00000000..421cc1ad --- /dev/null +++ b/app/tests/test_leaderboard_scoring.py @@ -0,0 +1,121 @@ +"""Leaderboard contributions retain tasks and attempts, never best-run scores.""" +from dataclasses import replace +from datetime import timedelta +import unittest + +from tests.test_comparison import job, trial +from nullius.leaderboard import scoring + + +def run(name, outcomes, dataset="first", **changes): + result = job([trial(str(i), outcome, trial_name=f"{name}-{i}") + for i, outcome in enumerate(outcomes)], dataset=dataset, job_id=name) + result.identity = {"benchmark": "gaia", "benchmark_version": "v1"} + return replace(result, **changes) + + +class Contributions(unittest.TestCase): + def contribution(self, runs, datasets=None, **options): + return scoring.contribution(runs, benchmark="gaia", version="v1", + datasets=datasets or {"first": None}, **options) + + def test_c2_most_distinct_tasks_then_latest_never_best_score(self): + large = run("large", ["resolved"] * 60 + ["agent_error"] * 40) + small = run("small", ["resolved"] * 10) + got = self.contribution([large, small]) + self.assertEqual((got.score, got.covered, got.run_ids), (.6, 100, ("large",))) + newer = replace(large, job_id="newer", finished_at=large.finished_at + timedelta(seconds=1), + trials=[trial(str(i), "agent_error") for i in range(100)]) + self.assertEqual(self.contribution([large, newer]).score, 0) + tied = replace(newer, job_id="aaa") + self.assertEqual(self.contribution([newer, tied]).run_ids, ("aaa",)) + + def test_c2_attempts_stay_together_without_repeat_pooling(self): + repeated = run("repeated", []) + repeated.trials = [trial(str(i), "resolved" if j == 0 else "agent_error", trial_name=f"{i}-{j}") + for i in range(10) for j in range(3)] + got = self.contribution([repeated]) + self.assertEqual(got.covered, 10) + self.assertAlmostEqual(got.score, 1 / 3) + + def test_c2_explicit_aliases_keep_the_canonical_tasks_attempts_together(self): + repeated = run("repeated", ["resolved", "agent_error"]) + got = self.contribution([repeated], {"first": {"0": "same", "1": "same"}}) + self.assertEqual((got.score, got.covered, got.total), (.5, 1, 1)) + + def test_c2_disjoint_overlap_and_dataset_slice(self): + first = run("first-run", ["resolved", "agent_error"]) + second = run("second-run", ["resolved", "resolved", "agent_error"], dataset="second") + manifests = {"first": {"0": "a", "1": "b"}, "second": {"0": "c", "1": "d", "2": "e"}} + got = self.contribution([first, second], manifests) + self.assertEqual((got.score, got.covered, got.total), (.6, 5, 5)) + manifests["second"]["0"] = "a" + got = self.contribution([first, second], manifests) + self.assertEqual((got.score, got.covered, got.total), (.5, 4, 4)) + self.assertEqual(self.contribution([first, second], manifests, dataset="first").score, .5) + + def test_c2_unknown_overlap_and_unavailable_slice_are_not_guessed(self): + runs = [run("a", ["resolved"]), run("b", ["resolved"], dataset="second")] + got = self.contribution(runs, {"first": None, "second": None}) + self.assertIsNone(got.score) + self.assertIsNone(got.total) + self.assertIn("identity", got.reason) + self.assertIsNone(self.contribution(runs, dataset="missing").score) + + def test_c2_explicit_merge_sources_count_once(self): + source = run("source", ["resolved"]) + merged = replace(source, job_id="merged", merged_from=["source"]) + self.assertEqual(self.contribution([source, merged]).run_ids, ("merged",)) + + def test_c3_pass_fail_infrastructure_and_missing(self): + got = self.contribution([run("a", ["resolved", "agent_error", "rate_limited"])]) + self.assertEqual((got.score, got.covered, got.excluded), (.5, 2, 1)) + self.assertIsNone(self.contribution([run("a", ["unknown", "rate_limited"])]).score) + + def test_c3_unknown_score_scale_is_not_used_as_a_pass_rate(self): + scored = run("scored", []) + scored.trials = [trial("task", "scored", score=2)] + self.assertIsNone(self.contribution([scored]).score) + + def test_c3_graded_crashes_parts_and_unsupported_scale(self): + graded = run("graded", ["agent_error"] * 9 + ["rate_limited"] * 2) + graded.trials.append(trial("grade", "scored", score=1, n_parts=1)) + got = self.contribution([graded], graded=True) + self.assertEqual((got.score, got.covered, got.excluded), (.1, 10, 2)) + self.assertEqual(got.note, "1 graded, 9 agent crashes; crashes count as 0") + weighted = replace(graded, trials=[trial("same", "scored", score=1, n_parts=3), + trial("same", "agent_error", n_parts=1)]) + self.assertEqual(self.contribution([weighted], graded=True).score, .75) + self.assertEqual(self.contribution([run("crash", ["agent_error"])], graded=True).score, 0) + for score in (0, None, 2, float("nan")): + with self.subTest(score=score): + value = replace(graded, trials=[trial("grade", "scored", score=score)]) + got = self.contribution([value], graded=True) + self.assertEqual(got.score, 0 if score == 0 else None) + + def test_c4_pass_cubed_keeps_existing_eligible_unit_semantics(self): + task = run("tau", []) + task.trials = [trial("same", trial_name=str(i)) for i in range(3)] + self.assertEqual(self.contribution([task], metric="pass^3").score, 1) + task.trials[-1].outcome = "agent_error" + self.assertEqual(self.contribution([task], metric="pass^3").score, 0) + task.trials.pop() + self.assertIsNone(self.contribution([task], metric="pass^3").score) + self.assertIsNone(self.contribution([run(str(i), ["resolved"]) for i in range(3)], metric="pass^3").score) + for metric in ("pass^2", "pass^4", "pass^5"): + with self.assertRaises(ValueError): + self.contribution([task], metric=metric) + + def test_c1_c4_only_completed_matching_version_contributes(self): + good = run("good", ["resolved", "agent_error"]) + for bad in (replace(good, preparing=True), replace(good, n_running_trials=1), + replace(good, finished_at=None), replace(good, agent_name="oracle"), + replace(good, agent_name="nop"), replace(good, identity={}), + replace(good, identity={"benchmark": "gaia", "benchmark_version": "v2"})): + with self.subTest(bad=bad): + self.assertIsNone(self.contribution([bad]).score) + self.assertEqual(self.contribution([good]).score, .5) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_leaderboard_weights.py b/app/tests/test_leaderboard_weights.py new file mode 100644 index 00000000..5cd9584d --- /dev/null +++ b/app/tests/test_leaderboard_weights.py @@ -0,0 +1,120 @@ +"""Profile scoring validates complete documents and normalizes measured sources.""" +import copy +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from nullius.leaderboard import configuration, weights + + +class WeightExamples(unittest.TestCase): + def test_c5_independent_weights_shares_and_missing(self): + self.assertEqual(weights.combine([(.5, 1), (1, 1)]), (.75, [0.5, 0.5])) + self.assertEqual(weights.combine([(.5, 3), (1, 1)]), (.625, [.75, .25])) + self.assertEqual(weights.combine([(.5, 3), (None, 1)]), (.5, [1, 0])) + self.assertEqual(weights.combine([(.625, 1), (0, 1)])[0], .3125) + self.assertEqual(weights.combine([(.625, 3), (0, 1)])[0], .46875) + self.assertEqual(weights.percent(.46875), "46.9%") + self.assertEqual(weights.combine([(.625, 1), (0, 0)])[0], .625) + self.assertEqual(weights.combine([(.5, 1), (1, 1)])[0], .75) + self.assertEqual(weights.combine([(.5, 1), (1, 0)])[0], .5) + self.assertEqual(weights.combine([(1, 0)]), (None, [0])) + + def test_c5_finite_weights_do_not_overflow_their_shares(self): + self.assertEqual(weights.combine([(.5, 1e308), (1, 1e308)]), (.75, [.5, .5])) + + def test_c7_unrounded_competition_ranks_and_groups(self): + rows = [{"key": key, "name": key, "overall": score, "reasons": reasons} + for key, score, reasons in [("partial", 1, ["GAIA 1 of 100 tasks"]), + ("a", .6, []), ("b", .6, []), ("c", .59999, []), + ("none", None, [])]] + result = weights.rank(rows) + self.assertEqual([(r["key"], r["rank"]) for r in result], + [("a", 1), ("b", 1), ("c", 3), ("partial", None), ("none", None)]) + self.assertEqual(weights.rank(rows, sort="name", descending=True)[0]["key"], "c") + + +class ConfigurationExamples(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.path = Path(self.directory.name) / "scoring.json" + self.benchmarks = [{"key": "gaia", "_version": "v1", "_default": "v1", "datasets": [{"id": "first"}], "score": {"kind": "pass"}}] + self.defaults = configuration.defaults(self.benchmarks) + + def test_c1_c5_all_fifteen_axes_and_defaults(self): + axes = self.defaults["axes"] + self.assertEqual(len(axes), 15) + self.assertEqual([axes[k]["weight"] for k in configuration.CAPABILITIES], [.12, .12, .08, .15, .15, .10, .08, .20]) + self.assertTrue(all(axes[k]["weight"] == 0 for k in configuration.DOMAINS)) + self.assertEqual(axes["Retrieval"]["entries"][0]["version"], "v1") + + def test_c19_invalid_values_preserve_stored_bytes(self): + configuration.save(self.path, self.defaults, self.benchmarks) + before = self.path.read_bytes() + for value in (-1, float("nan"), float("inf"), "abc", True): + draft = copy.deepcopy(self.defaults) + draft["axes"]["Retrieval"]["weight"] = value + with self.assertRaises(ValueError): + configuration.save(self.path, draft, self.benchmarks) + self.assertEqual(self.path.read_bytes(), before) + draft = copy.deepcopy(self.defaults) + for axis in draft["axes"].values(): + axis["weight"] = 0 + with self.assertRaises(ValueError): + configuration.save(self.path, draft, self.benchmarks) + draft = copy.deepcopy(self.defaults) + draft["axes"]["Retrieval"]["entries"] *= 2 + with self.assertRaises(ValueError): + configuration.save(self.path, draft, self.benchmarks) + + def test_c19_broken_settings_warn_without_overwrite_and_removed_references_survive(self): + self.path.write_text("{") + doc, warning = configuration.load(self.path, self.benchmarks) + self.assertEqual(doc, self.defaults) + self.assertIn("defaults", warning) + self.assertEqual(self.path.read_text(), "{") + configuration.save(self.path, self.defaults, []) + self.assertEqual(json.loads(self.path.read_text()), self.defaults) + + def test_c19_atomic_write_failure_preserves_valid_document(self): + configuration.save(self.path, self.defaults, self.benchmarks) + before = self.path.read_bytes() + with patch("nullius.ondisk.os.replace", side_effect=OSError("private path")): + with self.assertRaises(OSError): + configuration.save(self.path, self.defaults, self.benchmarks) + self.assertEqual(self.path.read_bytes(), before) + + def test_c20_custom_scores_names_stability_and_removal(self): + doc = copy.deepcopy(self.defaults) + doc["custom"] = [{"id": "calendar", "name": " Family calendar test ", "scores": {"A": 72, "B": 0, "C": None}}] + for axis in ("Personalization", "Home"): + doc["axes"][axis]["entries"] = [{"custom": "calendar", "weight": 1}] + clean = configuration.validate(doc, self.benchmarks) + self.assertEqual(clean["custom"][0]["name"], "Family calendar test") + for value in (120, -1, "abc", float("nan"), float("inf")): + bad = copy.deepcopy(doc) + bad["custom"][0]["scores"]["A"] = value + with self.assertRaises(ValueError): + configuration.validate(bad, self.benchmarks) + for name in ("", " "): + bad = copy.deepcopy(doc) + bad["custom"][0]["name"] = name + with self.assertRaises(ValueError): + configuration.validate(bad, self.benchmarks) + bad = copy.deepcopy(doc) + bad["custom"].append({"id": "second", "name": " family calendar TEST ", "scores": {}}) + with self.assertRaises(ValueError): + configuration.validate(bad, self.benchmarks) + clean["custom"][0]["name"] = "test" + renamed = configuration.validate(clean, self.benchmarks) + self.assertEqual(renamed["custom"][0]["scores"], {"A": 72, "B": 0, "C": None}) + removed = configuration.remove_custom(renamed, "calendar") + self.assertFalse(removed["custom"]) + self.assertFalse(removed["axes"]["Home"]["entries"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pyproject.toml b/pyproject.toml index 3c378979..6ab39768 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,7 @@ managed = false include-package-data = false packages = [ "nullius", "nullius.catalogue", "nullius.compare", "nullius.harbor", - "nullius.importers", "nullius.judge", "nullius.recipes", "nullius.runs", + "nullius.importers", "nullius.judge", "nullius.leaderboard", "nullius.recipes", "nullius.runs", "nullius.standard", "nullius.standard.backends", "nullius.standard.calls", "nullius.standard.contract", "nullius.standard.pages", "nullius.standard.proofs", "nullius.standard.protocols", "nullius.standard.requirements", "nullius.standard.runner", From c08209f2f619968fe0df459213483a1f52b7fcfe Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 25 Nov 2026 18:08:41 +0100 Subject: [PATCH 2/3] feat(web): connect leaderboard pages and command --- app/app.py | 4 +- app/nullius/catalogue/agents/codex/agent.json | 1 + .../catalogue/agents/digitalmate/agent.json | 1 + app/nullius/catalogue/agents/goose/agent.json | 1 + .../catalogue/agents/jiuwenswarm/agent.json | 1 + .../agents/mini-swe-agent/agent.json | 1 + .../catalogue/agents/opencode/agent.json | 1 + .../catalogue/agents/swe-agent/agent.json | 1 + .../catalogue/agents/terminus-2/agent.json | 1 + app/nullius/charts.py | 45 ++++-- app/nullius/cli.py | 2 + app/nullius/leaderboard/board.py | 41 ++++- app/nullius/leaderboard/cli.py | 54 +++++++ app/nullius/leaderboard/metrics.py | 47 ++++++ app/nullius/leaderboard/scoring.py | 2 +- app/nullius/leaderboard/service.py | 58 +++++++ app/nullius/standard/contract/definitions.py | 2 + app/packaging/verify.py | 2 + app/static/catalogue/agents/README.md | 4 +- app/static/catalogue/agents/digitalmate.svg | 1 + app/static/catalogue/agents/marks.json | 4 +- app/static/catalogue/agents/swe-agent.ico | Bin 0 -> 32038 bytes app/static/leaderboard/board.js | 148 ++++++++++++++++++ app/static/leaderboard/leaderboard.css | 63 ++++++++ app/static/leaderboard/scoring.js | 81 ++++++++++ app/static/tables.js | 5 +- app/templates/_icons.svg | 5 +- app/templates/base.html | 1 + app/templates/leaderboard/board.html | 43 +++++ app/templates/leaderboard/scoring.html | 16 ++ app/tests/field_contract.json | 3 + app/tests/test_categorical_charts.py | 23 +++ app/tests/test_leaderboard_board.py | 25 ++- app/tests/test_leaderboard_scoring.py | 6 +- app/tests/test_leaderboard_service.py | 92 +++++++++++ app/tests/test_standard_definitions.py | 5 + app/ui_tests/test_every_route.py | 7 +- app/ui_tests/test_leaderboard_routes.py | 118 ++++++++++++++ app/ui_tests/test_tables.py | 19 +++ app/web/leaderboard.py | 85 ++++++++++ docs/agents/add-manually.md | 3 + docs/cli/README.md | 2 +- docs/cli/pages.md | 2 + docs/cli/read-jobs.md | 25 +++ docs/field-guide.md | 56 +++++++ docs/settings/README.md | 38 +++++ pyproject.toml | 2 +- 47 files changed, 1115 insertions(+), 32 deletions(-) create mode 100644 app/nullius/leaderboard/cli.py create mode 100644 app/nullius/leaderboard/metrics.py create mode 100644 app/nullius/leaderboard/service.py create mode 100644 app/static/catalogue/agents/digitalmate.svg create mode 100644 app/static/catalogue/agents/swe-agent.ico create mode 100644 app/static/leaderboard/board.js create mode 100644 app/static/leaderboard/leaderboard.css create mode 100644 app/static/leaderboard/scoring.js create mode 100644 app/templates/leaderboard/board.html create mode 100644 app/templates/leaderboard/scoring.html create mode 100644 app/tests/test_leaderboard_service.py create mode 100644 app/ui_tests/test_leaderboard_routes.py create mode 100644 app/web/leaderboard.py diff --git a/app/app.py b/app/app.py index 101100cb..d0f4aa89 100644 --- a/app/app.py +++ b/app/app.py @@ -28,11 +28,11 @@ if __package__: # the wheel's private web namespace from .web.core import app from .web import shared - from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure + from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure, leaderboard else: # python app/app.py, and the source route suite from web.core import app from web import shared - from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure + from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure, leaderboard from nullius import execution, workspace # noqa: E402 - recorded runs, picked up again at start; the workspace left open diff --git a/app/nullius/catalogue/agents/codex/agent.json b/app/nullius/catalogue/agents/codex/agent.json index 0546056c..9ce68684 100644 --- a/app/nullius/catalogue/agents/codex/agent.json +++ b/app/nullius/catalogue/agents/codex/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "codex", "label": "Codex", + "company": "OpenAI", "summary": "OpenAI's coding agent.", "upstream": { "license": "Apache-2.0" diff --git a/app/nullius/catalogue/agents/digitalmate/agent.json b/app/nullius/catalogue/agents/digitalmate/agent.json index d5b17c23..a7a47346 100644 --- a/app/nullius/catalogue/agents/digitalmate/agent.json +++ b/app/nullius/catalogue/agents/digitalmate/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "digitalmate", "label": "DigitalMate", + "company": "ThinkFlowLab", "summary": "DigitalMate's Personal Agent service, run as Hive Home with its owned WorkSwarm runtimes.", "model": { "apis": [ diff --git a/app/nullius/catalogue/agents/goose/agent.json b/app/nullius/catalogue/agents/goose/agent.json index c20a9925..84462c5c 100644 --- a/app/nullius/catalogue/agents/goose/agent.json +++ b/app/nullius/catalogue/agents/goose/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "goose", "label": "Goose", + "company": "Agentic AI Foundation", "summary": "The AAIF's open-source agent, formerly Block's.", "upstream": { "package": "@aaif/goose-acp", diff --git a/app/nullius/catalogue/agents/jiuwenswarm/agent.json b/app/nullius/catalogue/agents/jiuwenswarm/agent.json index 42a257bd..c9b7e460 100644 --- a/app/nullius/catalogue/agents/jiuwenswarm/agent.json +++ b/app/nullius/catalogue/agents/jiuwenswarm/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "jiuwenswarm", "label": "JiuwenSwarm", + "company": "openJiuwen", "summary": "openJiuwen's WorkSwarm agent.", "start": { "acp": [ diff --git a/app/nullius/catalogue/agents/mini-swe-agent/agent.json b/app/nullius/catalogue/agents/mini-swe-agent/agent.json index d7d51c83..4bec14f0 100644 --- a/app/nullius/catalogue/agents/mini-swe-agent/agent.json +++ b/app/nullius/catalogue/agents/mini-swe-agent/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "mini-swe-agent", "label": "mini-swe-agent", + "company": "Princeton and Stanford", "summary": "Princeton's 100-line agent, bash only.", "upstream": { "package": "mini-swe-agent", diff --git a/app/nullius/catalogue/agents/opencode/agent.json b/app/nullius/catalogue/agents/opencode/agent.json index 42a873ab..f83d5ccc 100644 --- a/app/nullius/catalogue/agents/opencode/agent.json +++ b/app/nullius/catalogue/agents/opencode/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "opencode", "label": "OpenCode", + "company": "Anomaly", "summary": "The open-source terminal coding agent.", "upstream": { "package": "opencode-ai", diff --git a/app/nullius/catalogue/agents/swe-agent/agent.json b/app/nullius/catalogue/agents/swe-agent/agent.json index 3b33e010..5fca9fb3 100644 --- a/app/nullius/catalogue/agents/swe-agent/agent.json +++ b/app/nullius/catalogue/agents/swe-agent/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "swe-agent", "label": "SWE-agent", + "company": "Princeton and Stanford", "summary": "Princeton\u2019s software engineering agent with its upstream tool bundles.", "upstream": { "repository": "https://github.com/SWE-agent/SWE-agent", diff --git a/app/nullius/catalogue/agents/terminus-2/agent.json b/app/nullius/catalogue/agents/terminus-2/agent.json index de10d38d..434dd219 100644 --- a/app/nullius/catalogue/agents/terminus-2/agent.json +++ b/app/nullius/catalogue/agents/terminus-2/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "terminus-2", "label": "Terminus 2", + "company": "Harbor", "summary": "Harbor's terminal agent, used by Terminal-Bench.", "upstream": { "package": "harbor", diff --git a/app/nullius/charts.py b/app/nullius/charts.py index 849d270b..60a5aed9 100644 --- a/app/nullius/charts.py +++ b/app/nullius/charts.py @@ -47,6 +47,7 @@ class Value: baseline: bool = False tag: str = "" # a short name, where the full one does not fit (a scatter's dot) series: int = 0 # its colour, 1 on, the same in every chart; 0 for none + key: str = "" def cls(self, shape: str) -> str: """A mark's classes: its shape, its series (``s1`` to ``s``, cycling) and whether it is a check.""" @@ -105,6 +106,7 @@ class Mark: y2: float = 0.0 cls: str = "" title: str = "" + key: str = "" @dataclass(frozen=True) @@ -115,6 +117,7 @@ class Text: anchor: str = "start" cls: str = "" leading: float = _LINE + key: str = "" @dataclass(frozen=True) @@ -256,24 +259,25 @@ def dot(v, scale, mid): _TAG_W, _TAG_H = 7.5, 13.0 # a tag's width per character and its height, at the template's font size -def _tag_box(px: float, py: float, width: float, side: str) -> tuple: +def _tag_box(px: float, py: float, width: float, side: str, radius=_DOT, extra=0) -> tuple: """Where a tag ``width`` wide goes on ``side`` of a dot at (px, py): (x, baseline, anchor, box).""" - gap = _DOT + 3 + gap = radius + 3 x, base, anchor = {"right": (px + gap, py + 4, "start"), "left": (px - gap, py + 4, "end"), - "above": (px, py - gap - 2, "middle"), "below": (px, py + gap + 10, "middle")}[side] + "above": (px, py - gap - 2 - extra, "middle"), "below": (px, py + gap + 10, "middle")}[side] x0 = {"start": x, "end": x - width, "middle": x - width / 2}[anchor] - return x, base, anchor, (x0, base - _TAG_H + 3, x0 + width, base + 3) + return x, base, anchor, (x0, base - _TAG_H + 3, x0 + width, base + 3 + extra) def _overlaps(a: tuple, b: tuple) -> bool: return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] -def scatter(x: Metric, y: Metric) -> Panel: +def scatter(x: Metric, y: Metric, *, tiles=False) -> Panel: """A dot per item at (x, y), and its tag (``Value.tag``, else its place in the order) beside it, spelled out in a key under the plot. Every item keeps its own dot: items at one place are set in a ring around it, each tag outward from its dot. Any other tag takes the first side of its dot inside the plot and clear of the dots and tags before it.""" + radius = 11 if tiles else _DOT pairs = list(zip(x.values, y.values)) tags = [a.tag or str(i + 1) for i, (a, _) in enumerate(pairs)] shown = [(t, a, b) for t, (a, b) in zip(tags, pairs) if a.value is not None and b.value is not None] @@ -291,29 +295,42 @@ def scatter(x: Metric, y: Metric) -> Panel: places.setdefault((sx(item[1].value), sy(item[2].value)), []).append(item) dots = [] # (x, y, the tag's place on its ring or None, tag, x value, y value) for (px, py), group in places.items(): - ring = max(_DOT * 2, len(group) * (2 * _DOT + 4) / (2 * math.pi)) if len(group) > 1 else 0.0 + ring = max(radius * 2, len(group) * (2 * radius + 4) / (2 * math.pi)) if len(group) > 1 else 0.0 for k, item in enumerate(group): turn = 2 * math.pi * k / len(group) - math.pi / 2 at = (round(px + (ring + 11) * math.cos(turn), 2), round(py + (ring + 11) * math.sin(turn) + 4, 2)) if ring else None dots.append((round(px + ring * math.cos(turn), 2), round(py + ring * math.sin(turn), 2), at, *item)) - taken = [(px - _DOT, py - _DOT, px + _DOT, py + _DOT) for px, py, *_ in dots] - taken += [(tx - _TAG_W, ty - _TAG_H + 3, tx + _TAG_W, ty + 3) for _, _, (tx, ty), *_ in (d for d in dots if d[2])] + if tiles: + placed = [] + for px, py, *rest in dots: + candidates = [(max(left + radius, min(right - radius, px + dx)), + max(top + radius, min(bottom - radius, py + dy))) + for distance in range(0, 100, 2) + for dx, dy in ((distance, 0), (-distance, 0), (0, distance), (0, -distance))] + px, py = next(((cx, cy) for cx, cy in candidates if all(math.hypot(cx-ox, cy-oy) >= 2*radius+2 for ox, oy, *_ in placed)), candidates[-1]) + placed.append((px, py, *rest)) + dots = placed + taken = [(px - radius, py - radius, px + radius, py + radius) for px, py, *_ in dots] + taken += [(tx - _TAG_W, ty - _TAG_H + 3, tx + _TAG_W, ty + 3) for _, _, (tx, ty), *_ in (d for d in dots if d[2] and not tiles)] for px, py, at, tag, a, b in dots: - marks.append(Mark("circle", px, py, r=_DOT, cls=a.cls("dot"), + marks.append(Mark("tile" if tiles else "circle", px, py, r=radius, cls=a.cls("dot"), key=a.key, title=f"{tag} {a.name}: {x.label} {a.reading}, {y.label} {b.reading}")) - if at: # on a ring, the tag sits outward from its dot + if at and not tiles: # on a ring, the tag sits outward from its dot texts.append(Text(*at, (tag,), "middle", "tag")) continue - width = _TAG_W * len(tag) - spots = [_tag_box(px, py, width, side) for side in ("right", "left", "above", "below")] + width = _TAG_W * max(len(tag), len(a.note) if tiles else 0) + extra = 15 if tiles and a.note else 0 + offsets = [0] if not tiles else [0] + [sign*d for d in range(15, 211, 15) for sign in (1, -1)] + spots = [_tag_box(px, py + offset, width, side, radius, extra) + for offset in offsets for side in ("right", "left", "above", "below")] inside = [s for s in spots if s[3][0] >= left and s[3][2] <= right and s[3][1] >= top and s[3][3] <= bottom] tx, base, anchor, box = next((s for s in inside if not any(_overlaps(s[3], t) for t in taken)), (inside or spots)[0]) taken.append(box) - texts.append(Text(tx, base, (tag,), anchor, "tag")) + texts.append(Text(tx, base, (tag, a.note) if tiles and a.note else (tag,), anchor, "tag", key=a.key)) key_y = _S_HEIGHT + 8 key = _LEFT + (12 if any(a.series for a, _ in pairs) else 0) drawn = {id(d[4]) for d in dots} - for tag, (a, _) in zip(tags, pairs): + for tag, (a, _) in ([] if tiles else zip(tags, pairs)): # a name the caller numbered already (two runs of one agent) is not numbered twice lines = tuple(textwrap.wrap(a.name if a.name.startswith(f"{tag}. ") else f"{tag}. {a.name}", _CHARS)) if a.series: # its colour beside its name diff --git a/app/nullius/cli.py b/app/nullius/cli.py index aa960909..708a46c2 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -15,6 +15,7 @@ "serve": "open the web application", "runs": "inspect run output", "compare": "compare runs", + "leaderboard": "workspace composite agent scores", "flags": "write a run's task flags", "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", @@ -26,6 +27,7 @@ MODULES = { "runs": "nullius.runs.cli", "compare": "nullius.compare.cli", + "leaderboard": "nullius.leaderboard.cli", "flags": "nullius.runs.flags_cli", "import": "nullius.importers.cli", "standard": "nullius.standard.cli", diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py index 63cab7bd..a9c00d8c 100644 --- a/app/nullius/leaderboard/board.py +++ b/app/nullius/leaderboard/board.py @@ -3,11 +3,37 @@ import hashlib import json +import copy +from dataclasses import replace from math import isfinite +from nullius.standard.contract import definitions from . import configuration, scoring, weights +def project(jobs, agents, benchmarks, settings, benchmark, version, *, all_scores=False): + """A comparison projection: missing changed evidence invalidates its affected axis.""" + draft = copy.deepcopy(settings) + affected = set() + for name, axis in draft["axes"].items(): + for entry in axis["entries"]: + if entry.get("benchmark") == benchmark: + entry["version"] = version + if entry["weight"] > 0: + affected.add(name) + result = build(jobs, agents, benchmarks, draft, all_scores=all_scores) + for row in result["rows"]: + for name in affected: + axis = row["axes"][name] + if any(e.get("benchmark") == benchmark and e["weight"] > 0 and e["score"] is None for e in axis["entries"]): + axis["score"] = None + axis["share"] = 0 + if axis["weight"] > 0: + row["overall"] = None + row["rank"] = None + return result + + def row_identity(job): identity = job.identity limits = {k: v for k, v in identity.get("limits", {}).items() @@ -30,7 +56,7 @@ def _entry_key(entry): return tuple(entry.get(k, "") for k in ("benchmark", "dataset", "version", "metric")) -def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_open=True): +def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_open=True, metric_sources=None): """Pure board projection. Inputs belong to a single workspace and profile.""" config = configuration.validate(settings, benchmarks) agents = [a for a in agents if not a.get("example") and a["key"] not in ("nop", "oracle")] @@ -47,6 +73,8 @@ def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_ope identities[key] = identity measured_agents = {identity["agent"] for identity in identities.values()} for agent in agents: + if agent.get("_version", "") != agent.get("_default", agent.get("_version", "")): + continue if agent["key"] in measured_agents: continue identity = {"agent": agent["key"], "version": agent.get("_version", ""), "catalogue_only": True} @@ -59,6 +87,8 @@ def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_ope row = {"key": key, "agent": identity["agent"], "name": agent["label"], "company": agent.get("company", ""), "version": identity["version"], "identity": identity, "has_runs": bool(runs), "axes": {}, "metrics": _empty_metrics(), "reasons": [], "custom_names": []} + matching = next((a for a in agents if a["key"] == identity["agent"] and a.get("_version", "") == identity["version"]), None) + row["version_label"] = definitions.version_label(matching) if matching else identity["version"] trials = {} for name in configuration.AXES: axis = config["axes"][name] @@ -79,7 +109,10 @@ def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_ope evidence["reason"] = "Benchmark version unavailable" else: manifests = {d["id"]: d.get("tasks") if isinstance(d.get("tasks"), dict) else None for d in bench.get("datasets", [])} - got = scoring.contribution(runs, benchmark=entry["benchmark"], version=entry["version"], datasets=manifests, + # The standard writes benchmark/dataset; only remove this exact declared prefix. + recorded = {f"{bench['key']}/{d}": d for d in manifests} + normalized = [replace(j, dataset=recorded.get(j.dataset, j.dataset)) for j in runs] + got = scoring.contribution(normalized, benchmark=entry["benchmark"], version=entry["version"], datasets=manifests, dataset=entry["dataset"], metric=entry["metric"], graded=bench.get("score", {}).get("kind") == "score") evidence.update(score=got.score, tasks=got.total, covered=got.covered, excluded=got.excluded, runs=list(got.run_ids), reason=got.reason, note=got.note) @@ -104,8 +137,10 @@ def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_ope values = [getattr(t, field) for t in trials.values() if getattr(t, field) is not None and isfinite(getattr(t, field)) and getattr(t, field) >= 0] row["metrics"][metric] = {"value": sum(values) / len(values) if values else None, "count": len(values)} rows.append(row) + if metric_sources is not None: + metric_sources[key] = tuple(dict.fromkeys(t.trajectory_path for t in trials.values())) required = {name: {_entry_key(e) for row in rows for e in row["axes"][name]["entries"] - if "custom" not in e and e["available"] and e["weight"] > 0 and e["score"] is not None} + if "custom" not in e and e["available"] and e["weight"] > 0 and e["runs"]} for name in configuration.AXES if config["axes"][name]["weight"] > 0} for row in rows: for name, entries in required.items(): diff --git a/app/nullius/leaderboard/cli.py b/app/nullius/leaderboard/cli.py new file mode 100644 index 00000000..2ada66d5 --- /dev/null +++ b/app/nullius/leaderboard/cli.py @@ -0,0 +1,54 @@ +"""Read workspace composite scores without launching evaluations.""" +from __future__ import annotations + +import argparse +import json +import os +import sys + +from nullius.runs import parse +from . import configuration, service, weights + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="nullius leaderboard", description=__doc__, + epilog="Configuration: scoring.json in the profile configuration directory (nullius paths). Edit it through Scoring settings or as a complete JSON document. Exit 0: read; 2: usage; 3: missing root. Unavailable measurements and invalid-settings fallback are disclosed in the output.") + parser.add_argument("roots", nargs="*", help="result roots in one workspace; omit for unscored catalogue rows") + parser.add_argument("--json", action="store_true", help="full precision scores, identity, evidence, ranks/reasons and observed metric counts") + parser.add_argument("--all-scores", action="store_true", help="include unverified manual scores; default: verified only") + args = parser.parse_args(argv) + if any(not os.path.isdir(root) for root in args.roots): + print("A result root does not exist or is not a directory.", file=sys.stderr) + return 3 + result = service.document(parse.load_all(args.roots), workspace_open=bool(args.roots), all_scores=args.all_scores, deferred=True) + if args.json: + print(json.dumps(result, ensure_ascii=False, allow_nan=False)) + else: + if result["warning"]: + print(result["warning"]) + if result["empty"]: + print(result["empty"]) + for row in result["rows"]: + print(f"{row['rank'] or ''}\t{row['name']}\t{row['company']}\t{row['version_label']}\t{weights.percent(row['overall'])}") + setup = " · ".join(str(row["identity"][key]) for key in ("model", "effort") if row["identity"].get(key)) + if setup: + print(f" {setup}") + for name in configuration.AXES: + axis = row["axes"][name] + print(f" {name}: {weights.percent(axis['score'])} · weight {axis['weight']:g} · share {weights.percent(axis['share'])}") + for entry in axis["entries"]: + version = f" · {entry['version'] or 'Official'}" if "custom" not in entry else "" + reading = weights.percent(entry["score"]) if entry["score"] is not None else entry["reason"] + trust = " · not verified" if entry["unverified"] else "" + tasks = f" · {entry['covered']}/{entry['tasks']} tasks" if entry["tasks"] is not None else "" + runs = " · runs " + ", ".join(entry["runs"]) if entry["runs"] else "" + print(f" {entry['name']}{version} · {reading}{trust} · weight {entry['weight']:g} · share {weights.percent(entry['share'])}{tasks}{runs}") + for reason in row["reasons"]: + print(f" Not ranked: {reason}") + for metric, data in row["metrics"].items(): + print(f" {metric}: {data['value'] if data['value'] is not None else 'unavailable'} ({data['count']} observed)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/nullius/leaderboard/metrics.py b/app/nullius/leaderboard/metrics.py new file mode 100644 index 00000000..5abfd836 --- /dev/null +++ b/app/nullius/leaderboard/metrics.py @@ -0,0 +1,47 @@ +"""Deferred trajectory counts, cached by file identity and content digest.""" +from __future__ import annotations + +import hashlib +from pathlib import Path +from threading import RLock + +from nullius.traces import trajectory + + +class Cache: + def __init__(self): + self._entries = {} + self._lock = RLock() + + def read(self, path): + missing = {"steps": None, "calls": None} + try: + target = Path(path) + info = target.stat() + signature = (info.st_dev, info.st_ino, hashlib.sha256(target.read_bytes()).hexdigest()) + except OSError: + return missing + with self._lock: + previous = self._entries.get(path) + if previous and previous[0] == signature: + return dict(previous[1]) + try: + trace = trajectory.load(path) + result = missing if trace.error else {"steps": trace.n_steps, "calls": trace.n_tool_calls} + # A writer may have changed the file while its parser read it. + if hashlib.sha256(target.read_bytes()).hexdigest() != signature[2]: + return missing + except (OSError, ValueError, TypeError, KeyError): + result = missing + self._entries[path] = (signature, result) + return dict(result) + + def complete(self, document, sources): + for row in document["rows"]: + observations = [self.read(path) for path in sources.get(row["key"], ())] + for field in ("steps", "calls"): + values = [o[field] for o in observations if o[field] is not None] + row["metrics"][field] = {"value": sum(values) / len(values) if values else None, "count": len(values)} + + +CACHE = Cache() diff --git a/app/nullius/leaderboard/scoring.py b/app/nullius/leaderboard/scoring.py index 67023d7d..69f048a5 100644 --- a/app/nullius/leaderboard/scoring.py +++ b/app/nullius/leaderboard/scoring.py @@ -81,7 +81,7 @@ def contribution(jobs: Sequence[Job], *, benchmark: str, version: str, total = len({canonical for manifest in manifests for canonical in manifest.values()}) if all(m is not None for m in manifests) else None pool = [j for j in jobs if eligible(j) and j.dataset in scope and j.identity.get("benchmark") == benchmark - and j.identity.get("benchmark_version") == version] + and j.identity.get("benchmark_version", "") == version] sources = {source for j in pool for source in j.merged_from} pool = [j for j in pool if j.job_id not in sources] selected = {} diff --git a/app/nullius/leaderboard/service.py b/app/nullius/leaderboard/service.py new file mode 100644 index 00000000..8e0d1c99 --- /dev/null +++ b/app/nullius/leaderboard/service.py @@ -0,0 +1,58 @@ +"""Catalogue and profile inputs shared by the Leaderboard page and command.""" +from __future__ import annotations + +import hashlib +import json +from dataclasses import asdict +from urllib.parse import quote + +from nullius.standard.contract import definitions +from nullius import charts +from . import board, configuration, metrics, weights + + +def catalogue(): + return definitions.load("agent", every=True)[0], definitions.load("benchmark", every=True)[0] + + +def revision(): + try: + raw = configuration.location().read_bytes() + except FileNotFoundError: + raw = b"" + return hashlib.sha256(raw).hexdigest() + + +def options(benchmarks): + return [{"key": b["key"], "label": b["label"], "version": b.get("_version", ""), + "version_label": definitions.version_label(b), "metrics": ["Score", "pass^3"] if b.get("score", {}).get("kind") == "pass" else ["Score"], + "datasets": [{"id": d["id"], "label": d.get("label", d["id"])} for d in b.get("datasets", [])]} + for b in benchmarks] + + +def document(jobs, *, workspace="", workspace_open=False, all_scores=False, deferred=False): + agents, benchmarks = catalogue() + settings, warning = configuration.load(configuration.location(), benchmarks) + sources = {} + result = board.build(jobs, agents, benchmarks, settings, all_scores=all_scores, workspace_open=workspace_open, metric_sources=sources) + context = {"workspace": workspace, "settings": settings, "all_scores": all_scores, + "jobs": [(j.job_id, j.uid, str(j.finished_at), len(j.trials), j.identity, j.dir) for j in jobs]} + result["context"] = hashlib.sha256(json.dumps(context, sort_keys=True).encode()).hexdigest() + result["warning"], result["revision"] = warning, revision() + result["versions"] = [{"benchmark": b["key"], "version": b.get("_version", ""), + "label": b["label"] + " · " + (definitions.version_label(b) or "Official")} + for b in benchmarks if any(e.get("benchmark") == b["key"] for a in settings["axes"].values() for e in a["entries"])] + for row in result["rows"]: + for axis in row["axes"].values(): + for entry in axis["entries"]: + entry["links"] = [{"id": id, "url": "/job/" + quote(id, safe="") + ("?workspace=" + quote(workspace, safe="") if workspace else "")} for id in entry["runs"]] + if deferred: + metrics.CACHE.complete(result, sources) + result["scatter"] = {} + for field, label in (("time", "Time (seconds)"), ("cost", "Cost (USD)")): + x = charts.Metric(label, tuple(charts.Value(r["name"], r["metrics"][field]["value"], str(r["metrics"][field]["value"]), + note=r["version_label"], tag=r["name"], key=r["key"]) for r in result["rows"]), bounds=(0, None)) + y = charts.Metric("Overall", tuple(charts.Value(r["name"], r["overall"], weights.percent(r["overall"])) for r in result["rows"]), + fmt=lambda v, step, top: weights.percent(v), bounds=(0, 1)) + result["scatter"][field] = asdict(charts.scatter(x, y, tiles=True)) + return result diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index ad5f8918..5ffe7d8c 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1552,6 +1552,8 @@ def problems(d: dict, kind: str) -> List[str]: bad.append(f"{f}: say it") if "example" in d and (kind == "benchmark" or not isinstance(d["example"], bool)): bad.append("example: true or false, an agent's or a capability's") + if "company" in d and (kind != "agent" or not isinstance(d["company"], str) or not d["company"].strip()): + bad.append("company: nonempty text on an agent definition") bad += _upstream(d.get("upstream")) if kind == "benchmark": if d.get("family") not in FAMILIES: diff --git a/app/packaging/verify.py b/app/packaging/verify.py index 8df53432..49f6ab86 100644 --- a/app/packaging/verify.py +++ b/app/packaging/verify.py @@ -59,6 +59,8 @@ def digest(): web.app.config.update(TESTING=True) client = web.app.test_client() pages = ['/', '/benchmarks', '/agents', '/capabilities', '/settings', + '/leaderboard', '/scoring', '/api/leaderboard', '/api/scoring', + '/static/catalogue/agents/swe-agent.ico', '/static/catalogue/agents/digitalmate.svg', '/static/style.css', '/static/fonts/DMSans-Regular.woff2', '/static/fonts/dmsans-OFL.txt', '/static/brand/favicon.svg', '/static/brand/typesafe.png'] diff --git a/app/static/catalogue/agents/README.md b/app/static/catalogue/agents/README.md index 35fd9b58..d4210226 100644 --- a/app/static/catalogue/agents/README.md +++ b/app/static/catalogue/agents/README.md @@ -7,6 +7,8 @@ rendering a logo makes no request to its upstream website. | Agent | Asset source | | --- | --- | +| DigitalMate | ThinkFlowLab supplied ThinkFlow Orbit artwork: cream rounded tile, charcoal orb and ring, orange satellite (`digitalmate.svg`) | +| SWE-agent | [Official repository favicon](https://github.com/SWE-agent/SWE-agent/blob/3ea751c087f32b16e039a2233dd6eefecef325d5/docs/assets/favicon.ico), copied unchanged (`swe-agent.ico`) | | Codex | OpenAI's mark in `../../brand/marks.svg`, identifying its maker | | Goose | [Official repository logo](https://github.com/block/goose/blob/775b3958c394ae2747cfb01791d3a45ac579139a/documentation/static/img/logo.svg) | | JiuwenSwarm | [Official application logo](https://github.com/openJiuwen-ai/jiuwenswarm/blob/ffc539d74ba6fe034c60b6eac5ae3ea1da04b7dc/jiuwenswarm/channels/web/frontend/public/logo.svg) | @@ -14,5 +16,5 @@ rendering a logo makes no request to its upstream website. | OpenCode | [Official favicon](https://github.com/anomalyco/opencode/blob/66f1fa816d583fdfa0f52eff1c7d56c8458b1c4e/packages/ui/src/assets/favicon/favicon.svg) | | Terminus 2 | Harbor's mark in `../../brand/marks.svg`, identifying its maker | -The four SVG files are copied unchanged from these pinned sources. These marks +Upstream assets are copied unchanged from these pinned sources. These marks belong to their respective owners; inclusion does not imply endorsement. diff --git a/app/static/catalogue/agents/digitalmate.svg b/app/static/catalogue/agents/digitalmate.svg new file mode 100644 index 00000000..0354755a --- /dev/null +++ b/app/static/catalogue/agents/digitalmate.svg @@ -0,0 +1 @@ +ThinkFlow Orbit diff --git a/app/static/catalogue/agents/marks.json b/app/static/catalogue/agents/marks.json index e1dda87d..8c4b41d4 100644 --- a/app/static/catalogue/agents/marks.json +++ b/app/static/catalogue/agents/marks.json @@ -4,5 +4,7 @@ "mini-swe-agent": "catalogue/agents/mini-swe-agent.svg", "opencode": "catalogue/agents/opencode.svg", "codex": "brand/marks.svg#openai", - "terminus-2": "brand/marks.svg#harbor" + "terminus-2": "brand/marks.svg#harbor", + "digitalmate": "catalogue/agents/digitalmate.svg", + "swe-agent": "catalogue/agents/swe-agent.ico" } diff --git a/app/static/catalogue/agents/swe-agent.ico b/app/static/catalogue/agents/swe-agent.ico new file mode 100644 index 0000000000000000000000000000000000000000..b3342de034648b9000fa7e7e72bb750e67a50421 GIT binary patch literal 32038 zcmeI*1+-k%^)T>Ri~ z-_o*6{;gN9U%vNfX_oYL1nrS#=LQ~Kf`!|(0+-8F{ifEnyR|EB?hZJhdd#{2tx?^nM8&V%zf==$MT zKcTEpS{f29Pc_Pl<|^cp;z@gAJvf#d5RewHr0;+nL{7F(x97VDc9 zTVkoS&q0T!X9vEUT+?0rfR=Fj>EDeh@Xvg{JIAcfVen+0>p|cCEB)<>=K{~!=bS5z zGRi0^ug78DGtM+~I_b=F(z~C26LhFPrz@Yo%yjri8#FNQ!vps+*8@NJEM0K<)oHc0 z)=d-rVd7!%t;OH>kwzLREwS{n>DpWGPM?1N@AOsXhpymW?nQ%IKCm{rljqA^|2@z3 z{f|GJ_CDZ{G}|0={%WpA9C5@nL+_c=rdw^B`tQAe+G)2v(gF)F8n_plj63dlY4dHi zPmewSTCADwm?OAWY2=!9J!0nP8GFy1w%d8vbk2pBrN>?vm<~Afs5HTZ6QxNe z{bSH-|3i*Q`yPCF{C?Gqx2G+)+cAwhUXNBfj4;9oX^}pQr@J3~B7NCK9RX*$@yAZi zeVOam-v2b6cju*VyUUO4A>-T9o?CjH}Nt+>uS>ukXX_-M&xmro;)JaX%~l~-Rg4f^iqF7qtD z|E2?U96HxOrTZRxChfWZL1~uR=E$%OE5pgI>1XVnw(qxF`qOzAr$df9E-jk%+gM|d zo>KBx$A9)<}CDa7fy9&wbM-TW*t%KIycy_Iewp&9>ey%{|}zt$2<#*4T0H%kO-g zPX5zh5}J?;eflmLwnA6ds(aZ;?cx2Qb3G`Xd&!k)mDShEb3IWjoJCfRKf#1)`IS~l z$LIC?*bA?vBl3EkvgcH3%rVDGbImhftn&-6xHesM<#lPg8D>mm8=ZgEO?RZvfBbK( z>zCgCDDASxK531$*9)0Q_K}JE9C&DY=GC{;rkP%Sms%!${PjP(JpYYksrB`B=8sP@ zgZ%Z;r_&z$9+>BP_F?!i^i<}{nP-_TWcQipUX%_z{OGj!l1rx*S6Myg{@^2z4c^~k z+Z_^pKlv0>ro)aoAzgFJow1JDeQcpZV|o&eS6p@V;FSq7O_y4Bg>?9_C#JJ6xHK)Z z{7PxtopuR&b#?yh-Cy8%^}RtMn^#_K&5%)Lj?0nU0^>0!pPo)T`@FQ#W?KesV~jE8 zFLS+nI_9L)(2R@C*k<=U{8YebtyN_XynUZ#_Bm3&-S^Hi>ymWf zVMnJ0GhWu|ktePnIyf9R2Eg_T!J^DeMpI`a6FWA4el-Sau}3cm2a^MS|G`PmM{ zFH=u5ZKmB=S$C`zcG6jyzqj0W$KaLavd%c+^t02mue}re!B1+mUaNTc%wELHAAb2m zdiA}(r?&?Uj{EERR-Vh&o_pS*vX@&K_ByKom=B$k3CMdX(o+zaR1}aWx2n5*tz43J8qU=D~9cJ{q6UrEwXH% zf5C-ApU{&pzx{E*X5QL6*RCrv>$SYbF1+&Eyp}c`#+E32?6~H-8-(txKHq2azi^+$ z(l$Hx3%apS#vW&!z;DA%w+Q}rZM4yXzizqbfy7Vf=v){6{@{!6)9v>?9CJ%QRsBhJh`EDD zp}`bW_Ds*c{@$dzPt#%OH`^R@h2H$j#aE{FHrh1S4*##`R8xm;n|P8*gNAIm z>UZxh5zDtE2QSf6UPdQbuwC;wRgkE~+>6c;-%6T^CQ!l^y zEBuXxru?j3_u4m|de*ri&&g`Ki(bF_<~w6O{Bg3$gPwEDHFx;5+zk7k&S&DZfP^cyqFzoSn)HS~Es8u$&)?4#%3ct6(KYHO_%K10FD zkq@z2meF+ajd$J`JW6+;nAfp)xwaAhg$88hu_vDq{)hGCv-r%`JM0|(&16$d5%X%T zvrpiDN~V{%1>c0sHV1V4fb7S-lb>ge!sE4USKzP5Uwl1mIO_?2f)S4J^)72#jOg;~ zZVA6(nk;Mh%mtSo<4=%nqvg|ar<|GY_}in|j=Vi=1-3WdcOCt6!s%zV-ZSZBdH!E{ ztM2?4eltE;$SCWZe#7_lqqS@e-E{ZgVy?-2xbNJ5uk5ob>~K=RHxwBB~dUBY*wFWI&9{LNV|^vn9g+8Q;>ih?uyiVk8s+x}J*2A*RM%*j0uKbfZJ*)uJ)NS|15^di5=8lv0p zdhqd>$MQT!&%Exod%~xC?fpTCUMK&~_{#;MBgjm+&>;opsz2pkx{W?wbKUhr&y?%x z9qZx$bd&k7!b|3mH*7kzV~f&zVich>GOYZWVn1Ab)%BU*zs~x0p3p_#eg19M0fR$+&NJTv>B<{!O>cejW!Ug!==3x6Zq?J)(h z;qRhrn&H{j`8~Q}{^4&9`8#9}JBogEIJ8}s$-+@h048-4WbE3F!KKYM85K8q)^5Y5n5`THJpc;Lu(GH**~`<|aHCe}a8fcHQDE`6J0tgdG_l6mmuTlJo4 zmasRUeCdr=+~JSb;=)y3U&W~-pSz0xXL$~fJ>`txd$B6KEQVv=#pKummt1v2%r$*Z zchd)aDDg0{Pj-Ykg_k*Y&9ejFNqn)$ZR9l%@A9S-Z_T#2xLHSVt#@r#@D~FktHtWX zE5)VEopJWdYy6XM{+V{ku^cfz@!QL2Tpag-C!Y_zi)^dKwXN^yD#l`5G-n&JkLjJ!M<1iz zwAf?61G{Yh;74)k6;@d-{2eh!Icl*xa+)j?*ApLLC*y~+FSsnNwcdu=HrTR5b6@B| zRt$+HFO%)#pJMHhMIYpNR!4LLd!?)PU*Q9}H?hx&b8Lq`JM`$|L+{=8*N4JJHQ#c! z=AZm4^1xgcyxMz2b7QTZ^`m>xpMQ)0#EUR4C8T+@ujE6t_;Xmn~hn|dB zwV0;(*R<2k5OH8J4)!KKW!GMI?M>m|m`nPxBWr+cWk2&j$q{lG@3S$*UJ5?Vj@^lW zp@X?07e4s%`|#sqPO`ltc4q$hC+t9R4{@P$FByjpv$oKK(lMikw0-yvzCFfq#Lw=rQmXocQl#1DcpSd2aCyc|W-V{-b=rlUXNx z{PjNqw`yz~efSP?KH@j7DSYE-96VO=Yjzxh|IqkHSNOl+-RxNA7_9Qcy=R^!;B}mH zo_WKrV<+Qpc7%A9{D|kWG09B+&%KX4-8%PWOunKRax=Wk`QHQo0;~CgkGL#&=m+|- zz*dg(UHl_HwK&@hGtLyTEOac-au=N)e=!j<^xz|ojrdu~`H=(G%BZ7` z+KNlTsnJmkU#zNJ^IPLD?jZ+ieDPp$%K}TYquLj-cXbl#0XmAi=Zi!Aui(#qQS;Lb z@9sSR`{Vyr#IWJSj}jm3PW+lZ>wgJ->l#j+FS~ z;y2})-!2U!|TYllB+rYva2IkveK$+w2tYV zI;!6T|K(O(CF&c82i|H*mt1D~;B__Bm(=odXTHb$4;mb`5S_uF-^?FUCm|OomZ;uP zT%lUi;@P8(HhP*p*Idx|Y5~M1B2Mv3?4T|9+f)DA*1gSshrhgu92XenMw-q4D5H!T z{vw-K4&cd`-$)k?xGv;5-Q_vuZ7rxfQxmI}T8@QWulh}mU<6-IYYyXMHoCr}=L-I0 zZs4C|A@%T&nw_3gg@1h6H85m#JgwWx7!J?_*q>&kC6rhK7;vS0YOC!UXd zbcs2&2bOx*{E%tZ-Muf>ap12mf{ubS{j7&Wd{`XdzDJ*lSlPt`uCL4A@`z%IVrKNY zXW?z{>NuVG9Q_YDPvwOUoq0yHds^|IcL@IK*44(zb&G3~-*RKM{R7sy+<|=$c6-mI(q-4?91 z{ZHudubjK>Ze0L>@te}qLC%%6?s=H5uWihGEj`EsGO@dQBGJHl#tUJS4F_3M4`;vO=c4Co@oe^;Ze$;@k-B?bv;}W> z{0>$ygT314Sr6a5F8}ZK|1kyZ6Op%;XxTi!Tla~WE`OKoM5^3#U+=dZ+b;Z(i8J)gk@wx8RO z)$~(W%Y*)6q}IWBJ$l6b@(29(vNps|*=_CNpK^^k zXiG*GTC)eA$UQMf9Dj27`PCXXeHHqk^;K?=YY4pK(U2b(%%ed+F* zf1!nQzVXQD+2nVt-?JV%3V%J=TWLM$>!?*I{lA4j%sW31t-aMu>Lc1_hkhY%^mocp z=*>C)v_FNC;kEx$W&!sqefm>`@je!~) zM>XB^WggKtxYhPMh5zb4>sY-Py7O7twhuq^a_(u|A>!R)HE7}E%@>|-`Wf>WTSTpcJ~R1IeS_%A zPXeFsa4`SivtF%R{H&(zg4|0iuVfzu@^ixsH#+E3QAgFt-w2qk%}iHu8Fg7=sjIHJ zcJ5C(F?>_k6#Aoq93B~gp2ktDLC^RsMz!5eyT*6?LN2OzfP-E~dxMDS;C(qEa|M32 z!`>&JaZaM!$oWR`9`ITxdQbGttMO4|QDju%3;W3w*d5`bS4}_p;!7+Y{i3Uex)*8xHm&z=N)lXQI!pzvJGh^9NgX%<{Rw{Mirxj@mahsrL0K zd8!^ce`j8I=-0nBkF)ra%S3Nbd4{80hIxWB`hihi4V}$BdBH9aXA*0+ey_~y&Yl$H ziM2?U!c&hY*|K-;TOmWq1pHFQ3;xJ-b`*!Z;EHRa_O`^~>2AGhrN#ft|y5NjoxqN+?#y^JXgPxH7BO3H&v}JU0{8ey(YkH?*X!882B^Y3r)&V zJ*#{Jdw2gsj*PrM{s5!g6dK?s^p}HD2WmWUdj=ZN(|&*9jrY?>c^?e(rS8#M*Gq&a zN69fVu;?c=Z}ND?L@)ZR^whYG7ruG#q6HYi$tQ|Izyapb{gZ26}I|F~ABY6u>@jHJJ;n5=kc;L*{kc5|@OvY8 zYtNBw9fcpw^um&dcty{G{tfa(&66Co`N8jc=jhUZ$BSASJ$XAHI@8LCf-ox1LZ+3(nX=kPtO5B-XG9Bk-Y_`Uj^^4WPl82bdi z{2F~He2Xf)wVyi+zj5KzZGz&HJ@Q*R!#`E{>wSh3+sFPzYHjGNHP%@#c!3VKCxUVH{L%;OZM<3d zRArw+bYQm^d#)Dl@_l&04=1!`GlQR^k+2da3z=?7l`eN?UNY^?Sgd^_QHHoJ)J*SF6Ns;Ft1`)acpk(B4;t*5VVJ zZM9wa|8IQs`4E5Nr{;EUTd>yq9sKMbzN7eZBly`EV!&*Oi*jt0Z;U_eTTo!;Gn)(k z5PON8N8i<>dA%G!Js2DP27dd4jgk8u7szqktSLM8%w^r5p*#pwP zUTjg%@@_V!^V!{wnyvQc@7j8%@x%|&P)i>Is4ZtFAJ zgWanu`D@Pyza9;>>*QUDeXIY3kJvgtUn~^Ne4)1BYR~WT*R}OO^4XoO9{|sbZ+;kZ zh0Wh{s$OA3%WIW=**nS~ZQ)U`eqhKf48h5I?(BNthm+%CTa9F1Td+0y9ZX=WrF((B z9PyMoOxJc)wxY3GnXd9j6^|k#!BqIY!0MP~!vDQ~M+&IZ>XqMp^SiZ9EC0`*+ESB#TiNv{prJ7nCbpSQ~7<`hW{fEr+%NkqnD|X?#B;BCYO1Y2arRO6M?IJP{dc*PWBHH zgOTH88>tVv;f}vXoKEgZj6*Ko9DuFa_=Vo$`Qkis$?7@u&iLOO_Gz|H8JyWQ;#B&P z_0*t&@$bt1fxQ>v+8nbMe->|i^!ZnZ<*8qI*P5x?7e4E|g{z#Id6iqUXP$Vx=c%_) zFM!tKGW#8TM6QLuA!vav_EfWnqS$${yUZi}%6#&x*$QeRn#cnDASZ6$8n!ywKpx2H z+K+$7UH6DQ1|OAu?>m1|4L}*+Je74~-&S=BdO-Lza{Fri)QaN&n9r=sUwrd}puL>E zn4O#u`^p-yHr!*KRR4F9xP^M17=OQmh8e%C1#@C8;VJbFY8Z^mAC#Y9+p8JC`zUusVC!O>MON|oabMcn0vGMUbFG>FP$cjg7?&2p)*>D zGu@eG4W4*C#|zLY_&wia?tB&-ksoer@4sf_!~f0P>t1r|a6TZ{1M;24>FJvXpL!v9 zu<%Pc;u~v(JRnQ088&})E@J##bJd9d@V9)98VI>CHCmhI+`Z??AFI1EmbK&B>i8F2 zeofTO$+=mRy}6LDF>mA@Stvhf zy>({%f>Xee=QZ%nN9#;0rYn{nAs@>oV!oSD|FjmL*8U5RXe;L2_2o5zZ`ljir z>hsm%uouKC)HZ;vdVc8m{hQLicHHva_=n{2?T@r@pJ8(=c#SVV&-@F9h#QF$v0vzKz1Uh;H>m`GU=SK=-2|8xQZPCu47yn&IH(8v53bS-u;q_@BiOMu*~$HR4G+fPQp@ zYwettF=~&VSoc+>0jaBAkEy!_Q-V=s%&m_&HReot*Wekkistjr!#ll_N`hWeybR@eNVyq+`xB3r>c`v--74( zBkHmFO7ch6KA(tP&hEgE>QLoD)KH0at1*TT-#UD!{2aBCe6VL;dprJ5m0An&eRbvP zvFKPjobP?^B?AH;HkbMsaPkH0t-=mgvuJ$wkvbK2MxMX;|2E{5dN25p2|l|{JVRcL zt>*s`skPx#sS7E!XL@R?_j?9=%>Q^}@9;g?Tk1@{%L~c5@P%@&-T3wHM+fWYsaM|2 zHH;60%|?E(UD1gz3ZJ&_2ZLvrTfD|kC+GP);xBM3|BGOpamUN>FVc#?d#i6XcX&X( zr}3(9dQ82tT$Uby>V4%ie#F0Wr0xX+`q?9Zea0WdU;LM{Zpyum?pLR!)|*a~hZo1t zd&18savZMKUiDs|)k3n()sLyO5=XG_j{i$twa?vK*5I&k{5NX0)DMdxS~FES>e_N| J#;;4S{|9GFb^ZVV literal 0 HcmV?d00001 diff --git a/app/static/leaderboard/board.js b/app/static/leaderboard/board.js new file mode 100644 index 00000000..5da6c200 --- /dev/null +++ b/app/static/leaderboard/board.js @@ -0,0 +1,148 @@ +/* Shared row selection; filters affect the table alone. Text is always inserted as text. */ +(() => { + let data = JSON.parse(document.getElementById('lb-data').textContent); + const marks = JSON.parse(document.getElementById('lb-marks').textContent), table = document.getElementById('leaderboard-table'); + let selected = data.selected, versus = 'average', family = 'capabilities', metric = 'time', generation = 0, focusBefore = null, projection = null, comparisonGeneration = 0; + const percent = v => v == null ? '—' : `${Number((v * 100).toFixed(1))}%`; + const element = (tag, text, attrs = {}) => { const e = document.createElement(tag); if (text != null) e.textContent = text; Object.entries(attrs).forEach(([k,v]) => e.setAttribute(k,v)); return e; }; + const svg = (tag, attrs = {}, text) => { const e = document.createElementNS('http://www.w3.org/2000/svg',tag); Object.entries(attrs).forEach(([k,v]) => e.setAttribute(k,v)); if (text != null) e.textContent = text; return e; }; + const row = key => data.rows.find(r => r.key === key); + const compared = axis => versus === 'average' ? data.averages[axis]?.score : versus.startsWith('version:') ? projection?.rows.find(r=>r.key===selected)?.axes[axis]?.score : row(versus)?.axes[axis]?.score; + const delta = (a,b) => a == null || b == null ? '—' : `${a >= b ? '+' : ''}${((a-b)*100).toFixed(1)} pp`; + const pop = document.getElementById('lb-evidence'); + function dismiss() { pop.hidden = true; } + function evidence(target) { + const current = row(target.closest('tr')?.dataset.key || selected); if (!current) return; + const axisName = target.dataset.axis; if (!axisName) return; + pop.replaceChildren(element('strong', axisName)); + if (axisName === 'Overall') { + current.reasons.forEach(reason => pop.append(element('p', `Not ranked: ${reason}`))); + pop.append(element('p',[current.identity.model,current.identity.effort].filter(Boolean).join(' · '))); + data.axes.map(name=>[name,current.axes[name]]).filter(([,a]) => a.weight > 0).forEach(([name,a]) => { + const names = a.entries.filter(e => e.unverified && e.share > 0).map(e => e.name); + pop.append(element('p', `${name} · ${percent(a.score)} · weight ${a.weight} · share ${percent(a.share)}${names.length ? ' · '+names.join(', ')+' · not verified' : ''}`)); + }); + } else { + const axis = current.axes[axisName]; + if (!axis.entries.length) pop.append(element('p','No benchmark')); + axis.entries.forEach(e => { + const line = element('p', `${e.name}${e.version ? ' · '+e.version : ''} · ${e.score == null ? e.reason || 'not run' : percent(e.score)}${e.unverified ? ' · not verified' : ''} · ${innerWidth <= 700 ? 'x' : 'weight'} ${e.weight} · share ${percent(e.share)}`); + if (!e.custom && e.tasks != null) line.append(element('span', ` · ${e.covered}/${e.tasks} tasks`, {class:e.covered === e.tasks ? 'lb-complete-count' : ''})); + (e.links || []).forEach(link => { line.append(document.createTextNode(' · '),element('a',link.id,{href:link.url})); }); + if (e.note) line.append(document.createTextNode(` · ${e.note}`)); + pop.append(line); + }); + } + focusBefore = target; pop.hidden = false; + const box = target.getBoundingClientRect(); + pop.style.left = `${Math.max(12,Math.min(box.left,innerWidth-pop.offsetWidth-12))}px`; + pop.style.top = `${Math.max(12,Math.min(box.bottom+6,innerHeight-pop.offsetHeight-12))}px`; + } + document.addEventListener('keydown', e => { if (e.key === 'Escape') { dismiss(); focusBefore?.focus(); } }); + document.addEventListener('pointerdown', e => { if (!pop.contains(e.target) && !e.target.closest('[data-axis]')) dismiss(); }); + document.addEventListener('focusin', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); + document.addEventListener('pointerover', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); + document.addEventListener('click', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); + function medal(rank) { + if (!rank) return document.createTextNode(''); + if (rank > 4) return document.createTextNode(String(rank)); + const names=['gold','silver','bronze','chocolate']; + const span=element('span',null,{class:`lb-medal lb-medal-${rank}`,'aria-label':`Rank ${rank}, ${names[rank-1]}`}); + const icon=svg('svg',{'aria-hidden':'true',viewBox:'0 0 24 24'});icon.append(svg('use',{href:rank===4?'#i-medal-bitten':'#i-medal'}));span.append(icon,element('span',rank));return span; + } + function updateTable() { + data.rows.forEach(r => { + const tr = [...table.tBodies[0].rows].find(t => t.dataset.key === r.key); if (!tr) return; + tr.dataset.sortTie = r.name + ' ' + r.version_label + ' ' + r.key; + tr.dataset.sortGroup = r.rank ? 0 : r.overall != null ? 1 : 2; + tr.dataset.fStatus = `${r.rank ? 'ranked' : 'not-ranked'}${!r.has_runs?'\nno-run':''}`; + tr.querySelector('[data-col="rank"]').replaceChildren(medal(r.rank)); + tr.querySelector('[data-col="rank"]').dataset.sort=r.rank || ''; + const same = data.rows.filter(v=>v.agent===r.agent && v.version===r.version).length>1; + tr.querySelector('[data-name]').textContent = r.name + (same ? ' · '+[r.identity.model,r.identity.effort].filter(Boolean).join(' ') : ''); + tr.querySelectorAll('[data-axis]').forEach(cell => { + const a=cell.dataset.axis==='Overall'?{score:r.overall,unverified:r.unverified}:r.axes[cell.dataset.axis]; + cell.textContent=percent(a.score);cell.dataset.sort=a.score??''; + cell.classList.toggle('lb-unverified',Boolean(a.unverified)); + cell.style.setProperty('--lb-shade',`${a.score==null?0:Math.max(0,Math.min(1,(a.score-.2)/.6))*20}%`); + if(a.score!=null) { const bar=element('span',null,{class:'lb-bar'});bar.style.setProperty('--lb-value',`${a.score*100}%`);cell.append(bar); } + }); + for(const [field,m] of Object.entries(r.metrics)) { const cell=tr.querySelector(`[data-col="${field}"]`);cell.textContent=m.value==null?'—':field==='cost'?`$${m.value.toFixed(2)}`:Number(m.value.toFixed(1))+(field==='time'?'s':'');cell.dataset.sort=m.value??'';cell.title=`${m.count} observed`; } + table.tBodies[0].append(tr); + }); + let explicit=false;try {explicit=localStorage.getItem(table.id+'.cols')!==null;} catch {} + if(!explicit) data.axes.forEach(name=>{ + const cb=document.querySelector(`#${table.id}-tools input[data-col="${name}"]`); + if(cb) {cb.checked=data.averages[name].score!=null;table.querySelectorAll(`[data-col="${name}"]`).forEach(cell=>cell.style.display=cb.checked?'':'none');} + }); + table.dispatchEvent(new Event('table:update')); + document.getElementById('lb-trust-key').hidden=!data.rows.some(r=>r.custom_names.length); + applyFamily(); + } + function applyFamily() { + document.querySelectorAll('[data-family]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.family===family))); + table.querySelectorAll('[data-col]').forEach(cell=> { if(data.axes.includes(cell.dataset.col)) cell.hidden=!data[family].includes(cell.dataset.col); }); + } + function choose(key) { if(!row(key)) return; selected=key;document.querySelectorAll('[data-agent-select]').forEach(s=>s.value=selected);draw(); } + document.addEventListener('click',e=>{const target=e.target.closest('[data-select]');if(target) choose(target.dataset.select);}); + function selectable(node,key,x,y) { node.setAttribute('tabindex','0');node.setAttribute('role','button');node.dataset.select=key;node.dataset.cx=x;node.dataset.cy=y;node.classList.add('lb-point');node.setAttribute('aria-label',`${row(key)?.name} ${row(key)?.version_label}`);node.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();choose(key);}});return node; } + function nearest(plot) { plot.addEventListener('click',e=>{if(e.target.closest('text[data-select]'))return;const pt=plot.createSVGPoint();pt.x=e.clientX;pt.y=e.clientY;const p=pt.matrixTransform(plot.getScreenCTM().inverse());const points=[...plot.querySelectorAll('[data-cx]')].map(n=>({n,d:Math.hypot(p.x-Number(n.dataset.cx),p.y-Number(n.dataset.cy))})).sort((a,b)=>a.d-b.d||a.n.dataset.select.localeCompare(b.n.dataset.select));if(points[0]&&points[0].d<30){e.stopPropagation();choose(points[0].n.dataset.select);}},true); } + function drawScatter() { + const plot=document.getElementById('lb-scatter'), panel=data.scatter[metric];plot.replaceChildren();plot.setAttribute('viewBox',`0 0 360 ${panel.height}`); + const defs=svg('defs'), gradient=svg('linearGradient',{id:'lb-efficiency-tint',x1:0,y1:0,x2:1,y2:1}); + gradient.append(svg('stop',{offset:'0%','stop-color':'var(--good)','stop-opacity':'.12'}),svg('stop',{offset:'50%','stop-color':'var(--bg)','stop-opacity':'0'}),svg('stop',{offset:'100%','stop-color':'var(--bad)','stop-opacity':'.12'}));defs.append(gradient);plot.append(defs,svg('rect',{x:48,y:22,width:304,height:210,fill:'url(#lb-efficiency-tint)'})); + plot.append(svg('text',{x:54,y:38,class:'lb-better'},'BETTER')); + for(const m of panel.marks) { + if(m.shape==='tile') { + const group=selectable(svg('g'),m.key,m.x,m.y), mark=marks[m.key];group.append(svg('title',{},m.title)); + group.append(svg('rect',{x:m.x-11,y:m.y-11,width:22,height:22,rx:4,fill:'var(--bg)',class:m.key===selected?'lb-selected':''})); + if(mark?.includes('#')) {const icon=svg('svg',{x:m.x-9,y:m.y-9,width:18,height:18,viewBox:'0 0 24 24'});icon.append(svg('use',{href:mark}));group.append(icon);} + else if(mark) group.append(svg('image',{x:m.x-9,y:m.y-9,width:18,height:18,href:mark})); + else group.append(svg('text',{x:m.x,y:m.y+4,'text-anchor':'middle'},row(m.key)?.name.slice(0,1))); + plot.append(group); + } else plot.append(svg('line',{x1:m.x,y1:m.y,x2:m.x2,y2:m.y2,class:m.cls})); + } + for(const t of panel.texts) {const text=svg('text',{x:t.x,y:t.y,'text-anchor':t.anchor,class:t.cls});t.lines.forEach((line,i)=>text.append(svg('tspan',{x:t.x,dy:i?15:0,class:i?'small':''},line)));if(t.key) {text.dataset.select=t.key;text.setAttribute('tabindex','0');text.addEventListener('keydown',e=>{if(e.key==='Enter')choose(t.key);});}plot.append(text);} + } + nearest(document.getElementById('lb-scatter')); + function chart(kind,group) { + const container=document.querySelector(`[data-chart="${kind}-${group}"]`), names=data[group], current=row(selected);if(!current)return; + const plot=svg('svg',{viewBox:`0 0 360 ${kind==='strips'?names.length*42+20:320}`,role:'group','aria-label':`${group} ${kind}`}); + if(kind==='strips') names.forEach((name,i)=>{ + const y=30+i*42, label=svg('text',{x:0,y:y-10,tabindex:0,'data-axis':name},name);plot.append(label,svg('line',{x1:0,y1:y,x2:350,y2:y,class:'grid'})); + data.rows.forEach(r=>{const score=r.axes[name].score;if(score==null)return;const node=selectable(svg('circle',{cx:score*340+5,cy:y,r:r.key===selected?5:3,class:r.key===selected?'lb-selected':''}),r.key,score*340+5,y);node.append(svg('title',{},`${r.name} ${r.version_label} ${r.identity.model||''}: ${percent(score)}${r.axes[name].unverified?' · not verified':''}`));plot.append(node);}); + const score=compared(name);if(score!=null){const x=score*340+5;plot.append(versus==='average'?svg('line',{x1:x,y1:y-8,x2:x,y2:y+8,class:'lb-comparison','stroke-dasharray':'2 2'}):svg('path',{d:`M${x} ${y-6}l6 6-6 6-6-6Z`,class:'lb-comparison'}));} + plot.append(svg('text',{x:350,y:y-10,'text-anchor':'end'},`${percent(current.axes[name].score)} / ${percent(score)}${versus==='average'?' (n='+data.averages[name].count+')':''}`)); + }); + else { + const at=(i,value)=>[180+Math.sin(i/names.length*2*Math.PI)*90*value,155-Math.cos(i/names.length*2*Math.PI)*90*value]; + names.forEach((name,i)=>{const [x,y]=at(i,1),[lx,ly]=at(i,1.3);plot.append(svg('line',{x1:180,y1:155,x2:x,y2:y,class:'grid'}));const label=svg('text',{x:Math.max(name.length*4,Math.min(360-name.length*4,lx)),y:ly,tabindex:0,'text-anchor':'middle','data-axis':name},name);plot.append(label);}); + for(const compare of [false,true]) names.forEach((name,i)=>{const score=compare?compared(name):current.axes[name].score;if(score==null)return;const [x,y]=at(i,score),next=(i+1)%names.length,v=compare?compared(names[next]):current.axes[names[next]].score;if(v!=null){const [nx,ny]=at(next,v);plot.append(svg('line',{x1:x,y1:y,x2:nx,y2:ny,class:'lb-radar-line'+(compare?' lb-comparison':'')}));}const point=svg('circle',{cx:x,cy:y,r:4,tabindex:0,'data-axis':name,class:'lb-point'+(compare?' lb-comparison':'')});point.append(svg('title',{},`${name}: ${percent(score)}`));plot.append(point);}); + } + plot.querySelectorAll('text[data-axis]').forEach(label=>{ + const grow=on=>plot.querySelectorAll(`circle[data-axis="${label.dataset.axis}"]`).forEach(point=>point.classList.toggle('lb-hover',on)); + label.addEventListener('pointerenter',()=>grow(true));label.addEventListener('pointerleave',()=>grow(false)); + label.addEventListener('focus',()=>grow(true));label.addEventListener('blur',()=>grow(false)); + }); + container.replaceChildren(plot);nearest(plot); + } + function draw() { + const current=row(selected);if(!current)return; + const card=document.getElementById('lb-card');card.replaceChildren(element('h2',current.name),element('p',`${percent(current.overall)}${!current.rank?' · not ranked':''}`),element('p',[current.company,current.version_label,current.identity.model,current.identity.effort].filter(Boolean).join(' · '))); + card.append(element('p',`Covered: ${current.reasons.join('; ')||'All required entries'}`)); + const values=data.rows.map(r=>r.overall).filter(v=>v!=null), baseline=versus==='average'?(values.length?values.reduce((a,b)=>a+b,0)/values.length:null):versus.startsWith('version:')?projection?.rows.find(r=>r.key===selected)?.overall:row(versus)?.overall; + card.append(element('p',`Overall against ${versus==='average'?'Average':versus.startsWith('version:')?'benchmark version':row(versus)?.name}: ${delta(current.overall,baseline)}`)); + const differences=data.capabilities.map(name=>({name,a:current.axes[name].score,b:compared(name)})).filter(v=>v.a!=null&&v.b!=null).sort((a,b)=>(b.a-b.b)-(a.a-a.b)); + if(differences.length) card.append(element('p',`Best: ${differences[0].name} ${delta(differences[0].a,differences[0].b)}`),element('p',`Weakest: ${differences.at(-1).name} ${delta(differences.at(-1).a,differences.at(-1).b)}`)); + if(current.custom_names.length)card.append(element('p',`Not verified: ${current.custom_names.join(', ')}`)); + drawScatter();for(const kind of ['strips','radars'])for(const group of ['domains','capabilities'])chart(kind,group); + } + document.querySelectorAll('[data-family]').forEach(b=>b.onclick=()=>{family=b.dataset.family;applyFamily();}); + document.querySelectorAll('[data-agent-select]').forEach(s=>s.onchange=()=>choose(s.value)); + async function compareChoice() { const turn=++comparisonGeneration;projection=null;if(versus.startsWith('version:')) {const [benchmark,version]=JSON.parse(versus.slice(8));const response=await nulliusFetch('/api/leaderboard/comparison?'+new URLSearchParams({benchmark,version,all_scores:data.all_scores?'1':'0'}));if(response.ok){const result=await response.json();if(turn!==comparisonGeneration)return;projection=result;}}draw();} + document.querySelectorAll('[data-vs-select]').forEach(s=>{data.versions.forEach(v=>s.append(element('option',`Same agent: ${v.label}`,{value:'version:'+JSON.stringify([v.benchmark,v.version])})));s.onchange=()=>{versus=s.value;document.querySelectorAll('[data-vs-select]').forEach(v=>v.value=versus);compareChoice().catch(()=>{});};}); + document.getElementById('lb-metric').onchange=e=>{metric=e.target.value;drawScatter();}; + async function deferred(turn) { const response=await nulliusFetch(`/api/leaderboard/metrics?all_scores=${data.all_scores?1:0}&context=${encodeURIComponent(data.context)}`);if(!response.ok)return;const result=await response.json();if(turn!==generation||result.context!==data.context)return;result.rows.forEach(r=>{const existing=row(r.key);if(existing)existing.metrics=r.metrics;});updateTable(); } + document.getElementById('lb-mode').onchange=async e=>{const turn=++generation;const response=await nulliusFetch(`/api/leaderboard?all_scores=${e.target.value}`);if(!response.ok)return;const next=await response.json();if(turn!==generation)return;data=next;updateTable();compareChoice().catch(()=>{});draw();deferred(turn).catch(()=>{});}; + updateTable();choose(selected);deferred(generation).catch(()=>{}); +})(); diff --git a/app/static/leaderboard/leaderboard.css b/app/static/leaderboard/leaderboard.css new file mode 100644 index 00000000..383f69b4 --- /dev/null +++ b/app/static/leaderboard/leaderboard.css @@ -0,0 +1,63 @@ +.lb-head-link { min-width: 10rem; justify-content: center; } +.lb-controls, .lb-mode { display: flex; gap: 1rem; align-items: center; justify-content: space-between; flex-wrap: wrap; } +.lb-mode { margin-left: auto; } +.lb-mark { display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; flex-shrink: 0; } +.lb-mark img, .lb-mark svg { width: 100%; height: 100%; object-fit: contain; } +.lb-agent { display: flex; align-items: center; gap: .5rem; text-align: left; } +.lb-subtitle { display: block; } +.lb-table { table-layout: fixed; width: 100%; } +.lb-table [data-col="rank"] { width: 40px; } +.lb-table [data-col="agent"] { width: 170px; } +.lb-table [data-col="overall"] { width: 75px; } +.lb-table [data-col="steps"], .lb-table [data-col="time"], .lb-table [data-col="calls"], .lb-table [data-col="cost"] { width: 65px; } +.lb-table th, .lb-table td { overflow-wrap: anywhere; white-space: normal; transition: opacity .2s, background-color .32s; } +.lb-table [data-axis] { cursor: help; background: color-mix(in srgb, var(--series-1) var(--lb-shade, 0%), var(--bg)); color: var(--text); } +.lb-unverified { outline: 1px dashed var(--text-dim); outline-offset: -2px; } +.lb-bar { display: block; height: 3px; width: var(--lb-value); background: var(--accent); transition: width .32s cubic-bezier(.2,.7,.2,1); } +.lb-efficiency { display: grid; grid-template-columns: minmax(0, 2fr) minmax(220px, 1fr); gap: 2rem; margin: 2rem 0; } +.lb-chart-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 2rem; margin: 1rem 0 2rem; } +.lb-chart-pair > :last-child { border-left: 1px solid var(--border); padding-left: 2rem; } +.lb-chart-pair svg, #lb-scatter { width: 100%; display: block; overflow: visible; } +.lb-chart-pair svg { min-height: 260px; } +.lb-chart-pair text, #lb-scatter text { fill: var(--text); } +.lb-chart-pair .grid, #lb-scatter .grid { stroke: var(--border-soft); fill: none; } +.lb-point { fill: var(--accent); stroke: var(--bg); cursor: pointer; transform-box: fill-box; transform-origin: center; transition: transform 150ms; } +.lb-point:hover, .lb-point:focus, .lb-point.lb-hover { transform: scale(1.35); } +.lb-selected { stroke: var(--accent-strong); stroke-width: 3; } +.lb-comparison { stroke: var(--series-2); fill: var(--series-2); } +.lb-radar-line { fill: none; stroke: var(--accent); stroke-width: 2; } +.lb-radar-line.lb-comparison { stroke: var(--series-2); stroke-dasharray: 5 4; } +.lb-series-solid, .lb-series-dashed { width: 24px; border-top: 2px solid var(--accent); } +.lb-series-dashed { border-top-style: dashed; border-color: var(--series-2); } +.lb-evidence { position: fixed; z-index: 100; max-width: min(600px, calc(100vw - 24px)); max-height: min(440px, calc(100vh - 24px)); overflow: auto; padding: 1rem; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); color: var(--text); box-shadow: 0 4px 16px color-mix(in srgb, var(--text) 15%, transparent); } +.lb-evidence p { margin: .5rem 0; } +.lb-medal { position: relative; display: inline-block; width: 28px; height: 32px; color: var(--lb-medal-gold); } +.lb-medal svg { width: 100%; height: 100%; stroke: currentColor; fill: color-mix(in srgb, currentColor 20%, var(--bg)); } +.lb-medal span { position: absolute; inset: 12px 0 0; text-align: center; color: var(--text); } +.lb-medal-2 { color: var(--lb-medal-silver); }.lb-medal-3 { color: var(--lb-medal-bronze); }.lb-medal-4 { color: var(--lb-medal-chocolate); } +.lb-medal:hover { animation: lb-swing .55s ease-in-out; transform-origin: top; } +@keyframes lb-swing { 25% { transform: rotate(-14deg); } 75% { transform: rotate(12deg); } } +:root { --lb-medal-gold: #e8c85a; --lb-medal-silver: #c0c5cf; --lb-medal-bronze: #dca475; --lb-medal-chocolate: #b88568; } +:root[data-theme="light"] { --lb-medal-gold: #906500; --lb-medal-silver: #687282; --lb-medal-bronze: #975525; --lb-medal-chocolate: #633f2d; } +#scoring-form fieldset { border: 0; padding: 0; min-width: 0; } +#scoring-form section { margin: 1.5rem 0; } +.scoring-entry { display: grid; grid-template-columns: 2fr 2fr 1fr 1fr 1fr auto; gap: .5rem; margin: .7rem 0; align-items: end; } +.scoring-entry label { display: grid; gap: .3rem; min-width: 0; } +.scoring-entry select, .scoring-entry input { width: 100%; min-width: 0; } +.scoring-custom-scores { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: .6rem; } +[aria-invalid="true"] { outline: 2px solid var(--bad); } +@media (max-width: 700px) { + .lb-chart-pair, .lb-efficiency { grid-template-columns: minmax(0,1fr); } + .lb-chart-pair > :last-child { border-left: 0; border-top: 1px solid var(--border); padding: 1.5rem 0 0; } + .lb-company { display: none; } + .lb-table { min-width: 900px; } + .lb-table [data-col="agent"] { position: static; } + .scoring-entry { grid-template-columns: minmax(0,1fr); } + .scoring-no-choice { display: none; } + .lb-complete-count { display: none; } +} +@media (prefers-reduced-motion: reduce) { + .lb-medal, .lb-point, .lb-bar, .lb-table th, .lb-table td { animation: none !important; transition: none !important; } +} + +#lb-scatter .lb-better { fill: var(--good); } diff --git a/app/static/leaderboard/scoring.js b/app/static/leaderboard/scoring.js new file mode 100644 index 00000000..aa632207 --- /dev/null +++ b/app/static/leaderboard/scoring.js @@ -0,0 +1,81 @@ +/* Complete-document autosave: serialize writes and retain the latest local draft. */ +(() => { + const data=JSON.parse(document.getElementById('scoring-data').textContent), form=document.getElementById('scoring-form'); + let draft=data.settings, revision=data.revision, timer, writing=false, dirty=false, resetting=false; + const writable=form.dataset.writable==='true', status=form.querySelector('[data-changes]'), retry=form.querySelector('[data-settings-retry]'); + const el=(tag,text,attrs={})=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;Object.entries(attrs).forEach(([k,v])=>n.setAttribute(k,v));return n;}; + const input=(value,change,attrs={})=>{const n=el('input',null,{type:'number',min:0,step:'any',...attrs});n.value=value??'';n.oninput=()=>{change(n.value===''?null:Number(n.value));edited();};return n;}; + const select=(choices,value,change)=>{const n=el('select');choices.forEach(([v,label])=>{const o=el('option',label,{value:v});o.selected=v===value;n.append(o);});if(!choices.some(([v])=>v===value))n.append(el('option',value||'Unavailable',{value,selected:''}));n.onchange=()=>{change(n.value);render();edited();};return n;}; + const labelled=(text,control)=>{const l=el('label',text);l.append(control);return l;}; + const button=(text,action)=>{const b=el('button',text,{type:'button',class:'btn ghost sm'});b.onclick=action;return b;}; + const number=v=>Number.isFinite(v)&&v>=0; + function valid() { + let ok=true;const names=new Set(); + form.querySelectorAll('input').forEach(n=>n.setCustomValidity('')); + draft.custom.forEach(c=>{const normalized=c.name.trim().toLocaleLowerCase();const n=[...form.querySelectorAll('[data-custom-name]')].find(n=>n.dataset.customName===c.id);if(!normalized||names.has(normalized)){n?.setCustomValidity('Enter a unique name.');ok=false;}names.add(normalized);if(Object.values(c.scores).some(v=>v!=null&&(!number(v)||v>100)))ok=false;}); + if(!Object.values(draft.axes).some(a=>a.weight>0)) {form.querySelector('[data-overall]')?.setCustomValidity('At least one Weight in Overall must be positive.');ok=false;} + Object.values(draft.axes).forEach(a=>{if(!number(a.weight)||a.entries.some(e=>!number(e.weight)))ok=false;}); + form.querySelectorAll('input').forEach(n=>{n.setAttribute('aria-invalid',String(!n.checkValidity()));}); + return ok&&form.checkValidity(); + } + function shares() { + const normalized = values => { + const scale=Math.max(0,...values.filter(number)); + const total=scale?values.reduce((n,w)=>n+(number(w)?w/scale:0),0):0; + return values.map(w=>total&&number(w)?Number((w/scale/total*100).toFixed(1)):0); + }; + const overall=normalized(Object.values(draft.axes).map(a=>a.weight)); + Object.entries(draft.axes).forEach(([name,a],i)=>{ + form.querySelector(`[data-overall-share="${name}"]`).textContent=`share ${overall[i]}%`; + const shares=normalized(a.entries.map(e=>e.weight)); + form.querySelectorAll(`[data-scoring-axis="${name}"] [data-share]`).forEach((n,j)=>n.textContent=`share ${shares[j]}%`); + }); + } + function report(message,error=false) {status.textContent=message;status.closest('.st-savebar').hidden=!error;} + function edited() {resetting=false;dirty=true;shares();clearTimeout(timer);if(!valid())return;timer=setTimeout(save,300);} + async function save(reset=false) { + if(!writable||writing||(!reset&&(!dirty||!valid())))return; + writing=true;dirty=false;const body=reset?{reset:true}:structuredClone(draft); + if(reset){resetting=true;form.querySelector('fieldset').disabled=true;} + try { + const response=await nulliusFetch('/api/scoring',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':form.elements.csrf.value,'If-Match':revision},body:JSON.stringify(body)}); + const result=await response.json();if(!response.ok)throw new Error(result.error||'Scoring settings could not be saved. Retry.'); + revision=result.revision;if(reset){draft=result.settings;resetting=false;render();document.getElementById('reset-confirm').hidden=true;} + report('Scoring saved');window.nulliusNotify('Scoring saved',{key:'scoring'}); + } catch(error) {dirty=true;report(error.message,true);return;} + finally {writing=false;if(reset){form.querySelector('fieldset').disabled=!writable;}} + if(dirty&&valid())save(); + } + function render() { + const custom=document.getElementById('scoring-custom');custom.replaceChildren(); + draft.custom.forEach(c=>{ + const section=el('section'),name=el('input',null,{type:'text',required:'','data-custom-name':c.id});name.value=c.name;name.oninput=()=>{c.name=name.value;edited();}; + section.append(labelled('Name',name),button('Remove',()=>{draft.custom=draft.custom.filter(x=>x.id!==c.id);Object.values(draft.axes).forEach(a=>a.entries=a.entries.filter(e=>e.custom!==c.id));render();edited();})); + const scores=el('div',null,{class:'scoring-custom-scores'});data.rows.forEach(r=>scores.append(labelled([r.name,r.version_label,r.identity.model,r.identity.effort].filter(Boolean).join(' · '),input(c.scores[r.key],v=>c.scores[r.key]=v,{max:100,'aria-label':`${c.name}: ${r.name} ${r.version_label}`}))));section.append(scores);custom.append(section); + }); + document.querySelectorAll('[data-scoring-axis]').forEach(section=>{ + const axis=draft.axes[section.dataset.scoringAxis], container=section.querySelector('[data-entries]');container.replaceChildren(); + axis.entries.forEach((entry,index)=>{ + const line=el('div',null,{class:'scoring-entry'}), choices=[...new Map(data.options.map(o=>[o.key,o.label])).entries(),...draft.custom.map(c=>['custom:'+c.id,c.name])]; + const source=select(choices,entry.custom?'custom:'+entry.custom:entry.benchmark,value=>{if(value.startsWith('custom:'))axis.entries[index]={custom:value.slice(7),weight:entry.weight};else {const b=data.options.find(b=>b.key===value);axis.entries[index]={benchmark:value,dataset:'',version:b.version,metric:'Score',weight:entry.weight};}}); + line.append(labelled('Benchmark',source)); + if(entry.custom) for(const name of ['Dataset','Version','Metric'])line.append(el('span',`${name}: —`,{class:'scoring-no-choice'})); + else { + const versions=data.options.filter(o=>o.key===entry.benchmark), bench=versions.find(o=>o.version===entry.version); + line.append(labelled('Dataset',select([['','Whole benchmark'],...(bench?.datasets||[]).map(d=>[d.id,d.label])],entry.dataset,v=>entry.dataset=v))); + line.append(labelled('Version',select(versions.map(v=>[v.version,v.version_label||'—']),entry.version,v=>entry.version=v))); + line.append(labelled('Metric',select((bench?.metrics||['Score']).map(m=>[m,m]),entry.metric,v=>entry.metric=v))); + } + const weight=labelled('Weight',input(entry.weight,v=>entry.weight=v,{required:''}));weight.append(el('output','',{'data-share':''}));line.append(weight,button('Remove',()=>{axis.entries.splice(index,1);render();edited();}));container.append(line); + }); + const weight=section.querySelector('[data-overall]');weight.value=axis.weight;weight.oninput=()=>{axis.weight=weight.value===''?null:Number(weight.value);edited();}; + section.querySelector('[data-add-entry]').onclick=()=>{const b=data.options[0];if(!b)return;axis.entries.push({benchmark:b.key,dataset:'',version:b.version,metric:'Score',weight:1});render();edited();}; + });shares(); + } + document.getElementById('custom-add').onclick=()=>{draft.custom.push({id:crypto.randomUUID(),name:'',scores:{}});render();edited();}; + document.getElementById('reset-ask').onclick=()=>document.getElementById('reset-confirm').hidden=false; + document.getElementById('reset-no').onclick=()=>{resetting=false;document.getElementById('reset-confirm').hidden=true;}; + document.getElementById('reset-yes').onclick=()=>save(true); + retry.onclick=()=>save(resetting); + form.onsubmit=e=>e.preventDefault();render(); +})(); diff --git a/app/static/tables.js b/app/static/tables.js index c6a8411b..b7a75540 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -28,8 +28,10 @@ window.NulliusTable = { if (col === null) return; const type = heads[col].dataset.type || 'text'; [...body.rows].sort((a, b) => { + const group = Number(a.dataset.sortGroup || 0) - Number(b.dataset.sortGroup || 0); + if (group) return group; const x = key(a, type), y = key(b, type); - return (x < y ? -1 : x > y ? 1 : 0) * dir; + return (x < y ? -1 : x > y ? 1 : 0) * dir || (a.dataset.sortTie || "").localeCompare(b.dataset.sortTie || ""); }).forEach(r => body.appendChild(r)); after(); }; @@ -239,6 +241,7 @@ window.NulliusTable = { const ticks = table.querySelector('[data-check-all]') ? this.checks(table) : () => {}; let first = () => {}; const t = this.toolbar(table, tools, () => first()); + table.addEventListener("table:update", () => { t.resort(); first(); }); const pick = Boolean(table.querySelector('[data-pick]')); if (pick) this.picks(table, 'tr'); first = this.pager(table, table.id + '.per', pick ? r => t.passes(r) || this.chosen(r) : t.passes, ticks); diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg index 29618160..b8050de1 100644 --- a/app/templates/_icons.svg +++ b/app/templates/_icons.svg @@ -9,7 +9,10 @@ Runs Compare + Leaderboard + +## Leaderboard + +Leaderboard scores describe one workspace's completed runs of catalogue agents. +Controls, example agents, preparing/running jobs and standalone capability +results do not contribute. Agent versions and execution setups are separate +rows; sampling limits affect coverage rather than identity. + +For each dataset and benchmark version, select the compatible run with the most +distinct non-infrastructure tasks, then the latest finish, then its stable run +ID. A better score never wins selection. Repeated attempts stay with their task; +repeated runs are not pooled. Explicit merged runs replace their source shards. +A whole-benchmark entry unions selected datasets by canonical task identity; +an overlap uses the same run precedence and retains that task's attempts. +Unknown identities make aggregation or full coverage unavailable rather than +guessing aliases. A dataset entry reads only that dataset. + +Score is adjusted solve rate for pass/fail tasks. Graded scores preserve recorded +part weighting within a task, including agent crashes as zero with their part +count (one when absent). Distinct task scores are then averaged. Infrastructure +outcomes are excluded; missing measurements stay absent. Scores outside the +supported 0–1 scale are unavailable. Raw job metrics are unchanged. pass^3 uses +recorded attempts in one selected run and the existing eligible-unit semantics; +independent one-attempt runs cannot supply it. + +Each axis normalizes positive entry weights over available scores. Overall +normalizes positive axis weights over measured axes. Missing values are never +zero. Evidence gives effective shares, configured weights, benchmark versions, +task coverage and links to each selected run. An all-zero entry column is +unavailable. All-zero Overall weights are invalid. + +Rank requires Overall and complete known coverage of the required verified +entries across counted axes, including positive-weight domains. Unknown full +coverage prevents ranking. Removed entries and zero weights do not gate rank. +Manual sources cannot replace required verified evidence, and their absence +does not disqualify another row. Exact Overall ties share competition rank; +scored unranked rows follow ranked rows and retain their score bars. + +Verified only excludes custom scores everywhere. All scores includes them with +the configured weights; affected values identify unverified influence and name +the sources. Custom scores supply no tasks, runs or efficiency measurements. +They bind to stable agent/version/setup keys and never transfer to a new setup. + +Average uses available row scores and reports the count. A row comparison uses +shared measured capabilities for best and weakest differences in percentage +points. Benchmark-version comparisons are temporary: settings and ranks do not +change. Missing evidence for a replacement version leaves affected axes and +Overall differences absent, rather than renormalizing a partial comparison. +Radar segments connect only adjacent measured axes, including wraparound. + +Efficiency averages distinct selected real trials, deduplicated across mappings, +with infrastructure excluded. Time uses observed agent durations; cost uses +observed costs, each with its own count. Steps and Tool calls load later from +trajectories on the page; the command completes that read synchronously. Missing +or malformed traces are unavailable, not zero. Changed trace content invalidates +its cached metrics without reparsing unchanged traces. diff --git a/docs/settings/README.md b/docs/settings/README.md index bbe948b3..b68394d5 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -13,6 +13,7 @@ Existing results open without credentials. | [Hosts](run-hosts.md) | SSH machines | | [Data providers](data-providers.md) | Hugging Face and Docker Hub connections | | [Sandbox](sandbox.md) | Docker on this machine, the Boat key | +| [Scoring settings](#scoring-settings) | Leaderboard mappings, weights and custom scores | | [General](other.md) | Tour and checklist | ## Variables @@ -73,6 +74,7 @@ credential values. Linux defaults: | Stores | Default | | --- | --- | +| Composite scoring | `~/.config/nullius/scoring.json` | | Saved settings | `~/.config/nullius/settings.json` | | Benchmark credentials | `~/.config/nullius/secrets//` | | Hugging Face token | `~/.config/nullius/secrets/data-provider-huggingface/` | @@ -130,3 +132,39 @@ Set `NULLIUS_HOME` before both commands to migrate into a separate profile. Start-up options. + +## Scoring settings + +Open **Scoring settings** from the Leaderboard head; **Leaderboard** returns to +its table and charts. The dedicated page orders Custom benchmarks, Capabilities, +then Domains. Read-only clients can inspect it; only local clients can write. + +Each entry chooses a benchmark, dataset, pinned version, supported metric and +independent weight in that axis. Score is always offered; pass^3 is offered for +pass/fail benchmarks. Zero weight disables an entry without removing it. +Weight in Overall controls each axis separately, including domains. +Configured shares update while editing; the Leaderboard evidence shows effective +shares among the sources actually measured for that row. + +Valid complete documents autosave, followed by **Scoring saved**. There is no +Save button. Invalid inputs stay in the draft and do not change active scoring. +A failed write keeps the draft and shows Retry. A conflicting edit from another +page requires reloading before editing again. + +Manual benchmarks have a unique trimmed name and optional scores from 0 to 100 +per agent/version/setup. Blank means absent; zero is measured. Rename preserves +scores; removing a custom benchmark removes its scores and mappings together. +Verified only ignores these scores; All scores includes them and identifies +their unverified influence. + +Scoring is profile-wide in `scoring.json`, beside `settings.json` in the directory +shown by `nullius paths`. Writes replace the complete validated document +atomically. Malformed content uses defaults with a warning and is left intact. +Removed catalogue references remain unavailable and can be removed without +blocking unrelated edits. Negative or nonfinite weights, duplicate identical +entries, duplicate custom names, invalid scores and all-zero Overall weights +are refused. + +**Reset to defaults** asks in place before resetting mappings and weights and +removing all custom benchmarks and scores. Cancel and failed writes preserve the +previous document. diff --git a/pyproject.toml b/pyproject.toml index 6ab39768..e56d61a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,4 +56,4 @@ dependencies = {file = ["app/requirements.txt"]} "nullius.catalogue" = ["agents/*/*.json", "agents/*/*.py", "agents/*/*.toml", "agents/*/*.yaml", "agents/*/*.txt", "benchmarks/*/env/*", "benchmarks/*/*.json", "benchmarks/*/*.py", "benchmarks/*/*.yml", "benchmarks/*/startup/*.py", "capabilities/*/*.json", "capabilities/*/*.py"] "nullius.standard" = ["kits/*/*.json", "kits/*/*.py", "kits/*/*.Dockerfile", "kits/*/*.txt"] "nullius.judge" = ["floors.json"] -_nullius_app = ["templates/**/*.html", "templates/*.svg", "static/**/*.css", "static/**/*.js", "static/**/*.svg", "static/**/*.png", "static/**/*.json", "static/**/*.woff2", "static/**/*.ttf", "static/**/*.txt", "static/**/*.md", "requirements.txt", ".env.example"] +_nullius_app = ["templates/**/*.html", "templates/*.svg", "static/**/*.css", "static/**/*.js", "static/**/*.svg", "static/**/*.png", "static/**/*.ico", "static/**/*.json", "static/**/*.woff2", "static/**/*.ttf", "static/**/*.txt", "static/**/*.md", "requirements.txt", ".env.example"] From 5fbc337e78baad93af3158ee0acb53ca12dea749 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 25 Nov 2026 18:51:44 +0100 Subject: [PATCH 3/3] fix(web): enforce leaderboard evidence identity and preserve chart interaction --- .github/workflows/tests.yml | 9 +- AGENTS.md | 8 + .../benchmarks/osworld1/standard.json | 20 +- app/nullius/leaderboard/board.py | 14 +- app/nullius/leaderboard/cli.py | 2 +- app/nullius/leaderboard/configuration.py | 20 +- app/nullius/leaderboard/scopes.py | 24 +++ app/nullius/leaderboard/scoring.py | 6 +- app/nullius/leaderboard/service.py | 12 +- app/nullius/standard/contract/definitions.py | 21 +- app/nullius/standard/runner/job.py | 6 +- app/static/leaderboard/board.js | 36 ++-- app/static/leaderboard/motion.js | 103 ++++++++++ app/templates/leaderboard/board.html | 2 +- app/tests/test_categorical_charts.py | 4 +- app/tests/test_leaderboard_board.py | 25 ++- app/tests/test_leaderboard_service.py | 38 +++- app/tests/test_leaderboard_weights.py | 1 + app/tests/test_standard_definitions.py | 8 + app/ui_tests/browser/leaderboard.py | 192 ++++++++++++++++++ app/ui_tests/browser/mutations.py | 28 +++ app/ui_tests/browser/requirements.txt | 2 + app/ui_tests/test_leaderboard_routes.py | 38 +++- docs/benchmarks/add-manually.md | 10 + docs/cli/read-jobs.md | 3 +- docs/field-guide.md | 8 +- docs/settings/README.md | 6 +- 27 files changed, 592 insertions(+), 54 deletions(-) create mode 100644 app/nullius/leaderboard/scopes.py create mode 100644 app/static/leaderboard/motion.js create mode 100644 app/ui_tests/browser/leaderboard.py create mode 100644 app/ui_tests/browser/mutations.py create mode 100644 app/ui_tests/browser/requirements.txt diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9a1c9995..1096f0ec 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,4 +1,4 @@ -# The application's two suites and installable package, on every non-draft PR +# The application's backend, route and browser suites and installable package, on every non-draft PR # (again when a draft is marked ready) and by hand. There are no model calls # or containers: the docker tier is the nightly docker-tests workflow. uv is a test tool; Flask # is the app's only Python dependency. @@ -6,7 +6,7 @@ # Nothing shared is installed, because nothing shared is imported: the backend # is this repository's own code under app/nullius/ and imports only the # standard library. The Harbor build tests invoke uv against offline fixtures; -# only the route suite needs Flask. +# the web suites need Flask; browser interactions also use test-only Playwright. name: tests on: @@ -55,6 +55,11 @@ jobs: - name: route suite # Includes the recipe-compilation tests, which need Node. run: python3 app/tests/parallel.py app/ui_tests + - name: Leaderboard browser interactions + run: | + uv run --no-project --with-requirements app/ui_tests/browser/requirements.txt python -m playwright install --with-deps chromium + uv run --no-project --with-requirements app/requirements.txt --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/leaderboard.py + uv run --no-project --with-requirements app/requirements.txt --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/mutations.py - name: installed package # Temporary installs only; no publication or stored artifact. run: | diff --git a/AGENTS.md b/AGENTS.md index a25288ac..0b87c0cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,6 +80,14 @@ python3 app/tests/parallel.py uv run --no-project --with-requirements app/requirements.txt \ python app/tests/parallel.py app/ui_tests +# real-browser interactions (test-only dependency; install Chromium once) +uv run --no-project --with-requirements app/ui_tests/browser/requirements.txt \ + python -m playwright install chromium +uv run --no-project --with-requirements app/requirements.txt \ + --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/leaderboard.py +uv run --no-project --with-requirements app/requirements.txt \ + --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/mutations.py + # one module; a route module under uv as above, with -s app/ui_tests NULLIUS_HOME=$(mktemp -d) python3 -m unittest discover -s app/tests -t app -p test_live.py diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 42b94424..42d49969 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -367,5 +367,23 @@ "branch": "main" } } - } + }, + "task_parts": [ + { + "id": "os", + "label": "OS tasks", + "prefixes": [ + "os__" + ] + }, + { + "id": "office", + "label": "Office tasks", + "prefixes": [ + "libreoffice_calc__", + "libreoffice_impress__", + "libreoffice_writer__" + ] + } + ] } diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py index a9c00d8c..98d49485 100644 --- a/app/nullius/leaderboard/board.py +++ b/app/nullius/leaderboard/board.py @@ -4,11 +4,10 @@ import hashlib import json import copy -from dataclasses import replace from math import isfinite from nullius.standard.contract import definitions -from . import configuration, scoring, weights +from . import configuration, scoring, weights, scopes def project(jobs, agents, benchmarks, settings, benchmark, version, *, all_scores=False): @@ -58,10 +57,10 @@ def _entry_key(entry): def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_open=True, metric_sources=None): """Pure board projection. Inputs belong to a single workspace and profile.""" - config = configuration.validate(settings, benchmarks) + config = configuration.validate(settings, benchmarks, allow_unavailable=True) agents = [a for a in agents if not a.get("example") and a["key"] not in ("nop", "oracle")] agents_by = {a["key"]: a for a in agents} - benchmarks_by = {(b["key"], b.get("_version", "")): b for b in benchmarks} + benchmarks_by = {(b["key"], definitions.version_identity(b)): b for b in benchmarks} customs = {c["id"]: c for c in config["custom"]} grouped, identities = {}, {} for job in jobs: @@ -108,12 +107,9 @@ def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_ope if bench is None: evidence["reason"] = "Benchmark version unavailable" else: - manifests = {d["id"]: d.get("tasks") if isinstance(d.get("tasks"), dict) else None for d in bench.get("datasets", [])} - # The standard writes benchmark/dataset; only remove this exact declared prefix. - recorded = {f"{bench['key']}/{d}": d for d in manifests} - normalized = [replace(j, dataset=recorded.get(j.dataset, j.dataset)) for j in runs] + manifests, normalized, dataset = scopes.select(bench, entry["dataset"], runs) got = scoring.contribution(normalized, benchmark=entry["benchmark"], version=entry["version"], datasets=manifests, - dataset=entry["dataset"], metric=entry["metric"], graded=bench.get("score", {}).get("kind") == "score") + dataset=dataset, metric=entry["metric"], graded=bench.get("score", {}).get("kind") == "score") evidence.update(score=got.score, tasks=got.total, covered=got.covered, excluded=got.excluded, runs=list(got.run_ids), reason=got.reason, note=got.note) if entry["weight"] > 0 and got.score is not None: diff --git a/app/nullius/leaderboard/cli.py b/app/nullius/leaderboard/cli.py index 2ada66d5..574ccea8 100644 --- a/app/nullius/leaderboard/cli.py +++ b/app/nullius/leaderboard/cli.py @@ -13,7 +13,7 @@ def main(argv=None): parser = argparse.ArgumentParser(prog="nullius leaderboard", description=__doc__, epilog="Configuration: scoring.json in the profile configuration directory (nullius paths). Edit it through Scoring settings or as a complete JSON document. Exit 0: read; 2: usage; 3: missing root. Unavailable measurements and invalid-settings fallback are disclosed in the output.") - parser.add_argument("roots", nargs="*", help="result roots in one workspace; omit for unscored catalogue rows") + parser.add_argument("roots", nargs="*", help="result roots in one workspace; omit for catalogue rows without recorded-run measurements; --all-scores can still include saved manual scores") parser.add_argument("--json", action="store_true", help="full precision scores, identity, evidence, ranks/reasons and observed metric counts") parser.add_argument("--all-scores", action="store_true", help="include unverified manual scores; default: verified only") args = parser.parse_args(argv) diff --git a/app/nullius/leaderboard/configuration.py b/app/nullius/leaderboard/configuration.py index ccd44855..cc63d730 100644 --- a/app/nullius/leaderboard/configuration.py +++ b/app/nullius/leaderboard/configuration.py @@ -7,6 +7,8 @@ from pathlib import Path from nullius import ondisk, paths +from nullius.standard.contract import definitions +from . import scopes DOMAINS = ("Travel", "Dining", "Shopping", "Money", "Health", "Home", "Work") CAPABILITIES = ("Memory", "Safety", "Consistency", "Personalization", "Proactivity", "Retrieval", "Communication", "Execution") @@ -31,7 +33,7 @@ def location(): def defaults(benchmarks): - versions = {b["key"]: b.get("_version", "") for b in benchmarks + versions = {b["key"]: definitions.version_identity(b) for b in benchmarks if b.get("_version") == b.get("_default")} return {"schema": 1, "custom": [], "axes": { axis: {"weight": weight, "entries": [ @@ -45,7 +47,7 @@ def _number(value, label, upper=None): raise ValueError(f"{label}: enter a finite number between 0 and {upper}" if upper is not None else f"{label}: enter a finite nonnegative number") -def validate(document, benchmarks): +def validate(document, benchmarks, *, previous=None, allow_unavailable=False): """Validate every field before a write; preserve removed catalogue references.""" if not isinstance(document, dict) or set(document) != {"schema", "custom", "axes"} or document["schema"] != 1: raise ValueError("Invalid scoring document") @@ -67,7 +69,9 @@ def validate(document, benchmarks): for value in custom["scores"].values(): if value is not None: _number(value, "Custom score", 100) - available = {(b["key"], b.get("_version", "")): b for b in benchmarks} + available = {(b["key"], definitions.version_identity(b)): b for b in benchmarks} + preserved = {tuple(e.get(k) for k in ("benchmark", "dataset", "version", "metric")) + for a in (previous or {}).get("axes", {}).values() for e in a.get("entries", []) if "benchmark" in e} for name, axis in doc["axes"].items(): if not isinstance(axis, dict) or set(axis) != {"weight", "entries"} or not isinstance(axis["entries"], list): raise ValueError(f"{name}: invalid axis") @@ -88,6 +92,11 @@ def validate(document, benchmarks): if entry["metric"] not in ("Score", "pass^3") or (entry["metric"] == "pass^3" and bench is not None and (bench.get("score") or {}).get("kind") != "pass"): raise ValueError("Choose Score or supported pass^3") identity = tuple(entry[k] for k in ("benchmark", "dataset", "version", "metric")) + if bench is None and not allow_unavailable and identity not in preserved: + raise ValueError("Choose a catalogue benchmark version") + if (bench is not None and entry["dataset"] and entry["dataset"] not in {c["id"] for c in scopes.choices(bench)} + and not allow_unavailable and identity not in preserved): + raise ValueError("Choose a declared dataset or task-name part") if identity in seen: raise ValueError(f"{name}: duplicate entry") seen.add(identity) @@ -106,7 +115,7 @@ def remove_custom(document, key): def load(path, benchmarks): try: - return validate(json.loads(Path(path).read_text()), benchmarks), "" + return validate(json.loads(Path(path).read_text()), benchmarks, allow_unavailable=True), "" except FileNotFoundError: return defaults(benchmarks), "" except (OSError, ValueError, TypeError): @@ -114,7 +123,8 @@ def load(path, benchmarks): def save(path, document, benchmarks): - doc = validate(document, benchmarks) + previous, _ = load(path, benchmarks) + doc = validate(document, benchmarks, previous=previous) path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) ondisk.write_whole(path, json.dumps(doc, ensure_ascii=False, indent=2, allow_nan=False) + "\n", mode=0o600) diff --git a/app/nullius/leaderboard/scopes.py b/app/nullius/leaderboard/scopes.py new file mode 100644 index 00000000..316db2de --- /dev/null +++ b/app/nullius/leaderboard/scopes.py @@ -0,0 +1,24 @@ +"""Declared dataset and task-name parts, with no guessed task aliases.""" +from dataclasses import replace + + +def choices(benchmark): + return [{"id": d["id"], "label": d.get("label", d["id"])} + for d in benchmark.get("datasets", []) + benchmark.get("task_parts", [])] + + +def select(benchmark, dataset, runs): + manifests = {d["id"]: d.get("tasks") if isinstance(d.get("tasks"), dict) else None + for d in benchmark.get("datasets", [])} + recorded = {f"{benchmark['key']}/{d}": d for d in manifests} + normalized = [replace(j, dataset=recorded.get(j.dataset, j.dataset)) for j in runs] + part = next((p for p in benchmark.get("task_parts", []) if p["id"] == dataset), None) + if part: + prefixes = tuple(part["prefixes"]) + matches = lambda name: name.startswith(prefixes) + manifests = {d: {n: canonical for n, canonical in m.items() if matches(n)} if m is not None else None + for d, m in manifests.items()} + normalized = [replace(j, trials=[t for t in j.trials if matches(t.task_name)]) for j in normalized] + normalized = [j for j in normalized if j.trials] + dataset = "" + return manifests, normalized, dataset diff --git a/app/nullius/leaderboard/scoring.py b/app/nullius/leaderboard/scoring.py index 69f048a5..3e395c4d 100644 --- a/app/nullius/leaderboard/scoring.py +++ b/app/nullius/leaderboard/scoring.py @@ -81,7 +81,7 @@ def contribution(jobs: Sequence[Job], *, benchmark: str, version: str, total = len({canonical for manifest in manifests for canonical in manifest.values()}) if all(m is not None for m in manifests) else None pool = [j for j in jobs if eligible(j) and j.dataset in scope and j.identity.get("benchmark") == benchmark - and j.identity.get("benchmark_version", "") == version] + and version and j.identity.get("benchmark_version") == version] sources = {source for j in pool for source in j.merged_from} pool = [j for j in pool if j.job_id not in sources] selected = {} @@ -90,7 +90,9 @@ def contribution(jobs: Sequence[Job], *, benchmark: str, version: str, selected.setdefault(j.dataset, j) ids = tuple(j.job_id for j in selected.values()) if not selected: - return Contribution(total=total) + missing = any(eligible(j) and j.dataset in scope and j.identity.get("benchmark") == benchmark + and not j.identity.get("benchmark_version") for j in jobs) + return Contribution(total=total, reason="Benchmark version not recorded" if missing else "not run") if len(selected) > 1 and any(scope[d] is None for d in selected): return Contribution(total=total, run_ids=ids, reason="Task identity unavailable for aggregation") union = {} diff --git a/app/nullius/leaderboard/service.py b/app/nullius/leaderboard/service.py index 8e0d1c99..c2f91205 100644 --- a/app/nullius/leaderboard/service.py +++ b/app/nullius/leaderboard/service.py @@ -8,7 +8,7 @@ from nullius.standard.contract import definitions from nullius import charts -from . import board, configuration, metrics, weights +from . import board, configuration, metrics, weights, scopes def catalogue(): @@ -24,9 +24,9 @@ def revision(): def options(benchmarks): - return [{"key": b["key"], "label": b["label"], "version": b.get("_version", ""), - "version_label": definitions.version_label(b), "metrics": ["Score", "pass^3"] if b.get("score", {}).get("kind") == "pass" else ["Score"], - "datasets": [{"id": d["id"], "label": d.get("label", d["id"])} for d in b.get("datasets", [])]} + return [{"key": b["key"], "label": b["label"], "version": definitions.version_identity(b), + "version_label": (definitions.version_label(b) or definitions.version_identity(b)[:7]), "metrics": ["Score", "pass^3"] if b.get("score", {}).get("kind") == "pass" else ["Score"], + "datasets": scopes.choices(b)} for b in benchmarks] @@ -39,8 +39,8 @@ def document(jobs, *, workspace="", workspace_open=False, all_scores=False, defe "jobs": [(j.job_id, j.uid, str(j.finished_at), len(j.trials), j.identity, j.dir) for j in jobs]} result["context"] = hashlib.sha256(json.dumps(context, sort_keys=True).encode()).hexdigest() result["warning"], result["revision"] = warning, revision() - result["versions"] = [{"benchmark": b["key"], "version": b.get("_version", ""), - "label": b["label"] + " · " + (definitions.version_label(b) or "Official")} + result["versions"] = [{"benchmark": b["key"], "version": definitions.version_identity(b), + "label": b["label"] + " · " + ((definitions.version_label(b) or definitions.version_identity(b)[:7]) or "Official")} for b in benchmarks if any(e.get("benchmark") == b["key"] for a in settings["axes"].values() for e in a["entries"])] for row in result["rows"]: for axis in row["axes"].values(): diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 5ffe7d8c..c344a3bb 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -166,7 +166,7 @@ def setup_label(bench, which): # What a version may say for itself; the rest of the file is shared. VERSIONED = ("upstream", "install", "start", "model", "env", "options", "caches", "fidelity", "proven") # What a benchmark's version may say for itself: its data, its driver, how it scores, who plays its user, its environments. -BENCH_VERSIONED = ("upstream", "datasets", "files", "driver", "mcp_servers", "score", "simulator", "limits", "controls", "environments", +BENCH_VERSIONED = ("upstream", "datasets", "task_parts", "files", "driver", "mcp_servers", "score", "simulator", "limits", "controls", "environments", "options", "host", "setups", "proven", "leaderboard") # What a benchmark option may need: embedding and reranker models through the relay, # machine requirements (host), and digest-pinned auxiliary files. @@ -250,6 +250,11 @@ def _version_upstream(d: dict, v: str) -> dict: return dict(up, **own, version=v) +def version_identity(d: dict) -> str: + """The explicit release identity, or the pinned source commit of an unversioned definition.""" + return str(d.get("_version") or (d.get("upstream") or {}).get("tested") or "") + + def version_label(d: dict) -> str: """A version as a reader names it: its release tag, else its branch and short commit (``main (044bc33)``), else its key.""" @@ -1562,6 +1567,20 @@ def problems(d: dict, kind: str) -> List[str]: bad += _ports("needs", needs, d.get("family")) if isinstance(needs, list) and not needs: bad.append("needs: at least one port") + parts = d.get("task_parts", []) + seen_parts = {x.get("id") for x in (d.get("datasets") or []) if isinstance(x, dict)} + if not isinstance(parts, list): + bad.append("task_parts: a list of named task-prefix selections") + else: + for part in parts: + if (not isinstance(part, dict) or set(part) != {"id", "label", "prefixes"} + or not isinstance(part["id"], str) or not part["id"] or part["id"] in seen_parts + or not isinstance(part["label"], str) or not part["label"].strip() + or not isinstance(part["prefixes"], list) or not part["prefixes"] + or any(not isinstance(p, str) or not p for p in part["prefixes"])): + bad.append("task_parts: unique id, label and nonempty task-name prefixes required") + else: + seen_parts.add(part["id"]) bad += _host(d) bad += _files(d) bad += _bench_options(d) diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index ab4ad58f..b9d449ad 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -32,6 +32,7 @@ from nullius import ondisk from nullius.standard.calls import ledger +from nullius.standard.contract import definitions from nullius.traces import otel from nullius.traces.breakdown import breakdown @@ -225,9 +226,8 @@ def agent_name(other: dict) -> str: def _version(bench: dict) -> dict: - """A benchmark with versions says which one ran (``benchmark_version``), and the - ``key@version`` that names it; one without says nothing more than its key.""" - v = bench.get("_version") if "@" in str(bench.get("_ref") or "") else None + """Record the explicit benchmark release or source pin, never an inferred current default.""" + v = definitions.version_identity(bench) return {"benchmark_version": v, "benchmark_ref": bench["_ref"]} if v else {} diff --git a/app/static/leaderboard/board.js b/app/static/leaderboard/board.js index 5da6c200..24b9118b 100644 --- a/app/static/leaderboard/board.js +++ b/app/static/leaderboard/board.js @@ -2,7 +2,8 @@ (() => { let data = JSON.parse(document.getElementById('lb-data').textContent); const marks = JSON.parse(document.getElementById('lb-marks').textContent), table = document.getElementById('leaderboard-table'); - let selected = data.selected, versus = 'average', family = 'capabilities', metric = 'time', generation = 0, focusBefore = null, projection = null, comparisonGeneration = 0; + let selected = data.selected, versus = 'average', family = 'capabilities', metric = 'time', generation = 0, focusBefore = null, projection = null, comparisonGeneration = 0, returningFocus = false, tableMotion = null; + const motion=window.LeaderboardMotion; const percent = v => v == null ? '—' : `${Number((v * 100).toFixed(1))}%`; const element = (tag, text, attrs = {}) => { const e = document.createElement(tag); if (text != null) e.textContent = text; Object.entries(attrs).forEach(([k,v]) => e.setAttribute(k,v)); return e; }; const svg = (tag, attrs = {}, text) => { const e = document.createElementNS('http://www.w3.org/2000/svg',tag); Object.entries(attrs).forEach(([k,v]) => e.setAttribute(k,v)); if (text != null) e.textContent = text; return e; }; @@ -38,9 +39,9 @@ pop.style.left = `${Math.max(12,Math.min(box.left,innerWidth-pop.offsetWidth-12))}px`; pop.style.top = `${Math.max(12,Math.min(box.bottom+6,innerHeight-pop.offsetHeight-12))}px`; } - document.addEventListener('keydown', e => { if (e.key === 'Escape') { dismiss(); focusBefore?.focus(); } }); + document.addEventListener('keydown', e => { if (e.key === 'Escape') { dismiss(); returningFocus=true;focusBefore?.focus();returningFocus=false; } }); document.addEventListener('pointerdown', e => { if (!pop.contains(e.target) && !e.target.closest('[data-axis]')) dismiss(); }); - document.addEventListener('focusin', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); + document.addEventListener('focusin', e => { const target=e.target.closest('[data-axis]'); if(target&&!returningFocus) evidence(target); }); document.addEventListener('pointerover', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); document.addEventListener('click', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); function medal(rank) { @@ -51,6 +52,8 @@ const icon=svg('svg',{'aria-hidden':'true',viewBox:'0 0 24 24'});icon.append(svg('use',{href:rank===4?'#i-medal-bitten':'#i-medal'}));span.append(icon,element('span',rank));return span; } function updateTable() { + tableMotion?.capture(); + const focused=document.activeElement; data.rows.forEach(r => { const tr = [...table.tBodies[0].rows].find(t => t.dataset.key === r.key); if (!tr) return; tr.dataset.sortTie = r.name + ' ' + r.version_label + ' ' + r.key; @@ -62,10 +65,13 @@ tr.querySelector('[data-name]').textContent = r.name + (same ? ' · '+[r.identity.model,r.identity.effort].filter(Boolean).join(' ') : ''); tr.querySelectorAll('[data-axis]').forEach(cell => { const a=cell.dataset.axis==='Overall'?{score:r.overall,unverified:r.unverified}:r.axes[cell.dataset.axis]; - cell.textContent=percent(a.score);cell.dataset.sort=a.score??''; + let value=cell.querySelector('.lb-value');if(!value){cell.replaceChildren();value=element('span',null,{class:'lb-value'});cell.append(value);} + value.textContent=percent(a.score);cell.dataset.sort=a.score??''; cell.classList.toggle('lb-unverified',Boolean(a.unverified)); cell.style.setProperty('--lb-shade',`${a.score==null?0:Math.max(0,Math.min(1,(a.score-.2)/.6))*20}%`); - if(a.score!=null) { const bar=element('span',null,{class:'lb-bar'});bar.style.setProperty('--lb-value',`${a.score*100}%`);cell.append(bar); } + let bar=cell.querySelector('.lb-bar'); + if(a.score!=null){if(!bar){bar=element('span',null,{class:'lb-bar'});cell.append(bar);}bar.style.setProperty('--lb-value',`${a.score*100}%`);} + else bar?.remove(); }); for(const [field,m] of Object.entries(r.metrics)) { const cell=tr.querySelector(`[data-col="${field}"]`);cell.textContent=m.value==null?'—':field==='cost'?`$${m.value.toFixed(2)}`:Number(m.value.toFixed(1))+(field==='time'?'s':'');cell.dataset.sort=m.value??'';cell.title=`${m.count} observed`; } table.tBodies[0].append(tr); @@ -78,6 +84,7 @@ table.dispatchEvent(new Event('table:update')); document.getElementById('lb-trust-key').hidden=!data.rows.some(r=>r.custom_names.length); applyFamily(); + if(focused?.isConnected&&document.activeElement!==focused)focused.focus({preventScroll:true}); } function applyFamily() { document.querySelectorAll('[data-family]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.family===family))); @@ -88,13 +95,13 @@ function selectable(node,key,x,y) { node.setAttribute('tabindex','0');node.setAttribute('role','button');node.dataset.select=key;node.dataset.cx=x;node.dataset.cy=y;node.classList.add('lb-point');node.setAttribute('aria-label',`${row(key)?.name} ${row(key)?.version_label}`);node.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();choose(key);}});return node; } function nearest(plot) { plot.addEventListener('click',e=>{if(e.target.closest('text[data-select]'))return;const pt=plot.createSVGPoint();pt.x=e.clientX;pt.y=e.clientY;const p=pt.matrixTransform(plot.getScreenCTM().inverse());const points=[...plot.querySelectorAll('[data-cx]')].map(n=>({n,d:Math.hypot(p.x-Number(n.dataset.cx),p.y-Number(n.dataset.cy))})).sort((a,b)=>a.d-b.d||a.n.dataset.select.localeCompare(b.n.dataset.select));if(points[0]&&points[0].d<30){e.stopPropagation();choose(points[0].n.dataset.select);}},true); } function drawScatter() { - const plot=document.getElementById('lb-scatter'), panel=data.scatter[metric];plot.replaceChildren();plot.setAttribute('viewBox',`0 0 360 ${panel.height}`); + const live=document.getElementById('lb-scatter'),plot=svg('svg'), panel=data.scatter[metric];live.setAttribute('viewBox',`0 0 360 ${panel.height}`); const defs=svg('defs'), gradient=svg('linearGradient',{id:'lb-efficiency-tint',x1:0,y1:0,x2:1,y2:1}); gradient.append(svg('stop',{offset:'0%','stop-color':'var(--good)','stop-opacity':'.12'}),svg('stop',{offset:'50%','stop-color':'var(--bg)','stop-opacity':'0'}),svg('stop',{offset:'100%','stop-color':'var(--bad)','stop-opacity':'.12'}));defs.append(gradient);plot.append(defs,svg('rect',{x:48,y:22,width:304,height:210,fill:'url(#lb-efficiency-tint)'})); plot.append(svg('text',{x:54,y:38,class:'lb-better'},'BETTER')); for(const m of panel.marks) { if(m.shape==='tile') { - const group=selectable(svg('g'),m.key,m.x,m.y), mark=marks[m.key];group.append(svg('title',{},m.title)); + const group=selectable(svg('g',{'data-node':'point:'+m.key}),m.key,m.x,m.y), mark=marks[m.key];group.append(svg('title',{},m.title)); group.append(svg('rect',{x:m.x-11,y:m.y-11,width:22,height:22,rx:4,fill:'var(--bg)',class:m.key===selected?'lb-selected':''})); if(mark?.includes('#')) {const icon=svg('svg',{x:m.x-9,y:m.y-9,width:18,height:18,viewBox:'0 0 24 24'});icon.append(svg('use',{href:mark}));group.append(icon);} else if(mark) group.append(svg('image',{x:m.x-9,y:m.y-9,width:18,height:18,href:mark})); @@ -102,7 +109,8 @@ plot.append(group); } else plot.append(svg('line',{x1:m.x,y1:m.y,x2:m.x2,y2:m.y2,class:m.cls})); } - for(const t of panel.texts) {const text=svg('text',{x:t.x,y:t.y,'text-anchor':t.anchor,class:t.cls});t.lines.forEach((line,i)=>text.append(svg('tspan',{x:t.x,dy:i?15:0,class:i?'small':''},line)));if(t.key) {text.dataset.select=t.key;text.setAttribute('tabindex','0');text.addEventListener('keydown',e=>{if(e.key==='Enter')choose(t.key);});}plot.append(text);} + for(const t of panel.texts) {const text=svg('text',{x:t.x,y:t.y,'text-anchor':t.anchor,class:t.cls});t.lines.forEach((line,i)=>text.append(svg('tspan',{x:t.x,dy:i?15:0,class:i?'small':''},line)));if(t.key) {text.dataset.node='name:'+t.key;text.dataset.select=t.key;text.setAttribute('tabindex','0');text.addEventListener('keydown',e=>{if(e.key==='Enter')choose(t.key);});}plot.append(text);} + motion.morph(live,plot); } nearest(document.getElementById('lb-scatter')); function chart(kind,group) { @@ -110,21 +118,23 @@ const plot=svg('svg',{viewBox:`0 0 360 ${kind==='strips'?names.length*42+20:320}`,role:'group','aria-label':`${group} ${kind}`}); if(kind==='strips') names.forEach((name,i)=>{ const y=30+i*42, label=svg('text',{x:0,y:y-10,tabindex:0,'data-axis':name},name);plot.append(label,svg('line',{x1:0,y1:y,x2:350,y2:y,class:'grid'})); - data.rows.forEach(r=>{const score=r.axes[name].score;if(score==null)return;const node=selectable(svg('circle',{cx:score*340+5,cy:y,r:r.key===selected?5:3,class:r.key===selected?'lb-selected':''}),r.key,score*340+5,y);node.append(svg('title',{},`${r.name} ${r.version_label} ${r.identity.model||''}: ${percent(score)}${r.axes[name].unverified?' · not verified':''}`));plot.append(node);}); + data.rows.forEach(r=>{const score=r.axes[name].score;if(score==null)return;const node=selectable(svg('circle',{cx:score*340+5,cy:y,'data-node':name+':'+r.key,'data-reveal':i,r:r.key===selected?5:3,class:r.key===selected?'lb-selected':''}),r.key,score*340+5,y);node.append(svg('title',{},`${r.name} ${r.version_label} ${r.identity.model||''}: ${percent(score)}${r.axes[name].unverified?' · not verified':''}`));plot.append(node);}); const score=compared(name);if(score!=null){const x=score*340+5;plot.append(versus==='average'?svg('line',{x1:x,y1:y-8,x2:x,y2:y+8,class:'lb-comparison','stroke-dasharray':'2 2'}):svg('path',{d:`M${x} ${y-6}l6 6-6 6-6-6Z`,class:'lb-comparison'}));} plot.append(svg('text',{x:350,y:y-10,'text-anchor':'end'},`${percent(current.axes[name].score)} / ${percent(score)}${versus==='average'?' (n='+data.averages[name].count+')':''}`)); }); else { const at=(i,value)=>[180+Math.sin(i/names.length*2*Math.PI)*90*value,155-Math.cos(i/names.length*2*Math.PI)*90*value]; names.forEach((name,i)=>{const [x,y]=at(i,1),[lx,ly]=at(i,1.3);plot.append(svg('line',{x1:180,y1:155,x2:x,y2:y,class:'grid'}));const label=svg('text',{x:Math.max(name.length*4,Math.min(360-name.length*4,lx)),y:ly,tabindex:0,'text-anchor':'middle','data-axis':name},name);plot.append(label);}); - for(const compare of [false,true]) names.forEach((name,i)=>{const score=compare?compared(name):current.axes[name].score;if(score==null)return;const [x,y]=at(i,score),next=(i+1)%names.length,v=compare?compared(names[next]):current.axes[names[next]].score;if(v!=null){const [nx,ny]=at(next,v);plot.append(svg('line',{x1:x,y1:y,x2:nx,y2:ny,class:'lb-radar-line'+(compare?' lb-comparison':'')}));}const point=svg('circle',{cx:x,cy:y,r:4,tabindex:0,'data-axis':name,class:'lb-point'+(compare?' lb-comparison':'')});point.append(svg('title',{},`${name}: ${percent(score)}`));plot.append(point);}); + for(const compare of [false,true]) names.forEach((name,i)=>{const score=compare?compared(name):current.axes[name].score;if(score==null)return;const [x,y]=at(i,score),next=(i+1)%names.length,v=compare?compared(names[next]):current.axes[names[next]].score;if(v!=null){const [nx,ny]=at(next,v);plot.append(svg('line',{x1:x,y1:y,x2:nx,y2:ny,'data-node':'segment:'+compare+':'+name,'data-reveal':i,class:'lb-radar-line'+(compare?' lb-comparison':'')}));}const point=svg('circle',{cx:x,cy:y,r:4,tabindex:0,'data-node':'point:'+compare+':'+name,'data-reveal':i,'data-axis':name,class:'lb-point'+(compare?' lb-comparison':'')});point.append(svg('title',{},`${name}: ${percent(score)}`));plot.append(point);}); } plot.querySelectorAll('text[data-axis]').forEach(label=>{ const grow=on=>plot.querySelectorAll(`circle[data-axis="${label.dataset.axis}"]`).forEach(point=>point.classList.toggle('lb-hover',on)); label.addEventListener('pointerenter',()=>grow(true));label.addEventListener('pointerleave',()=>grow(false)); label.addEventListener('focus',()=>grow(true));label.addEventListener('blur',()=>grow(false)); }); - container.replaceChildren(plot);nearest(plot); + const live=container.querySelector('svg'); + if(live)motion.morph(live,plot); + else {container.append(plot);nearest(plot);motion.reveal(plot,kind);} } function draw() { const current=row(selected);if(!current)return; @@ -137,12 +147,12 @@ if(current.custom_names.length)card.append(element('p',`Not verified: ${current.custom_names.join(', ')}`)); drawScatter();for(const kind of ['strips','radars'])for(const group of ['domains','capabilities'])chart(kind,group); } - document.querySelectorAll('[data-family]').forEach(b=>b.onclick=()=>{family=b.dataset.family;applyFamily();}); + document.querySelectorAll('[data-family]').forEach(b=>b.onclick=()=>{family=b.dataset.family;applyFamily();table.querySelectorAll('td[data-axis]:not([hidden])').forEach(cell=>{if(cell.dataset.axis!=='Overall')motion.fade(cell,[{opacity:0},{opacity:1}],200);});}); document.querySelectorAll('[data-agent-select]').forEach(s=>s.onchange=()=>choose(s.value)); async function compareChoice() { const turn=++comparisonGeneration;projection=null;if(versus.startsWith('version:')) {const [benchmark,version]=JSON.parse(versus.slice(8));const response=await nulliusFetch('/api/leaderboard/comparison?'+new URLSearchParams({benchmark,version,all_scores:data.all_scores?'1':'0'}));if(response.ok){const result=await response.json();if(turn!==comparisonGeneration)return;projection=result;}}draw();} document.querySelectorAll('[data-vs-select]').forEach(s=>{data.versions.forEach(v=>s.append(element('option',`Same agent: ${v.label}`,{value:'version:'+JSON.stringify([v.benchmark,v.version])})));s.onchange=()=>{versus=s.value;document.querySelectorAll('[data-vs-select]').forEach(v=>v.value=versus);compareChoice().catch(()=>{});};}); document.getElementById('lb-metric').onchange=e=>{metric=e.target.value;drawScatter();}; async function deferred(turn) { const response=await nulliusFetch(`/api/leaderboard/metrics?all_scores=${data.all_scores?1:0}&context=${encodeURIComponent(data.context)}`);if(!response.ok)return;const result=await response.json();if(turn!==generation||result.context!==data.context)return;result.rows.forEach(r=>{const existing=row(r.key);if(existing)existing.metrics=r.metrics;});updateTable(); } document.getElementById('lb-mode').onchange=async e=>{const turn=++generation;const response=await nulliusFetch(`/api/leaderboard?all_scores=${e.target.value}`);if(!response.ok)return;const next=await response.json();if(turn!==generation)return;data=next;updateTable();compareChoice().catch(()=>{});draw();deferred(turn).catch(()=>{});}; - updateTable();choose(selected);deferred(generation).catch(()=>{}); + updateTable();choose(selected);tableMotion=motion.table(table);deferred(generation).catch(()=>{}); })(); diff --git a/app/static/leaderboard/motion.js b/app/static/leaderboard/motion.js new file mode 100644 index 00000000..ae08f9d6 --- /dev/null +++ b/app/static/leaderboard/motion.js @@ -0,0 +1,103 @@ +/* Persistent SVG nodes and cancellable geometry transitions for the composite view. */ +window.LeaderboardMotion = (() => { + const reduced = matchMedia('(prefers-reduced-motion: reduce)'); + const active = new Map(), timing = {duration:320, easing:'cubic-bezier(.2,.7,.2,1)'}; + const numeric = new Set(['x','y','cx','cy','x1','y1','x2','y2','r','data-cx','data-cy']); + function cancel(node, finish=false) { const old=active.get(node);if(old){old.cancel(finish);active.delete(node);} } + function fade(node, frames, duration=320, delay=0) { + cancel(node,true);if(reduced.matches)return; + const animation=node.animate(frames,{...timing,duration,delay}); + const controller={cancel:()=>animation.cancel()};active.set(node,controller); + animation.finished.then(()=>{if(active.get(node)===controller)active.delete(node);},()=>{}); + } + function geometry(node, from, to, delay=0) { + cancel(node);const keys=Object.keys(to).filter(k=>from[k]!=null && from[k]!==to[k]); + const set=values=>Object.entries(values).forEach(([k,v])=>node.setAttribute(k,v)); + if(!keys.length||reduced.matches){set(to);return;} + const pairs=keys.map(k=>[k,Number(from[k]),Number(to[k])]).filter(([,a,b])=>Number.isFinite(a)&&Number.isFinite(b)); + if(!pairs.length){set(to);return;} + set(from); + const animation=node.animate([{opacity:.7},{opacity:1}],{...timing,delay}); + let frame, start=null; + const controller={cancel:finish=>{cancelAnimationFrame(frame);animation.cancel();if(finish)set(to);}}; + active.set(node,controller); + const draw=now=>{ + start??=now;const t=Math.max(0,Math.min(1,(now-start-delay)/timing.duration)); + // Use the Web Animation's computed easing for the same curve as table motion. + const p=animation.effect.getComputedTiming().progress ?? t; + pairs.forEach(([k,a,b])=>node.setAttribute(k,a+(b-a)*p)); + if(t<1)frame=requestAnimationFrame(draw); + else {set(to);animation.cancel();if(active.get(node)===controller)active.delete(node);} + }; + frame=requestAnimationFrame(draw); + } + function key(node, index) { return node.nodeType===1 ? node.getAttribute('data-node') || `${node.tagName}:${index}` : `text:${index}`; } + function children(live, next) { + const old=new Map([...live.childNodes].map((n,i)=>[key(n,i),n])); + let cursor=live.firstChild; + [...next.childNodes].forEach((fresh,i)=>{ + const id=key(fresh,i);let node=old.get(id); + if(!node||node.nodeType!==fresh.nodeType||node.nodeName!==fresh.nodeName)node=fresh; + else { + old.delete(id); + if(node.nodeType===3)node.textContent=fresh.textContent; + else { + const from={},to={}; + for(const a of fresh.attributes)if(numeric.has(a.name)){from[a.name]=node.getAttribute(a.name);to[a.name]=a.value;} + cancel(node); + for(const a of [...node.attributes])if(!fresh.hasAttribute(a.name))node.removeAttribute(a.name); + for(const a of fresh.attributes)node.setAttribute(a.name,a.value); + children(node,fresh);geometry(node,from,to); + } + } + if(node!==cursor)live.insertBefore(node,cursor); + cursor=node.nextSibling; + }); + old.forEach(n=>{n.querySelectorAll?.('*').forEach(x=>cancel(x));cancel(n);n.remove();}); + } + function morph(live,next) { + const focus=document.activeElement,axis=focus?.dataset?.axis; + children(live,next); + if(focus!==document.activeElement){ + if(focus.isConnected)focus.focus({preventScroll:true}); + else if(axis)live.querySelector(`text[data-axis="${axis}"]`)?.focus({preventScroll:true}); + } + } + function reveal(plot,kind) { + if(reduced.matches)return; + const observer=new IntersectionObserver(entries=>{ + if(!entries.some(e=>e.isIntersecting))return;observer.disconnect(); + plot.querySelectorAll('[data-reveal]').forEach(node=>{ + if(kind==='strips')fade(node,[{transform:'translateX(-24px)',opacity:0},{transform:'translateX(0)',opacity:1}]); + else { + const from={},to={}; + for(const k of ['cx','cy','x1','y1','x2','y2'])if(node.hasAttribute(k)){to[k]=node.getAttribute(k);from[k]=k.startsWith('x')||k==='cx'?180:155;} + geometry(node,from,to,Number(node.dataset.reveal)*35); + } + }); + });observer.observe(plot); + } + function table(table) { + const measure=()=>new Map([...table.querySelectorAll('tr,th,td')].map(n=>[n,{rect:n.getBoundingClientRect(),text:n.textContent}])); + let previous=measure(),frame; + const capture=()=>{previous=measure();}; + const update=()=>{ + cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>{ + const next=measure(); + next.forEach(({rect,text},node)=>{ + const old=previous.get(node);if(!old||!rect.width||!rect.height)return; + const dx=old.rect.width?old.rect.x-rect.x:0,dy=node.tagName==='TR'?old.rect.y-rect.y:0; + if(Math.abs(dx)+Math.abs(dy)>.5)fade(node,[{transform:`translate(${dx}px,${dy}px)`},{transform:'translate(0,0)'}]); + else if(old.text!==text)fade(node,[{opacity:.25},{opacity:1}]); + });previous=next; + }); + }; + new MutationObserver(update).observe(table,{subtree:true,childList:true,attributes:true,attributeFilter:['hidden','style']}); + for(const event of ['click','input','change','keydown'])document.addEventListener(event,e=>{ + if(e.target.closest(`#${table.id}, #${table.id}-tools`))capture(); + },true); + return {capture}; + } + reduced.addEventListener('change',()=>{if(reduced.matches)[...active.keys()].forEach(n=>cancel(n,true));}); + return {morph,reveal,table,fade,reduced}; +})(); diff --git a/app/templates/leaderboard/board.html b/app/templates/leaderboard/board.html index e5794ce0..b013670e 100644 --- a/app/templates/leaderboard/board.html +++ b/app/templates/leaderboard/board.html @@ -40,4 +40,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/tests/test_categorical_charts.py b/app/tests/test_categorical_charts.py index 3e6a2254..ff27d7a2 100644 --- a/app/tests/test_categorical_charts.py +++ b/app/tests/test_categorical_charts.py @@ -116,7 +116,7 @@ def test_every_run_keeps_its_own_dot_and_tag_and_ties_sit_around_one_place(self) def test_logo_tiles_and_two_line_labels_do_not_overlap(self): x = c.Metric("Time", tuple(c.Value(name, value, str(value), tag=name, note="2.2.2", key=str(i)) - for i, (name, value) in enumerate((("Codex", 40), ("Goose", 40), ("Terminus", 40.1))))) + for i, (name, value) in enumerate((("Alpha", 40), ("Bravo", 40), ("Charlie", 40), ("Delta", 40))))) p = c.scatter(x, c.Metric("Overall", tuple(c.Value(v.name, .75, "75%") for v in x.values)), tiles=True) tiles = [(m.x-11, m.y-11, m.x+11, m.y+11) for m in p.marks if m.shape == "tile"] labels = [] @@ -124,7 +124,7 @@ def test_logo_tiles_and_two_line_labels_do_not_overlap(self): width = c._TAG_W * max(map(len, t.lines)) left = {"start": t.x, "middle": t.x-width/2, "end": t.x-width}[t.anchor] labels.append((left, t.y-c._TAG_H+3, left+width, t.y+3+15*(len(t.lines)-1))) - self.assertEqual(len(labels), 3) + self.assertEqual(len(labels), 4) for i, box in enumerate(tiles + labels): self.assertFalse(any(c._overlaps(box, other) for other in (tiles+labels)[i+1:])) diff --git a/app/tests/test_leaderboard_board.py b/app/tests/test_leaderboard_board.py index 3447aebd..c7d6f384 100644 --- a/app/tests/test_leaderboard_board.py +++ b/app/tests/test_leaderboard_board.py @@ -105,13 +105,36 @@ def test_c6_attempted_unavailable_entry_still_requires_verified_evidence(self): self.assertIsNone(a["rank"]) self.assertIn("Tau not run", a["reasons"]) + def test_task_name_part_uses_its_distinct_union_and_excludes_other_tasks(self): + from tests.test_comparison import trial + bench = self.benchmarks[0] + bench["task_parts"] = [{"id": "os", "label": "OS tasks", "prefixes": ["os__"]}] + bench["datasets"] = [{"id": "first", "tasks": {"os__shared": "shared", "office__other": "other"}}, + {"id": "second", "tasks": {"os__shared": "shared", "os__unique": "unique"}}] + self.config["axes"]["Retrieval"]["entries"][0]["dataset"] = "os" + first = self.make_run("A", []) + first.trials = [trial("os__shared", "resolved"), trial("office__other", "resolved")] + second = replace(first, job_id="second", dataset="second", trials=[trial("os__shared", "agent_error"), trial("os__unique", "resolved")]) + row = self.build([first, second])["rows"][0] + entry = row["axes"]["Retrieval"]["entries"][0] + self.assertEqual((entry["score"], entry["covered"], entry["tasks"]), (.5, 2, 2)) + self.assertEqual(row["rank"], 1) + def test_c13_missing_version_evidence_never_renormalizes_a_difference(self): - jobs = [self.make_run("A", ["resolved"])] + self.benchmarks.append({"key": "other", "label": "Other", "_version": "v1", "score": {"kind": "pass"}, + "datasets": [{"id": "first", "tasks": {"0": "0", "1": "1"}}]}) + other = {"benchmark": "other", "version": "v1", "dataset": "", "metric": "Score", "weight": 1} + self.config["axes"]["Retrieval"]["entries"].append(other) + self.config["axes"]["Execution"] = {"weight": 1, "entries": [other]} + jobs = [self.make_run("A", ["resolved"]), + replace(self.make_run("A", ["resolved", "agent_error"], benchmark="other"), job_id="other-run")] original = self.build(jobs) + self.assertEqual(original["rows"][0]["axes"]["Retrieval"]["score"], .75) projected = board.project(jobs, self.agents, self.benchmarks, self.config, "gaia", "unrun") row = next(r for r in projected["rows"] if r["has_runs"]) self.assertIsNone(row["axes"]["Retrieval"]["score"]) self.assertIsNone(row["overall"]) + self.assertEqual(row["axes"]["Execution"]["score"], .5) self.assertEqual(self.build(jobs), original) diff --git a/app/tests/test_leaderboard_service.py b/app/tests/test_leaderboard_service.py index bcbf463b..e8ee2270 100644 --- a/app/tests/test_leaderboard_service.py +++ b/app/tests/test_leaderboard_service.py @@ -11,10 +11,39 @@ from tests.test_comparison import job, trial from nullius.runs import parse from nullius.standard.contract import definitions +from nullius.standard.runner import job as recorded_job from nullius.leaderboard import board, configuration class RecordedIdentity(unittest.TestCase): + def test_new_standard_runs_record_the_resolved_source_pin(self): + for key in ("gaia", "osworld1"): + bench = definitions.get("benchmark", key) + expected = bench.get("_version") or bench["upstream"]["tested"] + recorded = recorded_job._version(bench) + self.assertEqual(recorded["benchmark_version"], expected) + identity = parse.identity_of({"standard": {"benchmark": key, **recorded}}, {}, "") + self.assertEqual(identity["benchmark_version"], expected) + + def test_no_roots_all_scores_can_rank_a_saved_manual_catalogue_score(self): + from nullius.leaderboard import service + with tempfile.TemporaryDirectory() as folder, patch.dict(os.environ, NULLIUS_HOME=folder): + agents, benches = service.catalogue() + doc = configuration.defaults(benches) + key = board.build([], agents, benches, doc)["rows"][0]["key"] + doc["custom"] = [{"id": "calendar", "name": "Calendar", "scores": {key: 72}}] + doc["axes"]["Personalization"]["entries"] = [{"custom": "calendar", "weight": 1}] + configuration.save(configuration.location(), doc, benches) + env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1])) + for flags, expected in (([], None), (["--all-scores"], .72)): + result = subprocess.run([sys.executable, "-m", "nullius", "leaderboard", "--json", *flags], env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + row = next(r for r in json.loads(result.stdout)["rows"] if r["key"] == key) + self.assertEqual(row["overall"], expected) + self.assertEqual(row["rank"], 1 if flags else None) + self.assertFalse(row["has_runs"]) + self.assertTrue(all(m["value"] is None for m in row["metrics"].values())) + def test_real_cli_reads_gaia_and_banking_result_directories(self): with tempfile.TemporaryDirectory() as folder: root = Path(folder) / "jobs" @@ -22,7 +51,7 @@ def test_real_cli_reads_gaia_and_banking_result_directories(self): ("bank-run", "tau3-bench", "banking_knowledge", ("pass",))): path = root / name path.mkdir(parents=True) - (path / "config.json").write_text(json.dumps({"standard": {"benchmark": benchmark, "plugged": "codex"}, + (path / "config.json").write_text(json.dumps({"standard": {"benchmark": benchmark, "plugged": "codex", **recorded_job._version(definitions.get("benchmark", benchmark))}, "agents": [{"name": "codex", "model_name": "model"}], "datasets": [{"name": f"{benchmark}/{dataset}"}]})) (path / "result.json").write_text(json.dumps({"started_at": "2026-11-01T10:00:00Z", "finished_at": "2026-11-01T11:00:00Z"})) for i, outcome in enumerate(outcomes): @@ -46,7 +75,7 @@ def test_real_cli_reads_gaia_and_banking_result_directories(self): self.assertEqual(row["axes"]["Money"]["score"], 1) self.assertEqual(row["company"], "OpenAI") - def test_unversioned_catalogue_and_real_parser_agree_without_a_wildcard(self): + def test_missing_version_is_unavailable_and_explicit_pin_matches(self): agents = definitions.load("agent")[0] benches = definitions.load("benchmark")[0] cfg = {"standard": {"benchmark": "gaia", "plugged": "codex"}, @@ -56,6 +85,11 @@ def test_unversioned_catalogue_and_real_parser_agree_without_a_wildcard(self): self.assertNotIn("benchmark_version", run.identity) result = board.build([run], agents, benches, configuration.defaults(benches)) row = next(r for r in result["rows"] if r["has_runs"]) + self.assertIsNone(row["axes"]["Retrieval"]["score"]) + self.assertEqual(row["axes"]["Retrieval"]["entries"][0]["reason"], "Benchmark version not recorded") + run.identity["benchmark_version"] = next(b for b in benches if b["key"] == "gaia")["upstream"]["tested"] + result = board.build([run], agents, benches, configuration.defaults(benches)) + row = next(r for r in result["rows"] if r["has_runs"]) self.assertEqual(row["axes"]["Retrieval"]["score"], .5) self.assertEqual(row["company"], "OpenAI") run.identity["benchmark_version"] = "unknown-version" diff --git a/app/tests/test_leaderboard_weights.py b/app/tests/test_leaderboard_weights.py index 5cd9584d..5a1dde63 100644 --- a/app/tests/test_leaderboard_weights.py +++ b/app/tests/test_leaderboard_weights.py @@ -76,6 +76,7 @@ def test_c19_broken_settings_warn_without_overwrite_and_removed_references_survi self.assertEqual(doc, self.defaults) self.assertIn("defaults", warning) self.assertEqual(self.path.read_text(), "{") + configuration.save(self.path, self.defaults, self.benchmarks) configuration.save(self.path, self.defaults, []) self.assertEqual(json.loads(self.path.read_text()), self.defaults) diff --git a/app/tests/test_standard_definitions.py b/app/tests/test_standard_definitions.py index e916321d..6d9e2cbd 100644 --- a/app/tests/test_standard_definitions.py +++ b/app/tests/test_standard_definitions.py @@ -118,6 +118,14 @@ def test_an_example_is_marked_true_or_false_on_an_agent_or_a_feature(self): self.bad(BENCH, "benchmark", lambda d: d.update(example=True), "example: true or false") self.assertIs(definitions.get("agent", "reference", definitions.CATALOGUE).get("example"), True) + def test_task_parts_require_distinct_names_and_task_prefixes(self): + part = {"id": "office", "label": "Office tasks", "prefixes": ["writer__"]} + self.assertEqual(definitions.problems(dict(BENCH, task_parts=[part]), "benchmark"), []) + for parts in (None, {}, [dict(part, id="all")], [part, part], + [dict(part, prefixes=[])], [dict(part, prefixes=[""])], + [dict(part, prefixes="writer__")], [dict(part, label=" ")]): + self.bad(BENCH, "benchmark", lambda d: d.update(task_parts=parts), "task_parts:") + def test_agent_company_is_optional_nonempty_text(self): self.assertEqual(definitions.problems(dict(AGENT, company="Maker"), "agent"), []) for value in (None, "", " ", 7): diff --git a/app/ui_tests/browser/leaderboard.py b/app/ui_tests/browser/leaderboard.py new file mode 100644 index 00000000..0ea623f8 --- /dev/null +++ b/app/ui_tests/browser/leaderboard.py @@ -0,0 +1,192 @@ +"""Real Chromium interactions against Flask routes and the shipped Leaderboard scripts. + +Run with the test-only requirements in this directory. No server or benchmark is started. +""" +from contextlib import ExitStack +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch +from urllib.parse import urlsplit + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from playwright.sync_api import sync_playwright, expect +from ui_tests.test_routes import web +from tests.test_comparison import job, trial +from nullius.leaderboard import configuration, service +from nullius.standard.contract import definitions + + +class LeaderboardBrowser(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.playwright = sync_playwright().start() + options = {"executable_path": os.environ["NULLIUS_TEST_CHROMIUM"]} if os.environ.get("NULLIUS_TEST_CHROMIUM") else {} + cls.browser = cls.playwright.chromium.launch(**options) + + @classmethod + def tearDownClass(cls): + cls.browser.close() + cls.playwright.stop() + + def setUp(self): + self.stack = ExitStack() + self.addCleanup(self.stack.close) + home = self.stack.enter_context(tempfile.TemporaryDirectory()) + self.stack.enter_context(patch.dict(os.environ, NULLIUS_HOME=home)) + self.stack.enter_context(patch.dict(web.shared.STATE, workspace=None, roots=[], job_roots=[], label="")) + self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) + pin = definitions.version_identity(definitions.get("benchmark", "gaia")) + self.jobs = [] + for agent, outcomes in (("codex", ["resolved", "resolved"]), ("goose", ["resolved", "agent_error"])): + r = job([trial(str(i), outcome) for i, outcome in enumerate(outcomes)], dataset="gaia/gaia-validation", agent=agent, job_id=agent) + r.identity = {"agent": agent, "agent_version": definitions.get("agent", agent)["_version"], "benchmark": "gaia", "benchmark_version": pin} + self.jobs.append(r) + self.stack.enter_context(patch.object(web.shared, "_load_jobs", return_value=self.jobs)) + config = configuration.defaults(service.catalogue()[1]) + config["axes"]["Communication"]["entries"] = [dict(config["axes"]["Retrieval"]["entries"][0])] + configuration.save(configuration.location(), config, service.catalogue()[1]) + self.client = web.app.test_client() + self.context = self.browser.new_context(viewport={"width": 1280, "height": 900}) + self.addCleanup(self.context.close) + self.page = self.context.new_page() + self.page.set_default_timeout(5000) + self.errors, self.posts = [], [] + self.fail_save = False + self.page.on("pageerror", lambda error: self.errors.append(str(error))) + self.page.route("**/*", self.route) + + def route(self, route): + request = route.request + url = urlsplit(request.url) + if url.hostname != "localhost": + route.abort() + return + if url.path == "/api/scoring" and request.method == "POST": + self.posts.append(json.loads(request.post_data)) + if self.fail_save: + route.fulfill(status=503, json={"error": "Scoring settings could not be saved. Retry."}) + return + response = self.client.open(url.path + ("?" + url.query if url.query else ""), method=request.method, + data=request.post_data, headers=dict(request.headers)) + try: + body=response.get_data() + mutation=os.environ.get('NULLIUS_BROWSER_MUTATION') + changes={ + 'keyboard': ('/static/leaderboard/board.js', "if(e.key==='Enter'||e.key===' ')", 'if(false)'), + 'autosave': ('/static/leaderboard/scoring.js', 'timer=setTimeout(save,300)', 'timer=setTimeout(()=>{},300)'), + 'escape': ('/static/leaderboard/board.js', 'if(target&&!returningFocus)', 'if(target)'), + 'morph': ('/static/leaderboard/motion.js', 'if(!keys.length||reduced.matches)', 'if(true)'), + } + if mutation in changes and url.path==changes[mutation][0]: + _,before,after=changes[mutation] + assert before.encode() in body + body=body.replace(before.encode(),after.encode()) + headers=dict(response.headers) + headers.pop('Content-Length',None) + route.fulfill(status=response.status_code, headers=headers, body=body) + finally: + response.close() + + def open(self, path): + self.page.goto("http://localhost" + path) + self.page.wait_for_load_state("networkidle") + self.page.evaluate("document.querySelector('[data-a=\"no\"]')?.click()") + + def choose(self, selector, index): + button=self.page.locator(selector).first.locator('xpath=following-sibling::button[1]') + button.scroll_into_view_if_needed() + self.page.evaluate('()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))') + button.click() + self.page.locator(f'.ui-select-menu [data-index="{index}"]').click() + + def test_escape_from_evidence_link_dismisses_and_returns_focus(self): + self.open("/leaderboard") + cell = self.page.locator('tbody tr [data-axis="Retrieval"]').first + cell.focus() + link = self.page.locator('#lb-evidence a').first + expect(link).to_be_visible() + link.focus() + self.page.keyboard.press("Escape") + expect(self.page.locator('#lb-evidence')).to_be_hidden() + expect(cell).to_be_focused() + # Returning normally to the trigger still opens it. + self.page.locator('#lb-mode').locator('xpath=following-sibling::button[1]').focus() + cell.focus() + expect(self.page.locator('#lb-evidence')).to_be_visible() + self.assertFalse(self.errors) + + def test_logo_keyboard_selection_keeps_node_focus_and_morphs_radar(self): + self.open("/leaderboard") + self.page.locator('[data-chart="radars-capabilities"]').scroll_into_view_if_needed() + self.page.wait_for_timeout(700) # settle the first visibility animation + self.page.evaluate("window.oldRadar=document.querySelector('[data-chart=\"radars-capabilities\"] svg')") + point = self.page.locator('#lb-scatter g[data-select]').nth(1) + point.focus() + self.page.evaluate("window.oldPoint=document.activeElement") + self.page.keyboard.press("Enter") + expect(self.page.locator('#lb-card h2')).to_have_text('Goose') + self.assertTrue(self.page.evaluate("oldPoint.isConnected && document.activeElement===oldPoint && oldRadar===document.querySelector('[data-chart=\"radars-capabilities\"] svg')")) + self.assertGreater(self.page.evaluate("document.querySelector('[data-chart=\"radars-capabilities\"]').getAnimations({subtree:true}).length"), 0) + self.assertFalse(self.errors) + + def test_agent_comparison_changes_cancel_and_reduced_motion_is_immediate(self): + self.open('/leaderboard') + self.page.locator('[data-chart="radars-capabilities"]').scroll_into_view_if_needed() + self.choose('[data-agent-select]', 1) + self.choose('[data-agent-select]', 0) + self.page.wait_for_timeout(400) + expect(self.page.locator('#lb-card h2')).to_have_text('Codex') + self.page.emulate_media(reduced_motion='reduce') + self.choose('[data-agent-select]', 1) + self.assertEqual(self.page.evaluate('document.getAnimations().length'), 0) + expect(self.page.locator('#lb-card h2')).to_have_text('Goose') + self.assertFalse(self.errors) + + def test_first_visibility_and_table_changes_animate(self): + self.open('/leaderboard') + radar=self.page.locator('[data-chart="radars-capabilities"]') + radar.scroll_into_view_if_needed() + self.page.wait_for_function("""document.querySelector('[data-chart="radars-capabilities"]').getAnimations({subtree:true}).length>0""") + self.assertGreater(radar.evaluate('(e)=>e.getAnimations({subtree:true}).length'),0) + self.page.locator('th[data-col="overall"]').click() + self.page.locator('th[data-col="overall"]').click() + self.page.wait_for_timeout(40) + self.assertGreater(self.page.locator('tbody').evaluate('(e)=>e.getAnimations({subtree:true}).length'),0) + search=self.page.locator('#leaderboard-table-tools [data-search]') + search.fill('Goose') + expect(search).to_be_focused() + expect(self.page.locator('tbody tr:visible [data-name]')).to_have_text('Goose') + self.page.wait_for_timeout(400) + self.assertFalse(self.errors) + + def test_autosave_valid_invalid_retry_and_latest_edit(self): + self.open('/scoring') + weight = self.page.locator('[data-scoring-axis="Retrieval"] [data-entries] input').first + with self.page.expect_response(lambda r: r.url.endswith('/api/scoring') and r.request.method == 'POST'): + weight.fill('3') + self.assertEqual(self.posts[-1]['axes']['Retrieval']['entries'][0]['weight'], 3) + before = configuration.location().read_bytes() + weight.fill('-1') + self.page.wait_for_timeout(400) + expect(weight).to_have_attribute('aria-invalid', 'true') + self.assertEqual(configuration.location().read_bytes(), before) + self.fail_save = True + with self.page.expect_response(lambda r: r.status == 503): + weight.fill('4') + expect(self.page.locator('[data-settings-retry]')).to_be_visible() + self.fail_save = False + with self.page.expect_response(lambda r: r.url.endswith('/api/scoring') and r.status == 200): + self.page.locator('[data-settings-retry]').click() + weight.fill('5') + with self.page.expect_response(lambda r: r.url.endswith('/api/scoring') and r.request.method == 'POST'): + weight.fill('6') + self.assertEqual(configuration.load(configuration.location(), service.catalogue()[1])[0]['axes']['Retrieval']['entries'][0]['weight'], 6) + self.assertFalse(self.errors) + + +if __name__ == '__main__': + unittest.main() diff --git a/app/ui_tests/browser/mutations.py b/app/ui_tests/browser/mutations.py new file mode 100644 index 00000000..997a4c1c --- /dev/null +++ b/app/ui_tests/browser/mutations.py @@ -0,0 +1,28 @@ +"""Prove the interaction regressions reject disabled keyboard, autosave, dismissal and morphing.""" +import io +import os +import unittest +from unittest.mock import patch +from leaderboard import LeaderboardBrowser + +CASES = { + 'keyboard': 'test_logo_keyboard_selection_keeps_node_focus_and_morphs_radar', + 'autosave': 'test_autosave_valid_invalid_retry_and_latest_edit', + 'escape': 'test_escape_from_evidence_link_dismisses_and_returns_focus', + 'morph': 'test_logo_keyboard_selection_keeps_node_focus_and_morphs_radar', +} + +if __name__ == '__main__': + for mutation, name in CASES.items(): + with patch.dict(os.environ, NULLIUS_BROWSER_MUTATION=mutation): + output = io.StringIO() + result = unittest.TextTestRunner(stream=output).run(unittest.TestSuite([LeaderboardBrowser(name)])) + # Errors from environment/setup do not prove a regression was caught. + failures = result.failures + result.errors + expected = {'keyboard': "Goose", 'autosave': 'waiting for event "response"', + 'escape': 'Locator expected to be hidden', 'morph': 'not greater than 0'}[mutation] + caught = len(failures) == 1 and expected in failures[0][1] + print(f'{mutation}: {"CAUGHT" if caught else "NOT CAUGHT"}') + if not caught: + print(output.getvalue()) + raise SystemExit(1) diff --git a/app/ui_tests/browser/requirements.txt b/app/ui_tests/browser/requirements.txt new file mode 100644 index 00000000..94276702 --- /dev/null +++ b/app/ui_tests/browser/requirements.txt @@ -0,0 +1,2 @@ +# Test-only browser automation; Flask remains the application's sole runtime dependency. +playwright==1.65.2 diff --git a/app/ui_tests/test_leaderboard_routes.py b/app/ui_tests/test_leaderboard_routes.py index 82969935..bdf79636 100644 --- a/app/ui_tests/test_leaderboard_routes.py +++ b/app/ui_tests/test_leaderboard_routes.py @@ -45,7 +45,9 @@ def test_empty_pages_keep_catalogue_axes_and_four_blocks(self): def test_api_and_cli_use_same_profile_scores_without_eager_trace_loads(self): run = job([trial("a"), trial("b", "agent_error")], dataset="gaia/gaia-validation", agent="codex") - run.identity = parse.identity_of({"standard": {"benchmark": "gaia", "plugged": "codex"}, "agents": [{"name": "codex", "model_name": "model"}]}, {}, "2.2.2") + from nullius.standard.contract import definitions + from nullius.standard.runner import job as recorded_job + run.identity = parse.identity_of({"standard": {"benchmark": "gaia", "plugged": "codex", **recorded_job._version(definitions.get("benchmark", "gaia"))}, "agents": [{"name": "codex", "model_name": "model"}]}, {}, "2.2.2") self.jobs.append(run) with patch("nullius.traces.trajectory.load") as load: response = self.client.get("/api/leaderboard") @@ -62,6 +64,40 @@ def test_api_and_cli_use_same_profile_scores_without_eager_trace_loads(self): response = self.client.get("/api/leaderboard/metrics", query_string={"context": "old-workspace"}) self.assertEqual(response.status_code, 409) + def test_new_unknown_dataset_is_rejected_but_saved_removed_part_can_be_edited(self): + self.client.get("/scoring") + with self.client.session_transaction() as session: + headers = {"X-CSRF-Token": session["csrf"], "Origin": "http://localhost"} + doc = self.client.get("/api/scoring").get_json()["settings"] + self.assertEqual(self.client.post("/api/scoring", json=doc, headers=headers).status_code, 200) + before = configuration.location().read_bytes() + pinned = doc["axes"]["Retrieval"]["entries"][0]["version"] + doc["axes"]["Retrieval"]["entries"][0]["version"] = "invented-version" + self.assertEqual(self.client.post("/api/scoring", json=doc, headers=headers).status_code, 400) + self.assertEqual(configuration.location().read_bytes(), before) + doc["axes"]["Retrieval"]["entries"][0]["version"] = pinned + doc["axes"]["Retrieval"]["entries"][0]["dataset"] = "not-a-real-dataset" + self.assertEqual(self.client.post("/api/scoring", json=doc, headers=headers).status_code, 400) + self.assertEqual(configuration.location().read_bytes(), before) + configuration.location().write_text(json.dumps(doc)) # a reference removed from the catalogue + doc["axes"]["Money"]["weight"] = 1 + self.assertEqual(self.client.post("/api/scoring", json=doc, headers=headers).status_code, 200) + doc["axes"]["Retrieval"]["entries"][0]["dataset"] = "another-invention" + self.assertEqual(self.client.post("/api/scoring", json=doc, headers=headers).status_code, 400) + + def test_osworld_default_parts_read_only_matching_task_names(self): + self.jobs.append(job([trial("os__one", "scored", score=1), trial("libreoffice_writer__two", "scored", score=.5), + trial("chrome__three", "scored", score=0)], dataset="osworld1/test_nogdrive", agent="codex")) + self.jobs[0].identity = {"benchmark": "osworld1", "benchmark_version": "desktop-env-v1.0.3", "agent": "codex", "agent_version": "2.2.2"} + doc = self.client.get("/api/leaderboard").get_json() + row = next(r for r in doc["rows"] if r["has_runs"]) + self.assertEqual(row["axes"]["Home"]["score"], 1) + self.assertEqual(row["axes"]["Work"]["score"], .5) + from nullius.leaderboard import service + choices = next(b for b in service.options(service.catalogue()[1]) if b["key"] == "osworld1")["datasets"] + self.assertIn({"id": "os", "label": "OS tasks"}, choices) + self.assertIn({"id": "office", "label": "Office tasks"}, choices) + def test_scoring_validates_atomic_documents_and_protects_writes(self): self.client.get("/scoring") with self.client.session_transaction() as session: diff --git a/docs/benchmarks/add-manually.md b/docs/benchmarks/add-manually.md index 6ea08c99..35684eb9 100644 --- a/docs/benchmarks/add-manually.md +++ b/docs/benchmarks/add-manually.md @@ -82,3 +82,13 @@ By hand: the [worked Harbor entry](../examples/new-benchmark/README.md). - [Add with an assistant](add-with-assistant.md) + +## Task-name parts + +A benchmark can declare `task_parts` for scoring a subset across its datasets. +Each part has a unique `id`, a display `label`, and nonempty `prefixes` matching +the task names its driver records. Part IDs must differ from dataset IDs. +Versions may override the parts. OSWorld uses `os__` for OS tasks and the +`libreoffice_calc__`, `libreoffice_impress__`, and `libreoffice_writer__` prefixes +for office tasks. A part does not establish full task coverage without a task +manifest. diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index 28dd86be..87b9d707 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -79,7 +79,8 @@ nullius leaderboard ./jobs --all-scores ``` Supply the result roots of one workspace. This reads completed jobs; it never -launches work. Without roots, it returns unscored catalogue rows. Exit 0 means +launches work. Without roots, catalogue rows have no recorded-run measurements. With +`--all-scores`, saved manual scores can still contribute and rank those rows. Exit 0 means the document was read; an invalid root exits 3, invalid arguments 2. Verified only is the default. `--all-scores` includes saved manual scores. diff --git a/docs/field-guide.md b/docs/field-guide.md index eeb4f301..1c56b115 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -302,7 +302,13 @@ repeated runs are not pooled. Explicit merged runs replace their source shards. A whole-benchmark entry unions selected datasets by canonical task identity; an overlap uses the same run precedence and retains that task's attempts. Unknown identities make aggregation or full coverage unavailable rather than -guessing aliases. A dataset entry reads only that dataset. +guessing aliases. A dataset entry reads only that dataset. A declared task-name +part reads only tasks matching its catalogue prefixes, across the selected +datasets; its coverage uses the same filtered task union. + +An entry requires an explicitly recorded benchmark version. For an unversioned +catalogue benchmark, new standard runs record its tested source pin. Older runs +without that identity remain unavailable; the current default is never inferred. Score is adjusted solve rate for pass/fail tasks. Graded scores preserve recorded part weighting within a task, including agent crashes as zero with their part diff --git a/docs/settings/README.md b/docs/settings/README.md index b68394d5..2940d83b 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -139,7 +139,7 @@ Open **Scoring settings** from the Leaderboard head; **Leaderboard** returns to its table and charts. The dedicated page orders Custom benchmarks, Capabilities, then Domains. Read-only clients can inspect it; only local clients can write. -Each entry chooses a benchmark, dataset, pinned version, supported metric and +Each entry chooses a benchmark, dataset or declared task-name part, pinned version, supported metric and independent weight in that axis. Score is always offered; pass^3 is offered for pass/fail benchmarks. Zero weight disables an entry without removing it. Weight in Overall controls each axis separately, including domains. @@ -161,7 +161,9 @@ Scoring is profile-wide in `scoring.json`, beside `settings.json` in the directo shown by `nullius paths`. Writes replace the complete validated document atomically. Malformed content uses defaults with a warning and is left intact. Removed catalogue references remain unavailable and can be removed without -blocking unrelated edits. Negative or nonfinite weights, duplicate identical +blocking unrelated edits. New mappings must name a declared dataset/part and +version. Legacy entries with an empty version remain unavailable until a pinned +version is selected; runs also need that recorded identity. Negative or nonfinite weights, duplicate identical entries, duplicate custom names, invalid scores and all-zero Overall weights are refused.