diff --git a/AGENTS.md b/AGENTS.md index 109434f1b..c1a5d04be 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/app.py b/app/app.py index 0445ff89c..0f51c211e 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 0546056c4..9ce686846 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 01928a1b0..0338f0bd8 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 c20a9925b..84462c5ca 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 42a257bdc..c9b7e4606 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 d7d51c837..4bec14f07 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 42a873ab1..f83d5ccc7 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 3b33e0103..5fca9fb3d 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 de10d38d3..434dd2196 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/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 684ffbc73..d036bcb9c 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/charts.py b/app/nullius/charts.py index 849d270b1..60a5aed9d 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 aa9609093..708a46c2a 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/__init__.py b/app/nullius/leaderboard/__init__.py new file mode 100644 index 000000000..e2b637ea6 --- /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 000000000..791530fee --- /dev/null +++ b/app/nullius/leaderboard/board.py @@ -0,0 +1,186 @@ +"""One workspace's composite scores, evidence, coverage and rank requirements.""" +from __future__ import annotations + +import hashlib +import json +import copy +from math import isfinite +from nullius.standard.contract import definitions + +from . import configuration, scoring, weights, scopes + + +def project(jobs, agents, benchmarks, settings, benchmark, version): + """A comparison projection: missing changed evidence invalidates its affected axis.""" + draft = copy.deepcopy(settings) + affected = set() + for name, axis in draft["axes"].items(): + merged = {} + for entry in axis["entries"]: + if entry.get("benchmark") == benchmark: + entry["version"] = version + if entry["weight"] > 0: + affected.add(name) + # an axis that listed two versions of the benchmark now lists one entry, with both weights + same = merged.setdefault(_entry_key(entry), entry) + if same is not entry: + same["weight"] += entry["weight"] + axis["entries"] = list(merged.values()) + # what each row measured of the benchmark before: a row that never ran it loses nothing to another version + had = {row["key"]: {(name, e["dataset"], e["metric"]) for name, axis in row["axes"].items() for e in axis["entries"] + if e.get("benchmark") == benchmark and e["weight"] > 0 and e["score"] is not None} + for row in build(jobs, agents, benchmarks, settings)["rows"]} + result = build(jobs, agents, benchmarks, draft) + 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 + and (name, e["dataset"], e["metric"]) in had.get(row["key"], ()) for e in axis["entries"]): + axis["score"] = None + axis["share"] = 0 + if axis["weight"] > 0: + family = "capabilities" if name in configuration.CAPABILITIES else "domains" + row["families"][family]["overall"] = None + row["overall"] = row["families"]["capabilities"]["overall"] + row["rank"] = None + for family in row["families"].values(): + family["rank"] = None + return result + + +def row_identity(job): + identity = job.identity + # a run names its agent as the user chose it: "codex", or "codex@2.2.2" for a version of it + agent, version = definitions.split(identity.get("agent", job.agent_name)) + # which tasks, how many at a time, the whole run's spending cap and retries after an infrastructure + # failure change coverage, never how a task is done + limits = {k: v for k, v in identity.get("limits", {}).items() + if k not in ("repeat", "n_tasks", "task_names", "sample", "seed", "concurrency", "max_usd", "retries")} + return {"agent": agent, "version": version or 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": identity.get("backend") or 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, *, workspace_open=True, metric_sources=None): + """Pure board projection. Inputs belong to a single workspace and profile.""" + 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"], definitions.version_identity(b)): b for b in benchmarks} + 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.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} + 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": []} + 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] + entries = [] + for entry in axis["entries"]: + evidence = dict(entry, score=None, share=0, tasks=None, covered=0, runs=[], reason="not run", available=True) + bench = benchmarks_by.get((entry["benchmark"], entry["version"])) + part = next((c["label"] for c in scopes.choices(bench) if c["id"] == entry["dataset"]), entry["dataset"]) if bench else entry["dataset"] + # one benchmark feeds an axis through several datasets and metrics: each names its own + label = bench["label"] if bench else entry["benchmark"] + evidence["name"] = " · ".join(filter(None, (label, part if part != label else "", + entry["metric"] if entry["metric"] != "Score" else ""))) + evidence["available"] = bench is not None + if bench is None: + evidence["reason"] = "Benchmark version unavailable" + else: + manifests, normalized, dataset, sizes = scopes.select(bench, entry["dataset"], runs) + got = scoring.contribution(normalized, benchmark=entry["benchmark"], version=entry["version"], datasets=manifests, + dataset=dataset, sizes=sizes, 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 + row["axes"][name] = {"score": score, "weight": axis["weight"], "share": 0, "entries": entries} + # each family has its own Overall; an axis's share is its share of its family's + row["families"] = {} + for family, names in configuration.FAMILIES.items(): + overall, shares = weights.combine((row["axes"][n]["score"], row["axes"][n]["weight"]) for n in names) + for n, share in zip(names, shares): + row["axes"][n]["share"] = share + row["families"][family] = {"overall": overall, "rank": None} + row["overall"] = row["families"]["capabilities"]["overall"] + 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] + mean = sum(values) / len(values) if values else None + row["metrics"][metric] = {"value": mean if mean is None or isfinite(mean) 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 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(): + for entry in row["axes"][name]["entries"]: + if _entry_key(entry) not in entries: + continue + reason = (f"{entry['name']}: {entry['reason']}" if entry["score"] is None and entry["runs"] else + 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) + for family in configuration.FAMILIES: + ranks = weights.competition(rows, lambda r: r["families"][family]["overall"]) + for row in rows: + row["families"][family]["rank"] = ranks.get(row["key"]) + 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, + "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/cli.py b/app/nullius/leaderboard/cli.py new file mode 100644 index 000000000..22ddff045 --- /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 catalogue rows without recorded-run measurements") + parser.add_argument("--json", action="store_true", help="full precision scores, identity, evidence, ranks/coverage notes and observed metric counts") + 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(service.qualified(parse.load_all(args.roots)), workspace_open=bool(args.roots), 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'])}") + domains = row["families"]["domains"] + print(f" Domains overall: {weights.percent(domains['overall'])}" + (f" · rank {domains['rank']}" if domains["rank"] else "")) + 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.get('version_label') or entry['version'] or 'Official'}" + reading = weights.percent(entry["score"]) if entry["score"] is not None else entry["reason"] + 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} · weight {entry['weight']:g} · share {weights.percent(entry['share'])}{tasks}{runs}") + for reason in row["reasons"]: + print(f" Partial: {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/configuration.py b/app/nullius/leaderboard/configuration.py new file mode 100644 index 000000000..54d6adac1 --- /dev/null +++ b/app/nullius/leaderboard/configuration.py @@ -0,0 +1,188 @@ +"""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 +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") +AXES = CAPABILITIES + DOMAINS +# Each family has its own Overall: the capabilities' weights, and the domains' (equal) weights. +FAMILIES = {"capabilities": CAPABILITIES, "domains": DOMAINS} +OVERALL = (.12, .12, .08, .15, .15, .10, .08, .20) + (.14,) * len(DOMAINS) +SCHEMA = 2 +# Each axis's benchmarks, from what their tasks were counted to need: a direct +# entry weighs 1, a partial one 0.5. A whole-benchmark flag over several disjoint +# datasets is shared out among them. +DIRECT, PARTIAL = 1, .5 +TAU = ("airline", "retail", "telecom", "banking_knowledge") +VITA = ("cross", "delivery", "instore", "ota") +CLAW = ("general", "multimodal", "multi_turn") +DEFAULT_ENTRIES = { + "Safety": [("tau3-bench", "retail", "Score", DIRECT), ("tau3-bench", "airline", "Score", PARTIAL), + ("tau3-bench", "banking_knowledge", "Score", PARTIAL), ("osworld1", "test_infeasible", "Score", PARTIAL), + ("osworld2", "test_v2", "Score", PARTIAL)] + + [("claw-eval", d, "Score", DIRECT / len(CLAW)) for d in CLAW], + "Consistency": [("tau3-bench", d, "pass^3", PARTIAL / len(TAU)) for d in TAU] + + [("vitabench", d, "pass^3", PARTIAL / len(VITA)) for d in VITA] + + [("claw-eval", d, "pass^3", PARTIAL / len(CLAW)) for d in CLAW], + "Personalization": [("mypcbench", "final", "Score", DIRECT)] + + [("vitabench", d, "Score", PARTIAL / len(VITA)) for d in VITA], + "Retrieval": [("gaia", "gaia-validation", "Score", DIRECT), ("tau3-bench", "banking_knowledge", "Score", DIRECT), + ("osworld2", "test_v2", "Score", PARTIAL), ("mypcbench", "final", "Score", DIRECT), + ("claw-eval", "general", "Score", PARTIAL / 2), ("claw-eval", "multimodal", "Score", PARTIAL / 2), + ("medagentbench", "v2", "Score", PARTIAL), ("healthagentbench", "full", "Score", PARTIAL)], + "Communication": [("tau3-bench", d, "Score", DIRECT / len(TAU)) for d in TAU] + + [("vitabench", d, "Score", DIRECT / len(VITA)) for d in VITA] + + [("claw-eval", "multi_turn", "Score", DIRECT), ("mypcbench", "final", "Score", PARTIAL)], + "Execution": [("osworld1", "test_nogdrive", "Score", DIRECT), ("osworld2", "test_v2", "Score", DIRECT), + ("swe-bench-verified", "verified", "Score", DIRECT), ("terminal-bench", "full", "Score", DIRECT), + ("gaia", "gaia-validation", "Score", PARTIAL), ("gsm8k", "test", "Score", PARTIAL), + ("humaneval", "humaneval", "Score", PARTIAL), ("mypcbench", "final", "Score", DIRECT), + ("costbench", "test", "Score", DIRECT), ("clawmark", "all", "Score", DIRECT), + ("medagentbench", "v2", "Score", DIRECT), ("healthagentbench", "full", "Score", DIRECT)] + + [("tau3-bench", d, "Score", DIRECT / len(TAU)) for d in TAU] + + [("vitabench", d, "Score", DIRECT / len(VITA)) for d in VITA] + + [("claw-eval", d, "Score", DIRECT / len(CLAW)) for d in CLAW], + "Travel": [("tau3-bench", "airline", "Score", DIRECT), ("vitabench", "ota", "Score", DIRECT), + ("vitabench", "cross", "Score", PARTIAL), ("costbench", "test", "Score", DIRECT)], + "Dining": [("vitabench", "delivery", "Score", DIRECT / 2), ("vitabench", "instore", "Score", DIRECT / 2), + ("vitabench", "cross", "Score", PARTIAL)], + "Shopping": [("tau3-bench", "retail", "Score", DIRECT), ("vitabench", "instore", "Score", PARTIAL), + ("clawmark", "ecommerce", "Score", PARTIAL)], + "Money": [("tau3-bench", "banking_knowledge", "Score", DIRECT), ("osworld2", "websites35", "Score", PARTIAL), + ("clawmark", "insurance", "Score", PARTIAL / 2), ("clawmark", "investment_analyst", "Score", PARTIAL / 2)], + "Health": [("medagentbench", "v2", "Score", DIRECT), ("healthagentbench", "full", "Score", DIRECT), + ("clawmark", "clinical_assistant", "Score", PARTIAL)], + "Work": [("swe-bench-verified", "verified", "Score", DIRECT), ("terminal-bench", "full", "Score", DIRECT), + ("osworld2", "test_v2", "Score", DIRECT), ("osworld1", "test_nogdrive", "Score", PARTIAL), + ("humaneval", "humaneval", "Score", PARTIAL), ("open-telco", "teleqna-lite", "Score", PARTIAL), + ("clawmark", "all", "Score", DIRECT), ("mypcbench", "final", "Score", PARTIAL), + ("claw-eval", "general", "Score", PARTIAL)], +} + + +def location(): + return Path(paths.config_dir()) / "scoring.json" + + +def defaults(benchmarks): + defaults_of = {b["key"]: b for b in benchmarks if b.get("_version") == b.get("_default")} + versions = {k: definitions.version_identity(b) for k, b in defaults_of.items()} + declared = lambda key, dataset: not dataset or dataset in {c["id"] for c in scopes.choices(defaults_of[key])} + axes = {axis: {"weight": weight, "entries": [ + {"benchmark": key, "dataset": dataset, "version": versions[key], "metric": metric, "weight": weight} + for key, dataset, metric, weight in DEFAULT_ENTRIES.get(axis, []) + if key in versions and declared(key, dataset)]} for axis, weight in zip(AXES, OVERALL)} + for names in FAMILIES.values(): + _zero_empty(axes, names) + return {"schema": SCHEMA, "axes": axes} + + +def _zero_empty(axes, names): + """An axis with no benchmark weighs nothing in its family's Overall, unless none of the family has one.""" + if any(axes[n]["entries"] for n in names): + for n in names: + if not axes[n]["entries"]: + axes[n]["weight"] = 0 + + +def _number(value, label, upper=None): + try: + bad = 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) + except OverflowError: # an integer no float can hold + bad = True + if bad: + 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, *, previous=None, allow_unavailable=False): + """Validate every field before a write; preserve removed catalogue references.""" + if not isinstance(document, dict) or set(document) != {"schema", "axes"} or document["schema"] != SCHEMA: + raise ValueError("Invalid scoring document") + doc = copy.deepcopy(document) + if not isinstance(doc["axes"], dict) or set(doc["axes"]) != set(AXES): + raise ValueError("Scoring requires all fifteen axes") + 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") + _number(axis["weight"], name) + seen, read = set(), 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 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 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") + # a benchmark with one dataset is that dataset: a write takes it whole or by its dataset, never both + only = bench.get("datasets", []) if bench is not None and not bench.get("task_parts") else [] + same = (entry["benchmark"], entry["dataset"] or (only[0]["id"] if len(only) == 1 else ""), entry["version"], entry["metric"]) + if identity in seen or (not allow_unavailable and same in read): + raise ValueError(f"{name}: duplicate entry") + seen.add(identity) + read.add(same) + for names in FAMILIES.values(): + _zero_empty(doc["axes"], names) # a row with no benchmark weighs nothing + if not any(axis["weight"] > 0 for axis in doc["axes"].values()): + raise ValueError("At least one Weight in Overall must be positive") + if not allow_unavailable: + # each family has its own Overall: a write leaves none of them without a weighted row that has a benchmark + for family, names in FAMILIES.items(): + mapped = [n for n in names if doc["axes"][n]["entries"]] + if mapped and not any(doc["axes"][n]["weight"] > 0 for n in mapped): + raise ValueError(f"{family.capitalize()}: at least one row with a benchmark needs a weight above 0") + return doc + + +def _upgrade(document): + """A file saved before schema 2: its custom benchmarks and their rows are dropped, and its domains, which then + weighed nothing, take the default domain weight when they have a benchmark. The rest is kept.""" + if not isinstance(document, dict) or document.get("schema") != 1 or not isinstance(document.get("axes"), dict): + return document + document = {k: v for k, v in document.items() if k != "custom"} | {"schema": SCHEMA} + for axis in document["axes"].values(): + if isinstance(axis, dict) and isinstance(axis.get("entries"), list): + axis["entries"] = [e for e in axis["entries"] if not (isinstance(e, dict) and "custom" in e)] + axes = document["axes"] + if all(isinstance(axes.get(n), dict) and isinstance(axes[n].get("entries"), list) and not axes[n].get("weight") for n in DOMAINS): + for name, weight in zip(AXES, OVERALL): + if name in DOMAINS: + axes[name]["weight"] = weight + _zero_empty(axes, DOMAINS) + return document + + +def load(path, benchmarks): + try: + return validate(_upgrade(json.loads(Path(path).read_text())), benchmarks, allow_unavailable=True), "" + except FileNotFoundError: + return defaults(benchmarks), "" + except (OSError, ValueError, TypeError, RecursionError): + return defaults(benchmarks), "Scoring settings could not be read; defaults are active." + + +def save(path, 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) + return doc diff --git a/app/nullius/leaderboard/metrics.py b/app/nullius/leaderboard/metrics.py new file mode 100644 index 000000000..ff0092e60 --- /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 Exception: # a file of any shape: its counts are unavailable + 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/scopes.py b/app/nullius/leaderboard/scopes.py new file mode 100644 index 000000000..81e608434 --- /dev/null +++ b/app/nullius/leaderboard/scopes.py @@ -0,0 +1,29 @@ +"""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): + """The manifests, the runs read as the entry's datasets, the dataset and each dataset's declared size.""" + manifests = {d["id"]: d.get("tasks") if isinstance(d.get("tasks"), dict) else None + for d in benchmark.get("datasets", [])} + sizes = {d["id"]: d["units"] for d in benchmark.get("datasets", []) + if isinstance(d.get("units"), int) and not isinstance(d.get("units"), bool) and d["units"] > 0} + 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"]) + # a run records a task as /; a part's prefixes are the unit's + own = benchmark["key"] + "/" + matches = lambda name: (name[len(own):] if name.startswith(own) else 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, sizes = "", {} + return manifests, normalized, dataset, sizes diff --git a/app/nullius/leaderboard/scoring.py b/app/nullius/leaderboard/scoring.py new file mode 100644 index 000000000..55a84e7bd --- /dev/null +++ b/app/nullius/leaderboard/scoring.py @@ -0,0 +1,151 @@ +"""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, verified=False): + """One task's score. ``verified``: its run passed or failed something, so an attempt that ran and ended with no + verdict is a miss, as the run's adjusted rate counts it.""" + ran = attempts.ran(ts) + if not graded: + grouped = attempts.Attempts(tuple(ts)) + if grouped.has_verdicts: + return grouped.rate + return 0 if verified and ran and all(t.outcome == classify.UNKNOWN for t in ran) 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, sizes: Mapping[str, int] | None = None) -> 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; without a manifest its declared size (``sizes``) +is its total, its tasks told apart by recorded name. 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()) + if all(m is not None for m in manifests): + total = len({canonical for manifest in manifests for canonical in manifest.values()}) + else: + total = (sizes or {}).get(next(iter(scope))) if len(scope) == 1 else None + pool = [j for j in jobs if eligible(j) and j.dataset in scope + and j.identity.get("benchmark") == benchmark + 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 = {} + precedence = lambda j: _precedence(j, scope[j.dataset]) + order = precedence + if metric == "pass^3": + # a run that recorded one attempt per task cannot supply pass^3: one that can comes first, whatever it scored + supplies = lambda j: ((attempts.for_tasks(_groups(j, scope[j.dataset]).values()) or {}).get("hat") or {}).get(3) is not None + order = lambda j: (not supplies(j),) + precedence(j) + for j in sorted(pool, key=order): + selected.setdefault(j.dataset, j) + ids = tuple(j.job_id for j in selected.values()) + if not selected: + 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 = {} + 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()) + if total is not None and len(tasks) > total: + # more names than the dataset declares: the names are not its tasks + total = None + 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: + by_run = {} + for run_id, _, ts in tasks: + by_run.setdefault(run_id, []).extend(ts) + verified = {run_id: attempts.has_verdict(ts) for run_id, ts in by_run.items()} + scores = [_score(ts, graded, verified[run_id]) for run_id, _, ts in tasks] + 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/service.py b/app/nullius/leaderboard/service.py new file mode 100644 index 000000000..4fc1b5ea1 --- /dev/null +++ b/app/nullius/leaderboard/service.py @@ -0,0 +1,71 @@ +"""Catalogue and profile inputs shared by the Leaderboard page and command.""" +from __future__ import annotations + +import hashlib +import json +import os +from collections import Counter +from dataclasses import replace +from urllib.parse import quote + +from nullius.standard.contract import definitions +from . import board, configuration, metrics, weights, scopes + + +def catalogue(): + return definitions.load("agent", every=True)[0], definitions.load("benchmark", every=True)[0] + + +def revision(): + try: + raw = configuration.location().read_bytes() + except OSError: # missing, unreadable, or not a file + raw = b"" + return hashlib.sha256(raw).hexdigest() + + +def qualified(jobs): + """The jobs of several roots, those that share a name told apart by the folder that holds each.""" + names = Counter(j.job_id for j in jobs) + def under(job, name): + return os.path.join(os.path.dirname(os.path.abspath(job.dir)), name) if names[name] > 1 else name + return [replace(j, job_id=under(j, j.job_id), merged_from=[under(j, s) for s in j.merged_from]) for j in jobs] + + +def options(benchmarks): + 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), "default": b.get("_version") == b.get("_default")} + for b in benchmarks] + + +def document(jobs, *, workspace="", workspace_open=False, deferred=False): + agents, benchmarks = catalogue() + settings, warning = configuration.load(configuration.location(), benchmarks) + sources = {} + result = board.build(jobs, agents, benchmarks, settings, workspace_open=workspace_open, metric_sources=sources) + context = {"workspace": workspace, "settings": settings, + "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() + # a version to compare with is one that changes something: another than the one every entry of its benchmark reads + mapped = {} + for axis in settings["axes"].values(): + for entry in axis["entries"]: + mapped.setdefault(entry.get("benchmark"), set()).add(entry.get("version")) + 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 mapped.get(b["key"], set()) - {definitions.version_identity(b)}] + labels = {(b["key"], definitions.version_identity(b)): definitions.version_label(b) or definitions.version_identity(b)[:7] + for b in benchmarks} + for row in result["rows"]: + for axis in row["axes"].values(): + for entry in axis["entries"]: + # a reader names a version by its release or short commit, never the whole pin + entry["version_label"] = labels.get((entry["benchmark"], entry["version"]), entry["version"][:7]) + # a run told apart by its folder (qualified) is still opened by its name + entry["links"] = [{"id": id, "url": "/job/" + quote(os.path.basename(id) if os.path.isabs(id) else id, safe="") + + ("?workspace=" + quote(workspace, safe="") if workspace else "")} for id in entry["runs"]] + if deferred: + metrics.CACHE.complete(result, sources) + return result diff --git a/app/nullius/leaderboard/weights.py b/app/nullius/leaderboard/weights.py new file mode 100644 index 000000000..cea728fab --- /dev/null +++ b/app/nullius/leaderboard/weights.py @@ -0,0 +1,49 @@ +"""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 level(value): + """A score as ranks and orders compare it: two means that differ only in their last bits, by the order they + were summed in, are the same score.""" + return round(value, 12) if isinstance(value, float) else value + + +def competition(rows, value): + """Competition ranks (1, 1, 3) by a value, compared as ``level`` reads it; a row without one has no rank.""" + eligible = sorted((r for r in rows if value(r) is not None), key=lambda r: (-level(value(r)), r["name"], r["key"])) + ranks, previous, assigned = {}, None, None + for i, row in enumerate(eligible, 1): + if level(value(row)) != previous: + assigned = i + ranks[row["key"]], previous = assigned, level(value(row)) + return ranks + + +def rank(rows, sort="overall", descending=True): + """Rank every row with an Overall from full precision; incomplete coverage stays a note, never a gate.""" + rows = [dict(row, rank=None) for row in rows] + ranks = competition(rows, lambda r: r["overall"]) + for row in rows: + row["rank"] = ranks.get(row["key"]) + eligible = [r for r in rows if r["overall"] is not None] + groups = [eligible, [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: level(r[sort]), reverse=descending) + absent) + return result diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 139da6433..51e1c3bdb 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -32,7 +32,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "21" +SCHEMA = "22" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — @@ -1103,7 +1103,7 @@ def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict: """What tells a Nullius standard run from another, from its ``config.json`` (``cfg``) and its ``result.json`` (``res``): the benchmark, its version and options; the agent as the run named it, the version its trials report - (``agent_version``) and its options, defaults included; the model; the + (``agent_version``) and its options, defaults included; the backend its units ran on; the model; the provider; the serving providers pinned by model (``served_by``) and who served (``served``); and the limits in force: time limits by phase, turns, model calls, attempts of each unit, retries, units at a time, and the @@ -1120,7 +1120,7 @@ def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict: out = {"benchmark": word(std.get("benchmark")), "benchmark_version": word(std.get("benchmark_version")), "benchmark_options": _options(std.get("benchmark_options")), "agent": word(std.get("plugged")), "agent_version": word(agent_version), - "agent_options": _options(std.get("options")), "model": word(first.get("model_name"))} + "agent_options": _options(std.get("options")), "backend": word(std.get("backend")), "model": word(first.get("model_name"))} # a control asks no model unless it has a judge or a simulated user; the provider it records is then a default asks = out["model"] or std.get("judge") or std.get("simulator") or std.get("kind") != "control" out["provider"] = word(std.get("provider")) if asks else "" diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 82486ed18..dcce5e880 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -169,7 +169,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. @@ -259,6 +259,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 origin_of(d: dict) -> str: """Where a resolved version comes from (``catalog.ORIGINS``): what its ``upstream.origin`` says, else ``experiment`` when its upstream lists ``fixes``, else its entry's (a benchmark's ``benchmark.json``), else official.""" @@ -266,7 +271,6 @@ def origin_of(d: dict) -> str: return up.get("origin") or ("experiment" if up.get("fixes") else d.get("_origin") or "official") - def fix_parts(fix: str) -> Tuple[str, str, str, str]: """A version's fix as (before, words, url, after): ``WORDS (https://...)`` makes its last few words a link to that address; a fix without one is all ``before``.""" @@ -1591,6 +1595,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: @@ -1599,6 +1605,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 ab4ad58f1..b9d449ad1 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/packaging/verify.py b/app/packaging/verify.py index 8df534328..49f6ab86f 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 35fd9b58d..d4210226a 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 000000000..0354755a2 --- /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 e1dda87d2..8c4b41d4f 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 000000000..b3342de03 Binary files /dev/null and b/app/static/catalogue/agents/swe-agent.ico differ diff --git a/app/static/leaderboard/board.js b/app/static/leaderboard/board.js new file mode 100644 index 000000000..17dae6dcb --- /dev/null +++ b/app/static/leaderboard/board.js @@ -0,0 +1,560 @@ +/* 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, returningFocus = false, tableMotion = null; + const motion=window.LeaderboardMotion; + const percent = v => v == null ? '–' : `${Number((v * 100).toFixed(1))}%`; + const whole = v => v == null ? '–' : `${Math.round(v * 100)}%`; + /* a time is rounded to the second before it is split, so 119.6 s reads 2m 00s */ + const minutes = s => { const t=Math.round(s); return `${Math.floor(t/60)}m ${String(t%60).padStart(2,'0')}s`; }; + /* a cost keeps two figures below ten cents, so $0.0042 and $0.0078 read apart */ + const cost = v => v >= .1 || v === 0 ? `$${v.toFixed(2)}` : v < .0001 ? '<$0.0001' : `$${v.toPrecision(2)}`; + const measure = (field,v) => v == null ? '–' : field==='cost' ? cost(v) : field==='time' ? minutes(v) : String(Math.round(v)); + /* a score as a column sorts it: two means that differ only in their last bits are the same score */ + const level = v => v == null ? '' : Number(v.toFixed(12)); + 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); + /* the charts, the card and the pickers show who is on the board: an agent filtered out of the table leaves them too */ + let onTable = null; + const shown = r => !onTable || onTable.has(r.key); + /* the average is the server's own mean, taken over the agents on the board */ + const fieldAverage = axis => { const v=data.rows.filter(shown).map(r=>r.axes[axis]?.score).filter(x=>x!=null); return v.length?v.reduce((a,b)=>a+b,0)/v.length:null; }; + const scored = () => data.rows.filter(r => r.overall != null && shown(r)); + /* a name says only as much as tells two rows apart: the version when an agent has several, the model when a version has several */ + /* what tells a row from the others of its agent and version: the parts of its setup that differ among them */ + const part = v => v == null ? '' : typeof v === 'object' ? Object.entries(v).map(([k,x])=>`${k} ${typeof x === 'object' ? JSON.stringify(x) : x}`).join(' ') : String(v); + const setup = r => { const twins=data.rows.filter(v=>v.agent===r.agent&&v.version===r.version); + return twins.length>1 ? ['model','effort','provider','backend','options','limits'].filter(k=>new Set(twins.map(v=>part(v.identity[k]))).size>1).map(k=>part(r.identity[k])).filter(Boolean).join(' ') : ''; }; + const label = r => [r.name, new Set(data.rows.filter(v=>v.agent===r.agent).map(v=>v.version)).size>1 ? r.version_label : '', setup(r)].filter(Boolean).join(' '); + const compared = axis => versus === 'average' ? fieldAverage(axis) : versus.startsWith('version:') ? projection?.rows.find(r=>r.key===selected)?.axes[axis]?.score : row(versus)?.axes[axis]?.score; + const versionKey = v => 'version:'+JSON.stringify([v.benchmark,v.version]); + const comparedName = () => versus === 'average' ? null : versus.startsWith('version:') ? (data.versions.find(v=>versionKey(v)===versus)?.label || 'benchmark version') : row(versus) ? label(row(versus)) : null; + /* a difference that rounds to nothing is 0.0, neither up nor down */ + const signed = v => { const n=Math.abs(v*100).toFixed(1); return Number(n) ? `${v < 0 ? '−' : '+'}${n}` : '0.0'; }; + const pop = document.getElementById('lb-evidence'); + let shownFor = null; + function dismiss() { pop.hidden = true; } + /* an open card stays true to the page: its score may have been drawn again, changed or hidden */ + function settle() { + if (pop.hidden) return; + let target=focusBefore; + if (!target?.isConnected && shownFor?.row) target=table.querySelector(`tr[data-key="${CSS.escape(shownFor.row)}"] [data-axis="${CSS.escape(shownFor.axis)}"]`); + if (!target?.isConnected || !target.getClientRects().length) { pinned=false; dismiss(); return; } + if (pop.contains(document.activeElement)) { focusBefore=target; place(target); } // a link in use keeps the focus + else evidence(target); + } + function evidence(target) { + const current = row(target.closest('tr')?.dataset.key || selected); if (!current) return; + const axisName = target.dataset.axis; if (!axisName) return; + shownFor = {row: target.closest('tr')?.dataset.key || '', axis: axisName}; + /* a score's evidence: what it is made of, each part's share, score and what it adds, and the total */ + const shareOf=v=>v==null?'–':v.toFixed(2), adds=(score,share)=>score==null||!share?'–':(score*share*100).toFixed(1); + const scoreCell=(score,reason)=>{const td=element('td',null,{class:'lb-ev-score'}),box=element('span',null,{class:'lb-ev-scorebox'});td.append(box);if(score==null){box.append(element('span',reason||'not run',{class:'muted'}));return td;}const bar=element('span',null,{class:'lb-ev-bar'}),fill=element('i');fill.style.width=`${score*100}%`;bar.append(fill);box.append(bar,element('span',whole(score),{class:'lb-ev-pct'}));return td;}; + const table=element('table',null,{class:'lb-ev-table'}), head=element('tr'), body=element('tbody'); + [axisName==='Overall'?(family==='domains'?'Domain':'Capability'):'Benchmark · dataset','Weight','Score','Adds'].forEach(t=>head.append(element('th',t))); + const thead=element('thead');thead.append(head);table.append(thead,body); + const line=(label,sub,share,score,reason)=>{const tr=element('tr'),name=element('td');name.append(...label);if(sub.length){const small=element('small');small.append(...sub);name.append(small);}tr.append(name,element('td',shareOf(share),{class:'lb-ev-num'}),scoreCell(score,reason),element('td',adds(score,share),{class:'lb-ev-num'}));body.append(tr);}; + const total=(label,score,share)=>{const foot=element('tfoot'),tr=element('tr');tr.append(element('td',label),element('td',shareOf(share),{class:'lb-ev-num'}),element('td',score==null?'–':percent(score),{class:'lb-ev-num'}),element('td'));foot.append(tr);table.append(foot);}; + const field=axisName==='Overall'?null:fieldAverage(axisName); + pop.replaceChildren(element('strong', `${axisName} · ${label(current)}`)); + if (axisName === 'Overall') { + pop.append(element('p',`Overall is the weighted mean of the ${family} measured`)); + const parts=data[family].map(name=>[name,current.axes[name]]).filter(([,a]) => a.weight > 0); + parts.forEach(([name,a]) => line([name],[],a.share,a.score,'not measured')); + total('Overall',current.overall,parts.reduce((n,[,a])=>n+(a.share||0),0)); + } else { + const axis = current.axes[axisName]; + pop.append(element('p',`${axisName} is the weighted mean of its benchmarks run${field!=null?` · field average ${whole(field)}`:''}`)); + if (!axis.entries.length) pop.append(element('p','No benchmark')); + else { + axis.entries.forEach(e => { + const [bench,...slice]=e.name.split(' · '), label=[e.note?element('span',bench,{title:e.note}):bench];if(slice.length)label.push(element('span',` · ${slice.join(' · ')}${e.metric&&e.metric!=='Score'?' · '+e.metric:''}`,{class:'muted'})); + const sub=[]; + if(e.version)sub.push(e.version_label||e.version); + if(e.tasks!=null)sub.push(`${e.covered} of ${e.tasks} tasks`); + const small=[sub.join(' · ')]; + (e.links||[]).forEach((link,i,all)=>small.push(' · ',element('a',all.length>1?`Open run ${i+1}`:'Open run',{href:link.url,title:link.id}))); + line(label,small,e.share,e.score,e.reason); + }); + total(axisName,axis.score,axis.entries.reduce((n,e)=>n+(e.share||0),0)); + } + } + if(body.children.length)pop.append(table); + focusBefore = target; pop.hidden = false; place(target); + } + /* the card never covers what it explains: a radar's whole chart, beside it, else the score itself: below it, else + above, else beside it; only a window too small for any overlaps */ + function place(target) { + pop.style.maxHeight=''; + const box = target.getBoundingClientRect(), w=pop.offsetWidth, h=pop.offsetHeight, gap=8, edge=12; + const clamp=(v,lo,hi)=>Math.max(lo,Math.min(v,hi)); + const chart=target.closest('[data-chart^="radars-"]')?.querySelector('svg')?.getBoundingClientRect(); + if (chart) { + const top=clamp(box.top+box.height/2-h/2,edge,innerHeight-h-edge); + const side=innerWidth-chart.right-gap-edge>=w?chart.right+gap:chart.left-gap-edge>=w?chart.left-gap-w:null; + if (side!=null) {pop.style.left=`${side}px`;pop.style.top=`${top}px`;return;} + } + let left=clamp(box.left,edge,innerWidth-w-edge), top; + if (innerHeight-box.bottom-gap-edge>=h) top=box.bottom+gap; + else if (box.top-gap-edge>=h) top=box.top-gap-h; + else { + top=clamp(box.top+box.height/2-h/2,edge,innerHeight-h-edge); + if (innerWidth-box.right-gap-edge>=w) left=box.right+gap; + else if (box.left-gap-edge>=w) left=box.left-gap-w; + else { + /* no room beside either: the larger of the room below and above, the card scrolling inside it */ + const below=innerHeight-box.bottom-gap-edge, above=box.top-gap-edge, room=Math.max(below,above); + if (room>=140) { pop.style.maxHeight=`${room}px`; top=below>=above ? box.bottom+gap : box.top-gap-room; } + else top=clamp(box.bottom+gap,edge,innerHeight-h-edge); + } + } + pop.style.left=`${left}px`;pop.style.top=`${top}px`; + } + const back = () => { returningFocus=true; focusBefore?.focus(); returningFocus=false; }; + /* Escape closes an open card; focus returns to its score only when it was inside the card */ + document.addEventListener('keydown', e => { if (e.key !== 'Escape' || pop.hidden) return; const inside=pop.contains(document.activeElement); pinned=false; dismiss(); if (inside) back(); }); + /* Enter on a score goes into its card's links; Tab past the last of them goes on to what follows the score, Shift+Tab + before the first back to the score */ + document.addEventListener('keydown', e => { + if (pop.hidden || !focusBefore?.isConnected) return; + const links=[...pop.querySelectorAll('a[href]')], at=document.activeElement; if (!links.length) return; + if ((e.key==='Enter' || e.key===' ') && at===focusBefore) { e.preventDefault(); pinned=true; links[0].focus(); } + else if (e.key==='Tab' && e.shiftKey && at===links[0]) { e.preventDefault(); back(); } + else if (e.key==='Tab' && !e.shiftKey && at===links.at(-1)) back(); // not prevented: the browser's own Tab then leaves the score + }); + /* a strip's dot is a button: Enter and Space choose its agent, as a click does */ + document.addEventListener('keydown', e => { const dot=e.target.closest?.('.lb-track [data-select]'); if (dot && (e.key==='Enter' || e.key===' ')) { e.preventDefault(); choose(dot.dataset.select); if (dot.isConnected) dot.focus({preventScroll:true}); } }); + /* the card follows its score as the page scrolls or resizes, and closes once the score is out of sight */ + const track = e => { + if (pop.hidden || (e.target instanceof Node && pop.contains(e.target))) return; + const box=focusBefore?.isConnected ? focusBefore.getBoundingClientRect() : null, clip=focusBefore?.closest('.table-wrap')?.getBoundingClientRect(); + /* in the table a score is out of sight past the table's box, or behind the columns that stay pinned */ + const held=[...(focusBefore?.closest('tr')?.querySelectorAll('.sticky-col') || [])].filter(c=>!c.contains(focusBefore) && getComputedStyle(c).position==='sticky').map(c=>c.getBoundingClientRect().right); + const from=Math.max(clip ? clip.left : -Infinity, ...held); + if (!box || !box.width || box.bottom<0 || box.top>innerHeight || box.right<0 || box.left>innerWidth || box.left+box.width/2clip.right)) { pinned=false; dismiss(); } + else place(focusBefore); + }; + document.addEventListener('scroll', track, true); addEventListener('resize', track); + /* hovering shows a score's evidence while the pointer is on it or on the card; a click or keyboard focus keeps it open */ + let pinned=false; + document.addEventListener('pointerdown', e => { if (!pop.contains(e.target) && !e.target.closest('[data-axis]')) { pinned=false; dismiss(); } }); + /* the card closes once focus is on something that is neither a score nor the card */ + document.addEventListener('focusin', e => { const target=e.target.closest('[data-axis]'); if(target&&!returningFocus) { pinned=target.matches(':focus-visible'); evidence(target); } else if(!target&&!pop.hidden&&!pop.contains(e.target)) { pinned=false; dismiss(); } }); + let leaving=0; + document.addEventListener('pointerover', e => { const target=e.target.closest('[data-axis]'); if(target||pop.contains(e.target))clearTimeout(leaving); if(target&&!pinned) evidence(target); }); + document.addEventListener('pointerout', e => { if(pinned||pop.hidden)return; if(!e.target.closest('[data-axis]')&&!pop.contains(e.target))return; clearTimeout(leaving); leaving=setTimeout(()=>{if(!pinned)dismiss();},180); }); + document.addEventListener('click', e => { const target=e.target.closest('[data-axis]'); if(target) { pinned=true; 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}`,role:'img','aria-label':`Rank ${rank}, ${names[rank-1]}`}); + span.append(laurel(rank));return span; + } + /* a laurel medal: the rank on a struck disc inside a wreath of eight leaves; the 4th, chocolate, has a bite out of + its upper right and two crumbs. Its colours are its metal's own, the same in both themes. */ + const METAL={1:['#fff1b8','#e8c24a','#9a6b12','#4a3205'],2:['#ffffff','#dde3ea','#8f9aa6','#232a31'],3:['#ffd9b5','#d68a4c','#8a4a1c','#3a1d08'],4:['#a8714c','#6e4027','#3e2112','#f4dcc6']}; + let medals=0; + function laurel(rank) { + const [light,mid,dark,ink]=METAL[rank], id=`lb-medal-${++medals}`, plot=svg('svg',{'aria-hidden':'true',viewBox:'0 0 40 48'}), defs=svg('defs'); + const shade=svg('radialGradient',{id:id+'-disc',cx:'35%',cy:'30%',r:'80%'}); + [[0,light],[.55,mid],[1,dark]].forEach(([at,color])=>shade.append(svg('stop',{offset:at,'stop-color':color})));defs.append(shade); + const body=svg('g'); + if(rank===4){const mask=svg('mask',{id:id+'-bite'});mask.append(svg('rect',{x:-10,y:-10,width:60,height:68,fill:'#fff'}),svg('circle',{cx:31,cy:15,r:4}),svg('circle',{cx:34.6,cy:20,r:3.7}),svg('circle',{cx:26.8,cy:12,r:2.4}));defs.append(mask);body.setAttribute('mask',`url(#${id}-bite)`);} + for(const side of [-1,1])for(let i=0;i<4;i++){ + const deg=124+i*30,a=deg*Math.PI/180,x=20+Math.cos(a)*15.6,y=25+Math.sin(a)*15.6; + const leaf=svg('g',{transform:`translate(${(side<0?x:40-x).toFixed(1)} ${y.toFixed(1)}) rotate(${side<0?deg+110:-(deg+110)})`}); + const blade=svg('ellipse',{class:'lb-leaf',cx:0,cy:0,rx:2.9,ry:5.2,fill:i%2?mid:dark});blade.style.setProperty('--i',i);leaf.append(blade);body.append(leaf); + } + body.append(svg('circle',{class:'lb-disc',cx:20,cy:25,r:12,'stroke-width':1.4,fill:`url(#${id}-disc)`,stroke:dark})); + plot.append(defs,body,svg('path',{d:'M14 41l6-3 6 3',fill:'none',stroke:dark,'stroke-width':1.6,'stroke-linecap':'round'}),svg('text',{x:20,y:30.6,'text-anchor':'middle','font-size':16,'font-weight':800,fill:ink},rank)); + if(rank===4)plot.append(svg('circle',{cx:36,cy:26,r:1,fill:mid}),svg('circle',{cx:33.8,cy:29.4,r:.75,fill:mid})); + return plot; + } + /* a score's chip: one blue whose perceived lightness moves in even steps from 50% to 100%, so every point of + score is the same step of shade; at or below 50% it is the darkest */ + /* one colour per rate: below 60% a navy that deepens with the rate, from 60% one strong colour */ + const heat = v => Math.max(0,Math.min(1,v/.6)); + function chip(cell, value, axis) { + cell.replaceChildren(); + if (value == null) { cell.append(element('span','–',{class:'lb-none'})); return; } + /* lightness runs .30 to .80 in the dark theme and .90 to .42 in the light one; past .62 dark text reads best */ + const t=heat(value), ink=value>=.6?' lb-top':''; + const span=element('span',whole(value),{class:`lb-chip${ink}`,tabindex:'0','data-axis':axis}); + span.style.setProperty('--lb-t',t.toFixed(3));span.style.setProperty('--lb-t2',Math.max(0,(value-.6)/.4).toFixed(3));cell.append(span); + } + function overall(cell, r) { + cell.replaceChildren(); + if (r.overall == null) { cell.append(element('span','–',{class:'lb-none'})); return; } + cell.append(element('span',`${(r.overall*100).toFixed(1)}%`,{class:'lb-overall',tabindex:'0','data-axis':'Overall'})); + const bar=element('span',null,{class:'lb-bar'}),fill=element('i');fill.style.width=`${r.overall*100}%`;bar.append(fill);cell.append(bar); + } + /* the medals and ranks follow who is on the board: a filter or a search ranks the rows that pass among themselves */ + let onBoard=null; + const shownRank=r=>onBoard?onBoard.get(r.key)??null:r.rank; + table.addEventListener('table:drawn',e=>{ + const keys=new Set(e.detail.rows.map(tr=>tr.dataset.key)), ranked=data.rows.filter(r=>keys.has(r.key)&&r.rank).sort((a,b)=>a.rank-b.rank); + const next=new Map();let previous=null,at=0;ranked.forEach((r,i)=>{if(r.rank!==previous)at=i+1;next.set(r.key,at);previous=r.rank;}); + const moved=!onTable||keys.size!==onTable.size||[...keys].some(k=>!onTable.has(k));onTable=keys; + if(moved)follow(); + const changed=!onBoard||ranked.length!==onBoard.size||ranked.some(r=>onBoard.get(r.key)!==next.get(r.key)); + onBoard=next;if(!changed)return; + table.querySelectorAll('tbody tr').forEach(tr=>{const r=row(tr.dataset.key);if(!r)return;const cell=tr.querySelector('[data-col="rank"]');cell.replaceChildren(medal(shownRank(r)));cell.dataset.sort=shownRank(r)||'';}); + card(); + }); + function follow() { + const first=scored().sort((a,b)=>(a.rank??1e9)-(b.rank??1e9))[0]||data.rows.find(shown); + if(versus!=='average'&&!versus.startsWith('version:')&&row(versus)&&!shown(row(versus))){versus='average';document.querySelectorAll('[data-vs-select]').forEach(v=>setSelect(v,versus));} + if(row(selected)&&!shown(row(selected))&&first)choose(first.key);else draw(); + } + function updateTable() { + tableMotion?.capture(); + const focused=document.activeElement, focusAxis=focused?.dataset?.axis, focusRow=focused?.closest?.('tr')?.dataset.key; + 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.classList.toggle('lb-sel', r.key === selected); + tr.querySelector('[data-col="rank"]').replaceChildren(medal(shownRank(r))); + tr.querySelector('[data-col="rank"]').dataset.sort=shownRank(r) || ''; + tr.querySelector('[data-name]').textContent = [r.name,setup(r)].filter(Boolean).join(' · '); + tr.dataset.search = [r.name,setup(r),r.company,r.version_label].filter(Boolean).join(' '); + const o=tr.querySelector('[data-col="overall"]');overall(o,r);o.dataset.sort=level(r.overall); + data.axes.forEach(name=>{const cell=tr.querySelector(`[data-col="${name}"]`),a=r.axes[name];chip(cell,a.score,name);cell.dataset.sort=level(a.score);}); + for(const [field,m] of Object.entries(r.metrics)) { const cell=tr.querySelector(`[data-col="${field}"]`);cell.replaceChildren(element('span',measure(field,m.value),{class:'lb-m'}));cell.dataset.sort=m.value??'';cell.title=`${m.count} observed`; } + table.tBodies[0].append(tr); + }); + columns(); + table.dispatchEvent(new Event('table:update')); + applyFamily(); + const again=focusAxis&&focusRow?table.querySelector(`tr[data-key="${CSS.escape(focusRow)}"] [data-axis="${CSS.escape(focusAxis)}"]`):focused; + if(again?.isConnected&&document.activeElement!==again)again.focus({preventScroll:true}); + settle(); + } + const tools=document.getElementById(`${table.id}-tools`); + /* what the viewer chose for each score column, kept apart from the toolkit's list of the columns then shown */ + const choices=()=>{try{const kept=JSON.parse(localStorage.getItem(table.id+'.axes')||'{}');return kept&&typeof kept==='object'?kept:{};}catch{return {};}}; + /* a score column shows when an agent has a score in it, unless the viewer chose otherwise for that column: an + empty one stays out until it is ticked, and comes in by itself with its first score */ + function columns() { + const chosen=choices(); + data.axes.forEach(name=>{ + const cb=tools?.querySelector(`input[data-col="${name}"]`);if(!cb)return; + cb.checked=name in chosen?chosen[name]===true:data.averages[name].score!=null; + table.querySelectorAll(`[data-col="${name}"]`).forEach(cell=>cell.style.display=cb.checked?'':'none'); + }); + } + 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); }); + size(); + } + /* Columns lists the shown family's score columns; Sort by, the columns the table shows: a sort by a column that + leaves, with its family or unticked, goes with it */ + function menus() { + tools?.querySelectorAll('input[data-col]').forEach(box=>{if(data.axes.includes(box.dataset.col))box.closest('label').hidden=!data[family].includes(box.dataset.col);}); + const showing=new Set(shownHeads().map(th=>th.dataset.col)); + tools?.querySelectorAll('input[data-sort-col]').forEach(box=>{if(box.value)box.closest('label').hidden=!showing.has(box.value);}); + const sorted=table.tHead.querySelector('th[data-sorted]')?.dataset.col; + if(sorted&&!showing.has(sorted))unsort(); + } + /* rows in the shown family's ranking: the order Sort by's Default means */ + const ranking=()=>data.rows.forEach(r=>{const tr=[...table.tBodies[0].rows].find(t=>t.dataset.key===r.key);if(tr)table.tBodies[0].append(tr);}); + const unsort=()=>{const none=tools?.querySelector('input[data-sort-col][value=""]');if(none){none.checked=true;none.dispatchEvent(new Event('change',{bubbles:true}));}}; + tools?.addEventListener('change',e=>{if(e.target.matches('input[data-sort-col]')&&!e.target.value){ranking();table.dispatchEvent(new Event('table:update'));}}); + /* each shown column keeps room for its name; past the card's width the table scrolls */ + const heads=()=>[...table.tHead.rows[0].cells]; + const shownHeads=()=>heads().filter(th=>!th.hidden&&th.style.display!=='none'); + const ruler=document.createElement('canvas').getContext('2d'); + function columnWidth(th) { + /* on a phone #, Agent and Overall fill the card's width exactly: Agent takes what the two leave, tighter on a narrow + one, so Overall is whole at any width */ + const phone=innerWidth<=700, room=wrap?.clientWidth||296, tight=phone&&room<290, rank=phone?(tight?36:44):48, overall=phone?(tight?78:84):104; + const fixed={rank,agent:phone?Math.max(112,Math.min(168,room-rank-overall)):238,overall,steps:66,time:84,calls:92,cost:88}; + if(fixed[th.dataset.col])return fixed[th.dataset.col]; + /* a score column is as wide as its name, measured in the header's own font */ + const style=getComputedStyle(th);ruler.font=`${style.fontWeight} ${style.fontSize} ${style.fontFamily}`; + const name=th.textContent.trim(), spacing=parseFloat(style.letterSpacing)||0, text=ruler.measureText(name).width+spacing*name.length; + /* beside the centred name, room for the sort arrow the stylesheet draws after it: 1.05rem, .25rem away */ + const rem=parseFloat(getComputedStyle(document.documentElement).fontSize);ruler.font=`500 ${1.05*rem}px ${style.fontFamily}`; + const side=Math.max(parseFloat(style.paddingLeft),parseFloat(style.paddingRight),ruler.measureText('↓').width+.25*rem); + return Math.max(88,Math.ceil(text+2*side)+2); + } + /* the columns fill the card exactly: room to spare goes to the score columns alone, so #, Agent, Overall and the + measures keep their width whatever is shown */ + const wrap=table.closest('.table-wrap'); + function size(except=null) { + const shown=shownHeads().filter(th=>th.dataset.col!==except), axes=shown.filter(th=>data.axes.includes(th.dataset.col)); + const base=new Map(shown.map(th=>[th,columnWidth(th)])), total=[...base.values()].reduce((a,b)=>a+b,0); + const spare=Math.max(0,(wrap?.clientWidth||0)-total), each=axes.length?Math.floor(spare/axes.length):0; + shown.forEach(th=>{th.style.width=`${base.get(th)+(axes.includes(th)?each:0)}px`;}); + if(except)heads().find(th=>th.dataset.col===except).style.width='0px'; + table.style.minWidth=`${total+each*axes.length}px`; + if(!except)menus(); + } + if(wrap){let seen=wrap.clientWidth;new ResizeObserver(()=>{if(wrap.clientWidth&&Math.abs(wrap.clientWidth-seen)>1){seen=wrap.clientWidth;size();}}).observe(wrap);} + /* a column chosen in Columns grows from nothing and fades in; one taken away fades and narrows to nothing first */ + const cellsOf=col=>[...table.querySelectorAll(`td[data-col="${CSS.escape(col)}"]`)]; + let passing=false; + function grow(col) { + const th=heads().find(h=>h.dataset.col===col);if(!th||th.hidden)return size(); + const cells=[th,...cellsOf(col)]; + cells.forEach(c=>c.classList.add('lb-instant','lb-closing'));th.style.width='0px';table.classList.add('lb-instant');table.offsetWidth; + cells.forEach(c=>c.classList.remove('lb-instant','lb-closing'));table.classList.remove('lb-instant');size(); + cellsOf(col).forEach(c=>motion.contents(c,true,280)); + } + function shrink(box) { + const col=box.dataset.col,th=heads().find(h=>h.dataset.col===col); + const pass=()=>{passing=true;box.dispatchEvent(new Event('change',{bubbles:true}));passing=false;size();}; + if(!th||th.hidden||motion.reduced.matches){pass();return;} + const cells=[th,...cellsOf(col)]; + const fades=cells.flatMap(c=>{c.classList.add('lb-closing');return motion.contents(c,false,200);}); + size(col); + setTimeout(()=>{pass();cells.forEach(c=>c.classList.remove('lb-closing'));fades.forEach(a=>a.cancel());},290); + } + /* a select changed from here: its selected attribute moves too, which the page's own select button watches */ + function setSelect(s,value) { if(![...s.options].some(o=>o.value===value))return; [...s.options].forEach(o=>o.toggleAttribute('selected',o.value===value)); s.value=value; } + function choose(key) { + if(!row(key)) return; selected=key; + document.querySelectorAll('[data-agent-select]').forEach(s=>setSelect(s,key)); + table.querySelectorAll('tbody tr').forEach(tr=>tr.classList.toggle('lb-sel',tr.dataset.key===selected)); + /* chosen in a chart or a picker, an agent's row may be on another page: the table turns to it */ + const chosen=[...table.tBodies[0].rows].find(tr=>tr.dataset.key===key); + if(chosen?.hidden)table.dispatchEvent(new CustomEvent('table:show',{detail:{row:chosen}})); + draw(); + } + document.addEventListener('click',e=>{const target=e.target.closest('[data-select]');if(target){choose(target.dataset.select);return;}const tr=e.target.closest('#leaderboard-table tbody tr');if(tr&&!e.target.closest('a'))choose(tr.dataset.key);}); + 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',label(row(key)));node.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();choose(key);}});return node; } + + /* the efficiency scatter, on the mockup's 640 by 426 grid: Overall up, time or cost per task across */ + const PL={l:46,r:618,t:30,b:380}; + /* the scatter is drawn at its box's own width, so its text keeps its size at any width and only the plot grows */ + const scatterBox=document.getElementById('lb-scatter').parentElement; + const plotWidth=()=>Math.max(520,Math.round(scatterBox.clientWidth||640)); + function fit(values,steps,n,floor) { + let a=Math.min(...values),b=Math.max(...values);const pad=Math.max((b-a)*.12,steps[0]);a=Math.max(floor,a-pad);b=b+pad; + const q=steps.find(q=>(b-a)/q<=n)||steps.at(-1);return {step:q,lo:Math.max(floor,Math.floor(a/q+1e-9)*q),hi:Math.ceil(b/q-1e-9)*q}; + } + /* a name's width in the page's own font, the one the plot's text is drawn in */ + const textWidth=(t,weight=600)=>{ruler.font=`${weight} 12px ${getComputedStyle(document.body).fontFamily}`;return Math.ceil(ruler.measureText(t).width);}; + function drawScatter() { + const live=document.getElementById('lb-scatter'),plot=svg('svg'),W=plotWidth(); + PL.r=W-22;live.setAttribute('viewBox',`0 0 ${W} 426`); + const time=metric==='time', value=r=>r.metrics?.[metric]?.value, x=r=>time?value(r)/60:value(r); + const points=scored().filter(r=>value(r)!=null); + const defs=svg('defs'); + const better=svg('linearGradient',{id:'lb-better',x1:0,y1:0,x2:1,y2:1}),worse=svg('linearGradient',{id:'lb-worse',x1:1,y1:1,x2:0,y2:0}); + better.append(svg('stop',{offset:0,'stop-color':'var(--lb-good)','stop-opacity':.26}),svg('stop',{offset:.5,'stop-color':'var(--lb-good)','stop-opacity':0})); + worse.append(svg('stop',{offset:0,'stop-color':'var(--bad)','stop-opacity':.17}),svg('stop',{offset:.5,'stop-color':'var(--bad)','stop-opacity':0})); + const clip=svg('clipPath',{id:'lb-logo-clip',clipPathUnits:'objectBoundingBox'});clip.append(svg('rect',{width:1,height:1,rx:.26})); + defs.append(better,worse,clip);plot.append(defs); + const frame={x:PL.l,y:PL.t,width:PL.r-PL.l,height:PL.b-PL.t,rx:6}; + plot.append(svg('rect',{...frame,fill:'url(#lb-better)','data-node':'tint-a'}),svg('rect',{...frame,fill:'url(#lb-worse)','data-node':'tint-b'})); + if(!points.length){plot.append(svg('text',{x:(PL.l+PL.r)/2,y:(PL.t+PL.b)/2,'text-anchor':'middle'},`No ${time?'time':'cost'} recorded yet`));motion.morph(live,plot);return;} + const fx=fit(points.map(x),time?[.1,.2,.5,1,2,5,10,20,30,60]:[.001,.002,.005,.01,.02,.05,.1,.2,.5,1,2,5],7,0), fy=fit(points.map(r=>r.overall*100),[1,2,5,10,20],6,0); + fy.hi=Math.min(100,fy.hi); + /* the axes end a logo's half short of the frame, so a point at 0% or 100%, or at no time, stays whole inside it */ + const IN=17, X=v=>PL.l+IN+(v-fx.lo)/((fx.hi-fx.lo)||1)*(PL.r-PL.l-2*IN), Y=v=>PL.b-IN-(v*100-fy.lo)/((fy.hi-fy.lo)||1)*(PL.b-PL.t-2*IN); + const places=q=>q<.01?3:q<.1?2:q<1?1:0; + for(let i=0,v;(v=fy.lo+i*fy.step)<=fy.hi+1e-6;i++)plot.append(svg('line',{x1:PL.l,x2:PL.r,y1:Y(v/100),y2:Y(v/100),class:'lb-grid','data-node':'gy'+i}),svg('text',{x:PL.l-8,y:Y(v/100)+4,'text-anchor':'end','data-node':'ty'+i},`${v}%`)); + for(let i=0,v;(v=fx.lo+i*fx.step)<=fx.hi+1e-6;i++)plot.append(svg('line',{x1:X(v),x2:X(v),y1:PL.t,y2:PL.b,class:'lb-grid','data-node':'gx'+i}),svg('text',{x:X(v),y:PL.b+18,'text-anchor':'middle','data-node':'tx'+i},time?v.toFixed(places(fx.step)):'$'+v.toFixed(Math.max(1,places(fx.step))))); + plot.append(svg('text',{x:PL.l+10,y:PL.t+20,class:'lb-better','data-node':'better'},'BETTER'),svg('text',{x:PL.l-34,y:PL.t-14,'data-node':'ylabel'},'Overall'),svg('text',{x:(PL.l+PL.r)/2,y:PL.b+36,'text-anchor':'middle','data-node':'xlabel'},`${time?'Minutes':'Cost'} per task`)); + /* each name sits beside its own logo, on whichever side is free of other logos and names */ + const under=r=>[r.version_label,setup(r)].filter(Boolean).join(' · '); + const R=13, H=27, spots=points.map(r=>({r,x:X(x(r)),y:Y(r.overall)})), taken=spots.map(s=>({x:s.x-R,y:s.y-R,w:2*R,h:2*R})); + const clash=(a,b)=>a.x(a.r.key===selected)-(b.r.key===selected)); + const placed=new Map(); + [...spots].sort((a,b)=>a.y-b.y).forEach(s=>{ + const w=Math.max(textWidth(s.r.name),textWidth(under(s.r),400))+3; + const options=[{x:s.x+R+5,y:s.y-H/2,anchor:'start'},{x:s.x-R-5-w,y:s.y-H/2,anchor:'end'},{x:s.x-w/2,y:s.y-R-2-H,anchor:'middle'},{x:s.x-w/2,y:s.y+R+2,anchor:'middle'},{x:s.x+R+5,y:s.y-H,anchor:'start'},{x:s.x+R+5,y:s.y,anchor:'start'},{x:s.x-R-5-w,y:s.y-H,anchor:'end'},{x:s.x-R-5-w,y:s.y,anchor:'end'}] + .map(o=>({...o,w,h:H})).filter(o=>o.x>=PL.l+3&&o.x+w<=PL.r-3&&o.y>=PL.t+2&&o.y+H<=PL.b-2&&!(o.xMath.abs(t.x+R-s.x)<.01&&Math.abs(t.y+R-s.y)<.01); + const best=options.find(o=>!taken.some(t=>t!==own&&clash(o,t)))||options[0]||{x:s.x+R+5,y:s.y-H/2,anchor:'start',w,h:H}; + taken.push(best);placed.set(s.r.key,best); + }); + for(const s of ordered){ + const r=s.r,me=r.key===selected,box=placed.get(r.key),tx=box.anchor==='start'?box.x:box.anchor==='end'?box.x+box.w:box.x+box.w/2; + const group=selectable(svg('g',{'data-node':'point:'+r.key,class:`lb-dot${me?' lb-current':''}`}),r.key,s.x,s.y); + group.append(svg('title',{},`${label(r)} · ${percent(r.overall)} · ${measure(metric,value(r))}`)); + const logo=svg('g',{class:'lb-logo','data-node':'logo'}); + logo.append(svg('rect',{class:'lb-tile',x:s.x-R,y:s.y-R,width:2*R,height:2*R,rx:7,'data-node':'tile'})); + const mark=marks[r.key]; + if(mark?.includes('#')){const icon=svg('svg',{x:s.x-R+3,y:s.y-R+3,width:2*R-6,height:2*R-6,viewBox:'0 0 24 24','data-node':'icon'});icon.append(svg('use',{href:mark}));logo.append(icon);} + else if(mark)logo.append(svg('image',{href:mark,x:s.x-R,y:s.y-R,width:2*R,height:2*R,'clip-path':'url(#lb-logo-clip)','data-node':'image'})); + else logo.append(svg('text',{x:s.x,y:s.y+4,'text-anchor':'middle','data-node':'initial'},r.name.slice(0,1))); + logo.append(svg('rect',{class:'lb-edge',x:s.x-R,y:s.y-R,width:2*R,height:2*R,rx:7,'data-node':'edge'})); + group.append(logo,svg('text',{x:tx,y:box.y+12,'text-anchor':box.anchor,class:`lb-name${me?' lb-me':''}`,'data-node':'name'},r.name),svg('text',{x:tx,y:box.y+24.5,'text-anchor':box.anchor,class:'lb-version','data-node':'version'},under(r))); + plot.append(group); + } + motion.morph(live,plot); + } + function nearest(plot) { plot.addEventListener('click',e=>{if(e.target.closest('[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); } + nearest(document.getElementById('lb-scatter')); + let drawnWidth=0;new ResizeObserver(()=>{const W=plotWidth();if(W!==drawnWidth&&drawnWidth){drawnWidth=W;drawScatter();}else drawnWidth=W;}).observe(scatterBox); + + /* strips: every agent's dot on one line per axis; the chosen one larger, the average a dashed tick, the compared one a diamond */ + function strips(group) { + const container=document.querySelector(`[data-chart="strips-${group}"]`), current=row(selected); if(!current) return; + const other=versus!=='average'; + data[group].forEach((name,i)=>{ + let line=container.children[i]; + if(!line){line=element('div',null,{class:'lb-srow'});line.append(element('span',name,{class:'lb-axis-name',tabindex:'0','data-axis':name}),element('span',null,{class:'lb-track'}),element('span',null,{class:'lb-sval'}));container.append(line);} + const track=line.children[1], keep=new Map([...track.children].map(n=>[n.dataset.node,n])), want=[]; + const put=(id,tag,cls,left,attrs={})=>{let n=keep.get(id);if(!n||n.tagName.toLowerCase()!==tag){n=element(tag,null,{'data-node':id});n.style.left=`${left}%`;}keep.delete(id);n.className=cls;Object.entries(attrs).forEach(([k,v])=>n.setAttribute(k,v));requestAnimationFrame(()=>{n.style.left=`${left}%`;});want.push(n);}; + const average=fieldAverage(name); + if(average!=null)put('average','u','',average*100,{title:`Average ${whole(average)}`}); + data.rows.filter(r=>r.axes[name].score!=null&&r.key!==selected&&shown(r)).forEach(r=>put('r:'+r.key,'i','',r.axes[name].score*100,{role:'button',tabindex:'0','data-select':r.key,'aria-label':`${label(r)} ${whole(r.axes[name].score)}`,title:`${label(r)} ${whole(r.axes[name].score)}`})); + if(current.axes[name].score!=null)put('r:'+selected,'i','lb-me',current.axes[name].score*100,{role:'button',tabindex:'0','data-select':selected,'aria-label':`${label(current)} ${whole(current.axes[name].score)}`,title:`${label(current)} ${whole(current.axes[name].score)}`}); + const versusScore=compared(name); + if(other&&versusScore!=null)put('versus','em','',versusScore*100,{title:`${comparedName()} ${whole(versusScore)}`}); + keep.forEach(n=>n.remove());want.forEach(n=>track.append(n)); + const value=line.children[2];value.replaceChildren(document.createTextNode(whole(current.axes[name].score))); + if(other&&versusScore!=null)value.append(element('small',whole(versusScore))); + }); + } + /* radars: rings at half and whole, a spoke per axis, the chosen agent filled, the comparison dashed */ + function radar(group) { + const container=document.querySelector(`[data-chart="radars-${group}"]`), names=data[group], current=row(selected);if(!current)return; + const cx=200, cy=178, R=126, n=names.length, at=(i,v)=>{const a=-Math.PI/2+i*2*Math.PI/n;return [cx+Math.cos(a)*v*R,cy+Math.sin(a)*v*R];}; + const points=list=>list.map(p=>p.map(v=>v.toFixed(1)).join(',')).join(' '); + const plot=svg('svg',{viewBox:'-90 -34 552 424',role:'group','aria-label':`${group} profile`,'data-cx':cx,'data-cy':cy}); + for(const v of [.5,1])plot.append(svg('polygon',{points:points(names.map((_,i)=>at(i,v))),class:'lb-ring','data-node':'ring'+v})); + names.forEach((name,i)=>{ + /* a label's nearest edge sits the same gap from its corner whichever way it faces: above a corner it ends there, + below it starts there, beside it it is centred on it */ + const [ex,ey]=at(i,1),ux=(ex-cx)/R,uy=(ey-cy)/R,lx=ex+ux*30,anchor=ux<-.2?'end':ux>.2?'start':'middle'; + const block=36, top=ey+uy*30-(uy<-.3?block:uy>.3?0:block/2), ly=top+14+4; + plot.append(svg('line',{x1:cx,y1:cy,x2:ex,y2:ey,class:'lb-ring','data-node':'spoke'+i})); + const text=svg('text',{x:lx,y:ly-4,'text-anchor':anchor,tabindex:0,'data-axis':name,'data-node':'label:'+name,class:'lb-axis-label'}); + text.append(document.createTextNode(name),svg('tspan',{x:lx,dy:19,class:'lb-me'},whole(current.axes[name].score))); + const v=compared(name);if(versus!=='average'&&v!=null)text.append(svg('tspan',{dx:5,class:'lb-versus'},whole(v))); + const label=svg('g',{class:'lb-label','data-node':'pill:'+name});label.append(svg('rect',{class:'lb-pill',rx:8,'data-axis':name}),text);plot.append(label); + }); + const series=(value,comparison)=>names.forEach((name,i)=>{ + const a=value(name),j=(i+1)%n,b=value(names[j]); + if(a!=null&&b!=null){const p=at(i,a),q=at(j,b); + if(!comparison)plot.append(svg('polygon',{points:points([[cx,cy],p,q]),class:'lb-wedge','data-node':'wedge:'+name,'data-reveal':i})); + plot.append(svg('line',{x1:p[0],y1:p[1],x2:q[0],y2:q[1],class:'lb-radar-line'+(comparison?' lb-comparison':''),'data-node':`segment:${comparison}:${name}`,'data-reveal':i}));} + if(a!=null){const [x,y]=at(i,a),point=svg('circle',{cx:x,cy:y,r:comparison?2.5:5,tabindex:comparison?-1:0,'data-node':`point:${comparison}:${name}`,'data-reveal':i,'data-axis':comparison?null:name,class:'lb-point'+(comparison?' lb-comparison':'')});if(comparison)point.removeAttribute('data-axis');point.append(svg('title',{},`${name}: ${whole(a)}`));plot.append(point);} + }); + series(name=>compared(name),true);series(name=>current.axes[name].score,false); + plot.classList.toggle('lb-versus-agent',versus!=='average'); + 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)); + /* the whole box answers the pointer, not only the letters */ + const box=label.parentNode;box.addEventListener('pointerenter',()=>grow(true));box.addEventListener('pointerleave',()=>grow(false)); + label.addEventListener('focus',()=>grow(true));label.addEventListener('blur',()=>grow(false)); + }); + const live=container.querySelector('svg'); + if(live){live.classList.toggle('lb-versus-agent',versus!=='average');motion.morph(live,plot);} + else {container.append(plot);motion.reveal(plot,'radars');} + pills(container.querySelector('svg')); + } + /* a label's hover pill is sized on the drawn text; a hidden board has none to measure, so it is sized again once shown */ + function pills(plot) { + plot?.querySelectorAll('.lb-label').forEach(g=>{ + const b=g.querySelector('text').getBBox(), r=g.querySelector('rect');if(!b.width)return; + Object.entries({x:b.x-11,y:b.y-7,width:b.width+22,height:b.height+14}).forEach(([k,v])=>r.setAttribute(k,v.toFixed(1))); + }); + } + function swatches() { + const agent=versus!=='average'; + document.querySelectorAll('.lb-swatch').forEach(s=>{ + const second=s.dataset.swatch==='1', line=s.closest('#leaderboard-radars'), color=second?(agent?'var(--series-2)':'var(--text-dim)'):'var(--accent)'; + s.replaceChildren(); + if(line){s.append(svg('line',{x1:1,x2:21,y1:7,y2:7,stroke:color,'stroke-width':2,'stroke-dasharray':second?'4 3':''}));if(!second)s.append(svg('circle',{cx:11,cy:7,r:4,fill:color}));} + else if(!second)s.append(svg('circle',{cx:11,cy:7,r:6,fill:color})); + else if(agent)s.append(svg('path',{d:'M11 0l7 7-7 7-7-7z',fill:color})); + else s.append(svg('line',{x1:11,x2:11,y1:0,y2:14,stroke:color,'stroke-width':1.5,'stroke-dasharray':'3 2'})); + }); + } + function card() { + const current=row(selected), box=document.getElementById('lb-card');if(!current)return; + const who=element('div',null,{class:'lb-who-big'}), mark=element('span',null,{class:'lb-mark lb-mark-big'}), name=element('span'); + const url=marks[current.key]; + if(url&&!url.includes('#'))mark.append(element('img',null,{src:url,alt:''})); + else if(url){const icon=svg('svg',{viewBox:'0 0 24 24','aria-hidden':'true'});icon.append(svg('use',{href:url}));mark.append(icon);} + name.append(element('h2',current.name),element('small',[current.company,current.version_label,setup(current)].filter(Boolean).join(' · ')));who.append(mark,name); + /* an agent the filter left out of the board keeps its standing among all */ + const on=shown(current), rank=on?shownRank(current):current.rank, ranked=on&&onBoard?onBoard.size:data.rows.filter(r=>r.rank).length; + const figure=element('div',null,{class:'lb-figure'});figure.append(element('span',current.overall==null?'–':`${(current.overall*100).toFixed(1)}%`,{class:'lb-fig'}),element('span',rank?`rank ${rank} of ${ranked}`:'not ranked',{class:'muted'})); + const bar=element('span',null,{class:'lb-bar lb-bar-wide'}),fill=element('i');fill.style.width=`${(current.overall||0)*100}%`;bar.append(fill); + const against=comparedName()||'the field'; + const differences=data[family].map(name=>({name,d:current.axes[name].score!=null&&compared(name)!=null?current.axes[name].score-compared(name):null})).filter(v=>v.d!=null).sort((a,b)=>b.d-a.d); + /* a version comparison holds each family's Overall: the shown family's is the one to compare with */ + const baseline=versus==='average'?null:versus.startsWith('version:')?projection?.rows.find(r=>r.key===selected)?.families?.[family]?.overall:row(versus)?.overall; + const lines=[]; + /* a difference reads green above the reference and red below it */ + const change=d=>{const text=signed(d);return element('span',text,{class:text==='0.0'?'':d>0?'lb-up':'lb-down'});}; + const named=v=>v?[`${v.name} `,change(v.d)]:['–']; + if(baseline!=null&¤t.overall!=null)lines.push([`Overall against ${against}`,[change(current.overall-baseline)]]); + lines.push([`Best against ${against}`,named(differences[0])],[`Weakest against ${against}`,named(differences.at(-1))]); + lines.push(['Time per task',[measure('time',current.metrics?.time?.value)]],['Cost per task',[measure('cost',current.metrics?.cost?.value)]]); + box.replaceChildren(who,figure,bar,...lines.map(([k,v,title])=>{const line=element('div',null,{class:'lb-kv'});const value=element('b',null,title?{title}:{});value.append(...v);line.append(element('span',k),value);return line;})); + } + /* the pickers list who is on the board with an Overall in the shown family, each named apart from its twins; the + chosen agent is always among them, and a comparison that is gone falls back to the average */ + function pickers() { + const rows=scored(), current=row(selected), agents=current&&!rows.includes(current)?[current,...rows]:rows; + const option=r=>element('option',label(r),{value:r.key}); + const versions=data.versions.map(v=>element('option',`Same agent: ${v.label}`,{value:versionKey(v)})), others=rows.filter(r=>r.key!==selected); + if(versus!=='average'&&!others.some(r=>r.key===versus)&&!versions.some(o=>o.value===versus)){versus='average';projection=null;} + document.querySelectorAll('[data-agent-select]').forEach(s=>{s.replaceChildren(...agents.map(option));setSelect(s,selected);}); + document.querySelectorAll('[data-vs-select]').forEach(s=>{s.replaceChildren(element('option','Average',{value:'average'}),...others.map(option),...versions.map(o=>o.cloneNode(true)));setSelect(s,versus);}); + } + function draw() { + if(!row(selected))return; + pickers();swatches();card();drawScatter();for(const group of ['domains','capabilities']){strips(group);radar(group);} + settle(); + } + function press(group,attr,value){document.querySelectorAll(`#${group} [${attr}]`).forEach(b=>b.setAttribute('aria-pressed',String(b.getAttribute(attr)===value)));} + /* switching families fades what the changing columns hold, never the cells, so a row's colour and Overall stay put */ + let swapping=0; + document.querySelectorAll('[data-family]').forEach(b=>b.onclick=()=>{ + if(b.dataset.family===family)return; family=b.dataset.family; + document.querySelectorAll('[data-family]').forEach(x=>x.setAttribute('aria-pressed',String(x.dataset.family===family))); + clearTimeout(swapping); + useFamily(); + /* a sort by a column of the family that leaves would order the rows by a column nobody sees: it goes with it */ + const sorted=table.tHead.querySelector('th[data-sorted]')?.dataset.col, stale=data.axes.includes(sorted)&&!data[family].includes(sorted); + if(motion.reduced.matches){if(stale)unsort();updateTable();draw();return;} + table.classList.add('lb-swap'); + /* the columns that come in take their widths at once, behind the faded contents: widths easing while the table's + own width has already changed would hand the difference to Agent and Overall */ + swapping=setTimeout(()=>{table.classList.add('lb-instant');if(stale)unsort();updateTable();table.offsetWidth;table.classList.remove('lb-instant','lb-swap');draw();},150); + }); + 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}));if(response.ok){const result=await response.json();if(turn!==comparisonGeneration)return;projection=result;}}draw();} + document.querySelectorAll('[data-vs-select]').forEach(s=>{s.onchange=()=>{versus=s.value;document.querySelectorAll('[data-vs-select]').forEach(v=>setSelect(v,versus));compareChoice().catch(()=>{});};}); + document.querySelectorAll('[data-metric]').forEach(b=>b.onclick=()=>{metric=b.dataset.metric;press('lb-metric','data-metric',metric);drawScatter();}); + /* the measures answer for the board they were asked about; when it changed meanwhile (a save landing as the page loaded, a + run that wrote a trial), the board is read again, once */ + let reread=false; + async function deferred(turn) { const response=await nulliusFetch(`/api/leaderboard/metrics?context=${encodeURIComponent(data.context)}`); + if(response.status===409&&!reread){reread=true;const got=await fetchBoard();if(got)apply(got);return;} + 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();card();drawScatter(); } + async function fetchBoard(){const turn=++generation;const response=await nulliusFetch('/api/leaderboard');if(!response.ok)return null;const next=await response.json();return turn===generation?{next,turn}:null;} + /* each family has its own Overall and ranks: the shown family's stand in a row's overall and rank, its ranking orders the rows */ + function useFamily(){data.rows.forEach(r=>{const f=r.families?.[family];if(f){r.overall=f.overall;r.rank=f.rank;}});data.rows.sort((a,b)=>(a.rank??1e9)-(b.rank??1e9)||a.name.localeCompare(b.name)||a.key.localeCompare(b.key));} + function apply({next,turn}){if(turn!==generation)return;const kept=new Map(data.rows.map(r=>[r.key,r.metrics]));next.rows.forEach(r=>{const m=kept.get(r.key);if(!m)return;r.metrics={...m,...Object.fromEntries(Object.entries(r.metrics||{}).filter(([,v])=>v?.value!=null))};});data=next;useFamily();if(!row(selected))selected=data.selected;updateTable();compareChoice().catch(()=>{});draw();deferred(turn).catch(()=>{});} + /* scores saved in Scoring settings reach the board when it is shown again */ + /* each save fetches the new board at once, so it is ready when the board is shown; it is drawn then, at its real size */ + let fresh=null; + document.addEventListener('leaderboard:rescored',()=>{fresh=null;fetchBoard().then(got=>{if(!got)return;if(table.getClientRects().length)apply(got);else fresh=got;}).catch(()=>{});}); + document.addEventListener('leaderboard:view',e=>{settle();if(e.detail.view!=='board')return;if(fresh){const got=fresh;fresh=null;apply(got);}document.querySelectorAll('[data-chart^="radars-"] svg').forEach(pills);}); + tools?.addEventListener('change',e=>{ + const box=e.target;if(!box.matches('input[data-col]')||passing)return; + if(data.axes.includes(box.dataset.col)){try{localStorage.setItem(table.id+'.axes',JSON.stringify({...choices(),[box.dataset.col]:box.checked}));}catch{}} + if(!box.checked){e.stopPropagation();shrink(box);} + else requestAnimationFrame(()=>motion.reduced.matches?size():grow(box.dataset.col)); + },true); + useFamily();updateTable();choose(selected);tableMotion=motion.table(table);deferred(generation).catch(()=>{}); + /* what was measured before the interface's own font had loaded is measured again with it */ + const remeasure=()=>{size();drawScatter();document.querySelectorAll('[data-chart^="radars-"] svg').forEach(pills);}; + document.fonts?.ready.then(remeasure);document.fonts?.addEventListener?.('loadingdone',remeasure); + if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>{columns();applyFamily();}); +})(); diff --git a/app/static/leaderboard/leaderboard.css b/app/static/leaderboard/leaderboard.css new file mode 100644 index 000000000..0a4f00892 --- /dev/null +++ b/app/static/leaderboard/leaderboard.css @@ -0,0 +1,278 @@ +.lb-head-link { min-width: 10rem; justify-content: center; } +:root { --lb-chip-lo: var(--surface-2); --lb-chip-hi: color-mix(in oklab, var(--accent) 24%, var(--accent-soft)); --lb-chip-text: var(--text); --lb-grey: #767a82; --lb-good: #5fae74; --lb-warn: #e5b451; } +:root[data-theme="light"] { --lb-grey: #9aa1ab; --lb-good: #3f8f55; --lb-warn: #8a6100; } + +/* cards: the board, the scatter, the agent, the strips and the radars */ +.lb-panel { background: var(--surface); border: 1px solid var(--border-soft); border-radius: var(--radius); padding: 28px 30px; margin: 0 0 24px; min-width: 0; } +/* the score columns hold their name and chip in the middle; the measures stay right-aligned */ +#leaderboard-table :is(th, td):not([data-col=rank], [data-col=agent], [data-col=steps], [data-col=time], [data-col=calls], [data-col=cost]) { text-align: center; } +#leaderboard-table td { vertical-align: middle; } +.lb-panel h2 { font-size: 1.25rem; font-weight: 600; margin: 0; } +.lb-panel h3 { font-size: .82rem; letter-spacing: .08em; text-transform: uppercase; font-weight: 500; color: var(--text-dim); margin: 0 0 8px; } +.lb-head { display: flex; flex-wrap: wrap; gap: 8px; justify-content: space-between; align-items: center; margin-bottom: 16px; } +.lb-two { display: grid; gap: 24px; grid-template-columns: minmax(0, 1fr); margin: 0 0 24px; } +.lb-two > .lb-panel { margin: 0; } +@media (min-width: 1000px) { .lb-two { grid-template-columns: minmax(0, 1.7fr) minmax(0, 1fr); } } + +/* the table */ +.lb-table { table-layout: fixed; width: 100%; font-size: .82rem; } +.lb-table th { white-space: nowrap; text-align: center; overflow: hidden; transition: width .28s cubic-bezier(.2,.7,.2,1), padding .28s cubic-bezier(.2,.7,.2,1), color .15s ease; } +.lb-table { transition: min-width .28s cubic-bezier(.2,.7,.2,1); } +.lb-table td { overflow: hidden; } +.lb-table .lb-closing { padding-left: 0; padding-right: 0; transition: width .28s cubic-bezier(.2,.7,.2,1), padding .28s cubic-bezier(.2,.7,.2,1); } +.lb-table.lb-instant, .lb-table.lb-instant :is(th, td), .lb-table .lb-instant { transition: none; } +/* switching families: the changing columns' contents fade, their cells and the row's colour stay */ +.lb-table :is(th, td) > * { transition: opacity .15s ease; } +.lb-table.lb-swap :is(th, td):not([data-col="rank"], [data-col="agent"], [data-col="overall"]) { color: transparent; } +.lb-table.lb-swap :is(th, td):not([data-col="rank"], [data-col="agent"], [data-col="overall"]) > * { opacity: 0; } +/* the sideways scrollbar's track is always there, so a wider table never pushes the page down */ +#leaderboard-board .table-wrap { overflow-x: scroll; } +.lb-table [data-col="rank"] { width: 48px; text-align: center; } +/* the sort arrow sits in the header's own padding: a sorted name stays centred, and is never cut by its column */ +#leaderboard-table thead th[data-sorted]::after { position: absolute; top: 50%; transform: translateY(-50%); line-height: 1; margin-left: .25rem; } +.lb-table [data-col="agent"] { width: 238px; text-align: left; } +.lb-table [data-col="overall"] { width: 104px; } +.lb-table [data-col="steps"] { width: 66px; } .lb-table [data-col="time"] { width: 84px; } .lb-table [data-col="calls"] { width: 92px; } .lb-table [data-col="cost"] { width: 88px; } +.lb-table td { text-align: center; white-space: nowrap; color: var(--text-dim); font-variant-numeric: tabular-nums; padding-top: 9px; padding-bottom: 9px; transition: background-color .2s, padding .28s cubic-bezier(.2,.7,.2,1), color .15s ease; } +/* the board sits on a card, so its pinned cells take the card's colour, and the row's when hovered or chosen */ +#leaderboard-board .table-wrap .grid .sticky-col, #leaderboard-board .table-wrap .grid thead th { background: var(--surface); } +#leaderboard-board .table-wrap .grid tbody tr:hover td { background: var(--surface-2); } +#leaderboard-board .table-wrap .grid tbody tr.lb-sel td { background: var(--accent-soft); } +.lb-table tbody tr { cursor: pointer; } +.lb-table tbody tr:hover td { background: var(--surface-2); } +.lb-table tbody tr.lb-sel td { background: var(--accent-soft); } +.lb-table tbody tr.lb-sel td:first-child { box-shadow: inset 3px 0 var(--accent); } +.lb-agent { all: unset; display: flex; align-items: center; gap: 10px; cursor: pointer; min-width: 0; max-width: 100%; } +.lb-agent:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.lb-mark { display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; flex: none; border-radius: 7px; overflow: hidden; } +.lb-mark img, .lb-mark svg { width: 100%; height: 100%; object-fit: contain; display: block; } +.lb-who { min-width: 0; } +.lb-who b { display: block; font-weight: 600; color: var(--text); white-space: normal; overflow-wrap: anywhere; } +.lb-who small { display: block; color: var(--text-faint); font-size: .75rem; white-space: normal; overflow-wrap: anywhere; } +.lb-overall { display: inline-block; font-weight: 600; color: var(--text); padding: 2px 5px; border: 1.5px solid transparent; cursor: help; } +.lb-bar { display: block; height: 4px; width: 68px; max-width: 100%; margin: 4px auto 0; border-radius: 2px; background: var(--surface-2); } +.lb-bar i { display: block; height: 100%; border-radius: 2px; background: var(--accent); transition: width .32s cubic-bezier(.2,.7,.2,1); } +.lb-chip { display: inline-block; min-width: 46px; padding: 4px 7px; border-radius: 6px; font-weight: 600; cursor: help; --lb-chip: color-mix(in oklab, var(--lb-chip-hi) calc(var(--lb-t, 0) * 100%), var(--lb-chip-lo)); background: var(--lb-chip); color: var(--lb-chip-text); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text) 8%, transparent); } +/* the text is white on a dark shade and near black on a light one: the shade's lightness decides, per theme */ +.lb-chip.lb-top { --lb-chip: color-mix(in oklab, var(--accent) calc(60% + var(--lb-t2, 0) * 40%), var(--accent-soft)); color: var(--surface); } +/* in the light theme the strong chip starts darker, so its white text reads from the first step (4.5:1) */ +:root[data-theme="light"] .lb-chip.lb-top { --lb-chip: color-mix(in oklab, var(--accent) calc(80% + var(--lb-t2, 0) * 20%), var(--accent-soft)); } +.lb-none { color: var(--text-faint); } +/* a cell's contents are boxes, so they can slide when their row moves */ +.lb-none, .lb-m { display: inline-block; } + +/* the scatter */ +.lb-scroll { overflow-x: auto; scrollbar-width: thin; } +.lb-scatter { display: block; width: 100%; min-width: 520px; } +.lb-scatter text, .lb-chart-pair svg text { fill: var(--text-dim); font: 12px var(--sans); } +.lb-scatter .lb-grid { stroke: color-mix(in srgb, var(--text) 8%, transparent); } +.lb-scatter .lb-better { fill: var(--lb-good); font-weight: 600; letter-spacing: .08em; } +.lb-scatter .lb-name { font-weight: 600; fill: var(--text-dim); } +.lb-scatter .lb-name.lb-me { fill: var(--text); } +.lb-scatter .lb-version { font-size: 10.5px; fill: var(--text-faint); } +.lb-dot { cursor: pointer; outline: none; } +.lb-dot .lb-tile { fill: var(--bg); } +.lb-dot .lb-edge { fill: none; stroke: color-mix(in srgb, var(--text) 15%, transparent); } +.lb-dot.lb-current .lb-edge { stroke: var(--accent); stroke-width: 2.5; } +.lb-dot:is(:hover, :focus-visible) .lb-edge { stroke: var(--text); } +.lb-dot .lb-logo { transform-box: fill-box; transform-origin: center; transition: transform .18s ease-out; } +.lb-dot:is(:hover, :focus-visible) .lb-logo { transform: scale(1.25); } + +/* the agent card */ +.lb-who-big { display: flex; gap: 12px; align-items: center; } +.lb-who-big h2 { font-size: 1.2rem; } +.lb-who-big small { color: var(--text-faint); font-size: .82rem; } +.lb-mark-big { width: 48px; height: 48px; border-radius: 10px; } +.lb-figure { margin: 18px 0 12px; display: flex; align-items: baseline; gap: 8px; } +.lb-fig { font-size: 2.5rem; font-weight: 650; line-height: 1.1; color: var(--text); } +.lb-bar-wide { width: 100%; height: 8px; margin: 0 0 18px; border-radius: 4px; } +.lb-bar-wide i { border-radius: 4px; } +.lb-kv { display: flex; justify-content: space-between; gap: 12px; padding: 6px 0; color: var(--text-dim); font-size: .88rem; } +/* a line's label wraps inside the card; its value keeps its own width */ +.lb-kv > span { min-width: 0; overflow-wrap: anywhere; } +.lb-kv > b { flex: none; max-width: 62%; } +.lb-kv .lb-up { color: var(--lb-good); } +.lb-kv .lb-down { color: var(--bad); } +.lb-kv b { color: var(--text); font-weight: 600; text-align: right; } + +/* pickers over the strips and the radars */ +.lb-picks { display: flex; flex-wrap: wrap; gap: 8px 10px; align-items: center; } +.lb-picks .lb-pick { display: inline-flex; align-items: center; gap: 6px; } +.lb-picks select, .lb-picks .ui-select-trigger { width: 190px; } +.lb-swatch { width: 22px; height: 14px; flex: none; } +/* scrolled to, a picker stops below the page's top bar rather than under it */ +.lb-picks .ui-select-trigger { scroll-margin-top: calc(var(--topbar-height) + 12px); } + +/* two columns: domains, capabilities */ +.lb-chart-pair { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; } +.lb-chart-pair > * + * { border-top: 1px solid var(--border); padding-top: 24px; } +/* the two halves pad alike on either side of the divider, so both charts are drawn at one size */ +@media (min-width: 900px) { .lb-chart-pair { grid-template-columns: 1fr 1fr; gap: 0; } .lb-chart-pair > :first-child { padding-right: 36px; } .lb-chart-pair > * + * { border-top: 0; border-left: 1px solid var(--border); padding: 0 0 0 36px; } } + +/* strips */ +.lb-srow { display: grid; grid-template-columns: 104px minmax(0, 1fr) 42px; gap: 10px; align-items: center; height: 38px; font-size: .88rem; } +.lb-srow > :last-child { line-height: 1.15; } +.lb-srow > :first-child { text-align: right; cursor: help; } +.lb-srow > :last-child { font-weight: 600; color: var(--text); } +.lb-srow small { display: block; color: var(--series-2); font-weight: 500; font-size: .72rem; line-height: 1; } +.lb-track { position: relative; height: 22px; background: linear-gradient(var(--border-soft), var(--border-soft)) center / 100% 1px no-repeat; } +.lb-track > * { position: absolute; top: 50%; transition: left .32s cubic-bezier(.2,.7,.2,1), transform .18s ease-out; } +.lb-track i { width: 8px; height: 8px; margin: -4px; border-radius: 50%; background: var(--lb-grey); cursor: pointer; } +.lb-track i.lb-me { width: 13px; height: 13px; margin: -6.5px; background: var(--accent); box-shadow: 0 0 0 2px var(--surface); z-index: 2; } +.lb-track i:is(:hover, :focus-visible) { transform: scale(1.5); outline: none; } +.lb-track u { top: 0; bottom: 0; border-left: 1.5px dashed var(--text-dim); } +.lb-track em { width: 11px; height: 11px; margin: -5.5px; transform: rotate(45deg); background: var(--series-2); box-shadow: 0 0 0 2px var(--surface); pointer-events: none; z-index: 3; } + +/* radars */ +.lb-chart-pair svg { display: block; width: 100%; max-height: 440px; overflow: visible; } +.lb-ring { fill: none; stroke: var(--border-soft); } +.lb-axis-label { cursor: help; outline: none; } +.lb-axis-label:focus-visible { text-decoration: underline; } +.lb-chart-pair svg text.lb-axis-label { font-size: 14.5px; } +.lb-chart-pair svg .lb-axis-label .lb-me { font-size: 16px; } +.lb-pill { fill: color-mix(in oklab, var(--accent) 16%, transparent); stroke: color-mix(in oklab, var(--accent) 28%, transparent); opacity: 0; cursor: help; transition: opacity 150ms; } +.lb-label:is(:hover, :focus-within) .lb-pill { opacity: 1; } +.lb-chart-pair svg .lb-label:is(:hover, :focus-within) text { fill: var(--accent); } +.lb-chart-pair svg .lb-label:is(:hover, :focus-within) .lb-me { fill: var(--accent); } +.lb-chart-pair svg .lb-me { fill: var(--text); font-weight: 600; } +.lb-chart-pair svg .lb-versus { fill: var(--series-2); } +.lb-wedge { fill: var(--accent); opacity: .14; } +.lb-radar-line { fill: none; stroke: var(--accent); stroke-width: 2; } +.lb-radar-line.lb-comparison { stroke: var(--text-dim); stroke-dasharray: 4 4; } +.lb-versus-agent .lb-radar-line.lb-comparison { stroke: var(--series-2); } +.lb-point { fill: var(--accent); cursor: pointer; transform-box: fill-box; transform-origin: center; transition: transform 150ms; outline: none; } +.lb-point.lb-comparison { fill: var(--text-dim); cursor: default; } +.lb-versus-agent .lb-point.lb-comparison { fill: var(--series-2); } +.lb-point:not(.lb-dot):is(:hover, :focus-visible, .lb-hover) { transform: scale(1.6); } +.lb-dot.lb-point { transform: none; } + +/* score evidence */ +.lb-evidence { position: fixed; z-index: 100; width: max-content; max-width: min(560px, calc(100vw - 24px)); max-height: min(640px, calc(100vh - 24px)); overflow: auto; padding: 18px 20px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); color: var(--text); font-size: .8rem; box-shadow: 0 8px 24px color-mix(in srgb, #000 30%, transparent); } +.lb-evidence > strong { display: block; font-size: .95rem; font-weight: 600; } +.lb-evidence p { margin: .3rem 0 0; color: var(--text-faint); font-size: .76rem; } +.lb-ev-table { width: 100%; margin-top: 12px; border-collapse: collapse; font-size: .8rem; } +.lb-ev-table th { padding: 0 8px 6px; color: var(--text-faint); font-weight: 500; font-size: .74rem; text-align: right; white-space: nowrap; border-bottom: 1px solid var(--border-soft); } +.lb-ev-table th:first-child, .lb-ev-table td:first-child { text-align: left; padding-left: 0; } +.lb-ev-table td { padding: 8px; vertical-align: top; border-bottom: 1px solid var(--border-soft); color: var(--text); } +.lb-ev-table td:last-child, .lb-ev-table th:last-child { padding-right: 0; } +.lb-ev-table td small { display: block; margin-top: 3px; color: var(--text-faint); font-size: .72rem; } +.lb-ev-table td small a { color: var(--text-dim); text-decoration: underline; text-underline-offset: 2px; } +.lb-ev-table td small a:hover { color: var(--text); } +.lb-ev-num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +.lb-ev-score { text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; } +.lb-ev-scorebox { display: inline-flex; gap: 8px; align-items: center; justify-content: flex-end; min-height: 1.2em; } +.lb-ev-pct { display: inline-block; min-width: 5ch; text-align: right; } +.lb-ev-bar { flex: none; width: 56px; height: 5px; border-radius: 3px; background: var(--surface-2); overflow: hidden; } +.lb-ev-bar i { display: block; height: 100%; background: var(--accent); border-radius: 3px; } +.lb-ev-table tfoot td { border-bottom: 0; padding-top: 10px; color: var(--accent); font-weight: 600; } + +/* medals */ +.lb-medal { display: inline-block; width: 30px; height: 36px; vertical-align: middle; color: var(--lb-medal-gold); } +.lb-medal svg { display: block; width: 100%; height: 100%; overflow: visible; } +.lb-medal text { font-family: var(--sans); } +.lb-medal-2 { color: var(--lb-medal-silver); }.lb-medal-3 { color: var(--lb-medal-bronze); }.lb-medal-4 { color: var(--lb-medal-chocolate); } +/* hovering a row grows its wreath again leaf by leaf, then the disc glows in its metal's colour */ +.lb-medal .lb-leaf { transform-box: fill-box; transform-origin: center; } +tr:hover .lb-medal .lb-leaf { animation: lb-leaf .42s cubic-bezier(.2,.7,.2,1) both; animation-delay: calc(var(--i) * 45ms); } +tr:hover .lb-medal .lb-disc { animation: lb-glow .9s ease-in-out .25s; } +@keyframes lb-leaf { from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; } } +@keyframes lb-glow { 50% { filter: drop-shadow(0 0 3px currentColor); } } +: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 settings: one header per card names the columns every row lines up under */ +.lb-settings fieldset { border: 0; padding: 0; margin: 0; min-width: 0; } +.lb-settings h2 { font-size: 1rem; margin: 0; } +.lb-axes > h2 { margin-bottom: 14px; } +.lb-settings .lb-input { box-sizing: border-box; width: 100%; min-width: 0; min-height: 34px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-2); color: var(--text); font: 13px/1.5 var(--sans); font-variant-numeric: tabular-nums; outline: none; transition: border-color .15s, box-shadow .15s; } +.lb-input:hover { border-color: var(--text-faint); } +.lb-input:focus { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } +.lb-input::placeholder { color: var(--text-faint); } +.lb-settings .lb-input:disabled { opacity: .5; cursor: not-allowed; } +.lb-input[type=number] { -moz-appearance: textfield; appearance: textfield; } +.lb-input::-webkit-inner-spin-button, .lb-input::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } +.lb-input[aria-invalid="true"] { border-color: var(--bad); box-shadow: inset 0 0 0 1px var(--bad); } +.lb-icon { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; padding: 0; flex: none; } +.lb-icon .ic { width: 16px; height: 16px; } +/* every select keeps room for its name on one line; an axis's weight in Overall sits beside its name, folded or not, and its + benchmarks open below it: nothing moves when a row folds */ +.lb-axis { --lb-entry: minmax(112px, 1.2fr) minmax(132px, 1.3fr) minmax(132px, 1.2fr) minmax(96px, 1fr) 72px 34px; + display: grid; grid-template-columns: 156px minmax(0, 1fr); grid-template-areas: 'name weight' '. entries'; gap: 0 16px; align-items: start; padding: 14px 0; border-top: 1px solid var(--border-soft); } +.lb-axis h3 { text-transform: none; letter-spacing: normal; margin: 0; font-size: .88rem; font-weight: 600; color: var(--text); } +.lb-fold { display: inline-flex; align-items: center; min-height: 34px; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer; text-align: left; } +.lb-fold:hover { color: var(--accent-strong); } +.lb-fold:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; } +.lb-count { margin-left: 8px; color: var(--text-faint); font-weight: 400; font-size: .76rem; font-variant-numeric: tabular-nums; } +.lb-fold[aria-expanded="true"] .lb-count { display: none; } +.lb-overview { margin: 12px 0 20px; } +.lb-overview > .lb-fold { font-size: .82rem; font-weight: 600; color: var(--text-dim); } +.lb-ov-wrap { margin-top: 8px; } +.lb-ov { width: 100%; border-collapse: collapse; font-size: .8rem; } +.lb-ov th { padding: 6px 6px 8px; color: var(--text-faint); font-weight: 500; font-size: .72rem; text-align: left; border-bottom: 1px solid var(--border-soft); hyphens: auto; vertical-align: bottom; } +.lb-ov td { padding: 8px 6px; border-bottom: 1px solid var(--border-soft); color: var(--text); vertical-align: middle; } +.lb-ov tr > :first-child { padding-left: 0; font-weight: 500; } +.lb-ov .lb-ov-num { text-align: center; } +.lb-ov-chip { display: inline-block; min-width: 40px; padding: 3px 6px; border-radius: 6px; font: 600 .74rem var(--mono); font-variant-numeric: tabular-nums; + background: color-mix(in oklab, var(--accent) calc(16% + var(--v, 0) * 30%), transparent); color: var(--text); } +.lb-ov-none { color: var(--text-faint); } +.lb-axis > h3 { grid-area: name; } +.lb-axis > .lb-entries { grid-area: entries; } +.lb-weight { grid-area: weight; align-self: start; } +.lb-weight-name { color: var(--text-faint); font-size: .75rem; } +.lb-axis-head .lb-fold { display: none; } +.lb-axis-head { padding: 0 0 8px; border-top: 0; color: var(--text-faint); font-size: .75rem; } +.lb-entries { display: grid; gap: 8px; justify-items: start; min-width: 0; } +/* the space above a row's benchmarks is inside what slides, never padding the slide's height would leave behind */ +.lb-entries::before { content: ''; height: 2px; } +.lb-entries > [data-entries] { display: grid; gap: 8px; width: 100%; } +.lb-entries > [data-entries]:empty { display: none; } +.lb-entry { display: grid; grid-template-columns: var(--lb-entry); gap: 8px; align-items: center; min-width: 0; } +.lb-cell { min-width: 0; } +.lb-cell .ui-select-trigger { width: 100%; } +.lb-cell.lb-none { color: var(--text-faint); text-align: center; } +.lb-cell.lb-fixed { padding: 0 12px; overflow-wrap: anywhere; } +.lb-weight { display: grid; grid-template-columns: auto 58px; justify-content: start; gap: 8px; align-items: center; } +.lb-weight output { text-align: left; } +.lb-reset { display: flex; justify-content: flex-end; margin: 0 0 16px; } +#reset-confirm:not([hidden]) { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: flex-end; } +.lb-savebar[hidden] { display: none; } +.lb-savebar { position: sticky; bottom: 12px; display: flex; gap: 12px; align-items: center; justify-content: space-between; padding: 10px 14px; border: 1px solid var(--bad); border-radius: 10px; background: var(--surface-2); } +@media (max-width: 700px) { + .lb-company { display: none; } + /* #, Agent and Overall fill a phone's width exactly: the first score is a sideways scroll away, Overall never cut */ + .lb-table :is(th, td) { padding-left: .6rem; padding-right: .6rem; } + .lb-table [data-col="rank"] { width: 44px; } + #leaderboard-table [data-col="agent"] { position: relative; left: auto; width: 168px; box-shadow: none; } + .lb-table [data-col="overall"] { width: 84px; } + .lb-picks .lb-pick { flex: 1 1 100%; } + .lb-picks select, .lb-picks .ui-select-trigger { flex: 1; width: auto; } + .lb-picks > .muted { display: none; } + .lb-srow { grid-template-columns: 96px minmax(0, 1fr) 40px; } + .lb-complete-count { display: none; } +} +@media (max-width: 380px) { + /* a narrow phone: tighter cells and a smaller logo keep Overall whole and a name on one line */ + .lb-table [data-col="rank"] { padding-left: .2rem; padding-right: .2rem; } + #leaderboard-table td[data-col="agent"] { padding-right: .3rem; } + .lb-agent { gap: 8px; } + .lb-agent .lb-mark { width: 24px; height: 24px; } +} +/* a scoring row lays out by its card's width, whatever the window's and the rail's: too narrow for a row's name beside + its benchmarks, they go under it; narrower still, each benchmark stacks */ +.lb-axes { container-type: inline-size; } +@container (max-width: 800px) { + .lb-axis { grid-template-areas: 'name weight' 'entries entries'; } + .lb-axis-head > span { display: none; } + .lb-axis-head > .lb-entry { grid-column: 1 / -1; } +} +@container (max-width: 640px) { + .lb-axis { grid-template-columns: minmax(0, 1fr) auto; gap: 0 10px; } + .lb-axis-head { display: none; } + .lb-entry { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); padding-bottom: 8px; border-bottom: 1px dashed var(--border-soft); } + .lb-entry > .lb-none { display: none; } + .lb-entry > :first-child { grid-column: 1 / -1; } + .lb-weight { grid-template-columns: auto 90px; } +} +@media (prefers-reduced-motion: reduce) { + .lb-medal, .lb-medal *, .lb-point, .lb-bar i, .lb-table, .lb-table th, .lb-table td, .lb-track > *, .lb-dot .lb-logo { animation: none !important; transition: none !important; } +} diff --git a/app/static/leaderboard/motion.js b/app/static/leaderboard/motion.js new file mode 100644 index 000000000..9604f7c22 --- /dev/null +++ b/app/static/leaderboard/motion.js @@ -0,0 +1,131 @@ +/* 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);},()=>{}); + } + /* a table cell's contents fade, never the cell: its background is the row's colour */ + function contents(cell, show=true, duration=240) { + if(reduced.matches)return []; + const options={duration,easing:show?'ease-out':'ease-in',fill:show?'none':'forwards'}; + return [cell.animate(show?[{color:'transparent'},{}]:[{},{color:'transparent'}],options), + ...[...cell.children].map(child=>child.animate(show?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],options))]; + } + 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'?Number(plot.dataset.cx??180):Number(plot.dataset.cy??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}])); + const box=table.closest('.table-wrap')||table; + let previous=measure(),height=box.offsetHeight,frame,easing=null; + const capture=()=>{if(!box.getClientRects().length)return;previous=measure();height=easing?height:box.offsetHeight;}; + /* rows coming or going change the table's height: it eases to its new height instead of jumping */ + const ease=(from,to)=>{ + if(reduced.matches||Math.abs(from-to)<2)return; + easing?.cancel();box.style.overflowY='hidden'; + easing=box.animate([{height:`${from}px`},{height:`${to}px`}],{duration:280,easing:'cubic-bezier(.2,.7,.2,1)'}); + const done=easing;done.finished.then(()=>{if(easing===done){easing=null;box.style.overflowY='';}},()=>{}); + }; + const update=()=>{ + cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>{ + /* a hidden table (the other view showing) has no height to ease from or to: it is measured afresh once shown */ + if(!box.getClientRects().length){previous=new Map();height=null;return;} + const next=measure(),now=box.offsetHeight;if(height!=null)ease(height,now);height=now; + /* nothing in a table is moved by a transform, which some engines draw blank: a row that moved, a cell that + appears or one whose text changed fades in where it now is */ + /* a cell's contents may move, never the cell: a row that moved slides what it holds from where it was, a row + that comes back fades and drops what it holds in */ + const arriving=new Set(); + const slide=(row,frames,duration)=>{if(reduced.matches)return;[...row.cells].forEach(cell=>[...cell.children].forEach(child=>child.animate(frames,{duration,easing:'cubic-bezier(.2,.7,.2,1)'})));}; + next.forEach(({rect,text},node)=>{ + const old=previous.get(node);if(!old||!rect.width||!rect.height)return; + if(node.tagName==='TD'&&arriving.has(node.parentElement))return; + const appeared=!old.rect.width||!old.rect.height; + if(node.tagName==='TR'){ + if(appeared){arriving.add(node);slide(node,[{opacity:0,transform:'translateY(-10px)'},{opacity:1,transform:'none'}],320);} + else{const dy=old.rect.y-rect.y;if(Math.abs(dy)>.5)slide(node,[{transform:`translateY(${dy}px)`},{transform:'none'}],320);} + return; + } + if(appeared||old.text!==text)contents(node); + });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,contents,reduced}; +})(); diff --git a/app/static/leaderboard/scoring.js b/app/static/leaderboard/scoring.js new file mode 100644 index 000000000..8ac4a2e6a --- /dev/null +++ b/app/static/leaderboard/scoring.js @@ -0,0 +1,142 @@ +/* Scoring settings, the Leaderboard's other view: complete-document autosave, writes in turn, the latest draft kept. */ +(() => { + 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, queued=false; + const writable=form.dataset.writable==='true', status=form.querySelector('[data-changes]'), retry=form.querySelector('[data-settings-retry]'), bar=status.closest('.lb-savebar'); + 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 icon=name=>{const s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttribute('class','ic');s.setAttribute('aria-hidden','true');const u=document.createElementNS('http://www.w3.org/2000/svg','use');u.setAttribute('href','#'+name);s.append(u);return s;}; + const input=(value,change,attrs={})=>{const n=el('input',null,{type:'number',min:0,step:'any',class:'lb-input',...attrs});n.value=value??'';n.oninput=()=>{change(n.value===''?null:Number(n.value));edited();};return n;}; + const select=(choices,value,change,label)=>{const n=el('select',null,{'aria-label':label});choices.forEach(([v,text])=>{const o=el('option',text,{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=()=>{const held=document.activeElement===n.nextElementSibling;change(n.value);render();edited();if(held)refocus(label);};return n;}; + /* a select that changed is drawn again with its row: focus goes to the one that took its place, once its button is built */ + const refocus=label=>requestAnimationFrame(()=>requestAnimationFrame(()=>[...form.querySelectorAll('select')].find(n=>n.getAttribute('aria-label')===label)?.nextElementSibling?.focus())); + const cell=child=>{const c=el('span',null,{class:'lb-cell'});c.append(child);return c;}; + const none=()=>el('span','–',{class:'lb-cell lb-none'}); + const remove=(label,action)=>{const b=el('button',null,{type:'button',class:'btn ghost sm lb-icon','aria-label':label,title:'Remove'});b.append(icon('i-x'));b.onclick=action;return b;}; + const number=v=>Number.isFinite(v)&&v>=0; + /* each section opens on an overview: every benchmark's share of each of its axes */ + const names=section=>[...section.querySelectorAll('[data-scoring-axis]')].map(n=>n.dataset.scoringAxis); + const keyOf=e=>e.benchmark; + const labelOf=key=>data.options.find(o=>o.key===key)?.label||key; + /* a benchmark's default version: the one a new row reads */ + const versionOf=key=>data.options.find(o=>o.key===key&&o.default)||data.options.find(o=>o.key===key); + /* a benchmark with one dataset is that dataset: read whole or by its dataset, it is one entry */ + const sole=o=>o&&o.datasets.length===1?o.datasets[0].id:''; + const identity=e=>[e.benchmark,e.dataset||sole(data.options.find(o=>o.key===e.benchmark&&o.version===e.version)),e.version,e.metric].join('\n'); + const families=[...form.querySelectorAll('section.lb-axes')].map(section=>({title:section.querySelector('h2').textContent,names:names(section)})); + /* what keeps the draft from being saved: a field marked where it is wrong, or one line saying what to do. + Each family has its own Overall, so each needs a weighted row among those that have a benchmark. */ + function check() { + form.querySelectorAll('input').forEach(n=>{n.setCustomValidity('');n.setAttribute('aria-invalid',String(!n.checkValidity()));}); + /* a weight that is wrong is marked in place, and named with its row: the row may be folded */ + const wrong=[...form.querySelectorAll('input.lb-input')].find(n=>!n.disabled&&!n.checkValidity())?.closest('[data-scoring-axis]')?.dataset.scoringAxis + ||Object.entries(draft.axes).find(([,a])=>!number(a.weight)||a.entries.some(e=>!number(e.weight)))?.[0]; + if(wrong)return {ok:false,message:`${wrong}: enter a weight of 0 or more.`}; + for(const [name,axis] of Object.entries(draft.axes)){const seen=new Set();for(const e of axis.entries){if(seen.has(identity(e)))return {ok:false,message:`${name}: ${labelOf(e.benchmark)} is listed twice. Change or remove one.`};seen.add(identity(e));}} + for(const family of families){const mapped=family.names.filter(n=>draft.axes[n].entries.length);if(mapped.length&&!mapped.some(n=>draft.axes[n].weight>0))return {ok:false,message:`${family.title}: give at least one row a weight above 0.`};} + if(!Object.values(draft.axes).some(a=>a.entries.length))return {ok:false,message:'Add a benchmark to a row.'}; + if(!Object.values(draft.axes).some(a=>a.weight>0))return {ok:false,message:'Give at least one row a weight above 0.'}; + return {ok:true,message:''}; + } + const shareIn=(axis,key)=>{const a=draft.axes[axis],total=a.entries.reduce((n,e)=>n+(number(e.weight)?e.weight:0),0);return total?a.entries.filter(e=>keyOf(e)===key).reduce((n,e)=>n+(number(e.weight)?e.weight:0),0)/total:0;}; + function overview() { + form.querySelectorAll('[data-overview]').forEach(table=>{ + const mine=names(table.closest('section')); + const keys=[...new Set(mine.flatMap(a=>draft.axes[a].entries.map(keyOf)))]; + const head=el('tr');head.append(el('th','Benchmark'),...mine.map(a=>el('th',a,{class:'lb-ov-num'}))); + const body=el('tbody'); + keys.forEach(key=>{ + const tr=el('tr');tr.append(el('td',labelOf(key))); + mine.forEach(a=>{const v=shareIn(a,key),td=el('td',null,{class:'lb-ov-num'});if(v>0){const chip=el('span',v.toFixed(2),{class:'lb-ov-chip'});chip.style.setProperty('--v',v.toFixed(3));td.append(chip);}else td.append(el('span','·',{class:'lb-ov-none'}));tr.append(td);}); + body.append(tr); + }); + if(!keys.length){const tr=el('tr');tr.append(el('td','No benchmark',{colspan:mine.length+1,class:'lb-ov-none'}));body.append(tr);} + const thead=el('thead');thead.append(head);table.replaceChildren(thead,body); + }); + } + /* the bar under the form: a save that failed offers Retry, one refused because the settings changed elsewhere offers + Reload, and what keeps the draft from being saved is said with no button */ + const FAILED='Scoring settings could not be saved. Retry.'; + function report(message,kind='') {status.textContent=message;bar.hidden=!kind;bar.dataset.kind=kind;retry.hidden=kind==='invalid';retry.textContent=kind==='conflict'?'Reload':'Retry';} + function edited() { + resetting=false;dirty=true;overview();clearTimeout(timer); + const {ok,message}=check(); + if(message)report(message,'invalid');else if(bar.dataset.kind==='invalid')report(''); + if(ok)timer=setTimeout(save,300); + } + async function save(reset=false) { + if(!writable)return; + if(writing){queued=queued||reset;return;} // a reset asked during a write runs after it + if(!reset&&(!dirty||!check().ok))return; + writing=true;dirty=false;const body=reset?{reset:true}:structuredClone(draft); + if(reset){resetting=true;form.querySelector('fieldset').disabled=true;} + let failed=false; + 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),keepalive:true}); + const result=await response.json().catch(()=>({})); + if(!response.ok||!result.revision){const refused=new Error(result.error||FAILED);refused.kind=response.status===409?'conflict':'error';throw refused;} + revision=result.revision;if(reset){draft=result.settings;resetting=false;render();document.getElementById('reset-confirm').hidden=true;document.getElementById('reset-ask').hidden=false;} + const now=check().message;report(now||'Scoring saved',now?'invalid':''); // what the draft typed meanwhile still needs + window.nulliusNotify('Scoring saved',{key:'scoring'}); + document.getElementById('lb-warning')?.remove(); // the file that could not be read has been rewritten + document.dispatchEvent(new Event('leaderboard:rescored')); + } catch(error) {dirty=true;failed=true;report(error.kind?error.message:FAILED,error.kind||'error');} + finally {writing=false;if(reset){form.querySelector('fieldset').disabled=false;}} + if(queued){queued=false;save(true);} + else if(!failed&&dirty&&check().ok)save(); + } + function render() { + document.querySelectorAll('[data-scoring-axis]').forEach(section=>{ + const name=section.dataset.scoringAxis, axis=draft.axes[name], container=section.querySelector('[data-entries]');container.replaceChildren(); + axis.entries.forEach((entry,index)=>{ + const line=el('div',null,{class:'lb-entry'}), choices=[...new Map(data.options.map(o=>[o.key,o.label])).entries()]; + const n=index+1, source=select(choices,entry.benchmark,value=>{axis.entries[index]={benchmark:value,dataset:sole(versionOf(value)),version:versionOf(value).version,metric:'Score',weight:entry.weight};},`${name}, benchmark ${n}`); + line.append(cell(source)); + const versions=data.options.filter(o=>o.key===entry.benchmark), bench=versions.find(o=>o.version===entry.version), sets=bench?.datasets||[], metrics=bench?.metrics||['Score']; + /* one dataset is the whole benchmark: a fixed value, not a choice between two equal ones */ + const only=sets.length===1&&(!entry.dataset||entry.dataset===sets[0].id); + line.append(only?el('span',sets[0].label,{class:'lb-cell lb-fixed small muted'}):sets.length||entry.dataset?cell(select([['','Whole benchmark'],...sets.map(d=>[d.id,d.label])],entry.dataset,v=>entry.dataset=v,`${name}, dataset ${n}`)):none()); + line.append(versions.length>1||!bench?cell(select(versions.map(v=>[v.version,v.version_label||'–']),entry.version,v=>entry.version=v,`${name}, version ${n}`)):none()); + line.append(metrics.length>1||entry.metric!=='Score'?cell(select(metrics.map(m=>[m,m]),entry.metric,v=>entry.metric=v,`${name}, metric ${n}`)):none()); + line.append(cell(input(entry.weight,v=>entry.weight=v,{required:'','aria-label':`${name}, weight ${n}`})),remove(`Remove benchmark ${n} from ${name}`,()=>{axis.entries.splice(index,1);if(!axis.entries.length)axis.weight=0;render();edited();(container.querySelectorAll('.lb-entry > .lb-icon')[index]||section.querySelector('[data-add-entry]')).focus();})); + container.append(line); + }); + section.querySelector('[data-count]').textContent=axis.entries.length; + const weight=section.querySelector('[data-overall]');if(weight){weight.value=axis.weight;weight.disabled=!axis.entries.length;weight.title=axis.entries.length?'':'Add a benchmark first';weight.oninput=()=>{axis.weight=weight.value===''?null:Number(weight.value);edited();};} + section.querySelector('[data-add-entry]').onclick=()=>{ + /* a new row reads the first benchmark the axis does not name yet, as a whole; when it names them all, the first it + does not list whole, else the first */ + const whole=o=>({benchmark:o.key,dataset:sole(o),version:o.version,metric:'Score',weight:1}), listed=new Set(axis.entries.map(identity)), named=new Set(axis.entries.map(e=>e.benchmark)); + const firsts=[...new Set(data.options.map(o=>o.key))].map(versionOf), pick=firsts.find(o=>!named.has(o.key))||firsts.find(o=>!listed.has(identity(whole(o))))||firsts[0]; + if(!pick)return; + const fresh=whole(pick); + /* an empty axis weighs 0 in Overall; its first benchmark brings back the axis's standard weight */ + if(!axis.entries.length&&!axis.weight)axis.weight=data.overall?.[name]||0; + axis.entries.push(fresh);render();edited();}; + });overview(); + /* a viewer who may not write still opens every row: only what edits is locked */ + if(!writable)form.querySelectorAll('input:not([type=hidden]),select,button:not(.lb-fold)').forEach(n=>{n.disabled=true;}); + } + /* each axis folds its benchmarks away; rows open folded, the overview open */ + form.querySelectorAll('.lb-fold').forEach(b=>b.onclick=()=>{const open=b.getAttribute('aria-expanded')!=='true';b.setAttribute('aria-expanded',String(open));window.NulliusDisclosure.setHidden(document.getElementById(b.getAttribute('aria-controls')),open);}); + document.getElementById('reset-ask').onclick=()=>{document.getElementById('reset-confirm').hidden=false;document.getElementById('reset-ask').hidden=true;document.getElementById('reset-no').focus();}; + document.getElementById('reset-no').onclick=()=>{resetting=false;queued=false;document.getElementById('reset-confirm').hidden=true;document.getElementById('reset-ask').hidden=false;document.getElementById('reset-ask').focus();}; + document.getElementById('reset-yes').onclick=()=>save(true); + retry.onclick=()=>bar.dataset.kind==='conflict'?location.reload():save(resetting); + form.onsubmit=e=>e.preventDefault();render(); + /* an edit made just before leaving the page is still sent: the request outlives the page */ + addEventListener('pagehide',()=>{if(dirty&&!writing&&check().ok){clearTimeout(timer);save();}}); + + /* the switch between the two views: no page load; the address follows, so a reload or Back lands on the same view */ + const views={board:document.getElementById('lb-board-view'),scoring:form}, link=document.getElementById('lb-switch'), title=document.getElementById('lb-title'); + const paths={board:'/leaderboard',scoring:'/scoring'}; + function show(view, push) { + const other=view==='scoring'?'board':'scoring'; + views[view].hidden=false;views[other].hidden=true; + title.textContent=view==='scoring'?'Scoring settings':'Leaderboard';document.title=`${title.textContent} · Nullius`; + link.textContent=view==='scoring'?'Leaderboard':'Scoring settings';link.href=paths[other]; + if(push)history.pushState({view},'',paths[view]); + document.dispatchEvent(new CustomEvent('leaderboard:view',{detail:{view}})); + } + link.addEventListener('click',e=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.button)return;e.preventDefault();show(views.scoring.hidden?'scoring':'board',true);}); + addEventListener('popstate',()=>show(location.pathname.startsWith('/scoring')?'scoring':'board',false)); +})(); diff --git a/app/static/style.css b/app/static/style.css index 1c9fc3178..2726474cc 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -450,6 +450,8 @@ button.seg:hover { filter: brightness(1.25); } .table-wrap .grid .sticky-col { position: sticky; left: var(--sticky-left, 0); z-index: 2; background: var(--bg); } +/* a header's screen-reader name is placed against its cell, inside the scroll box, so it never widens the page */ +.table-wrap .grid th:not(.sticky-col) { position: relative; } .table-wrap .grid .sticky-col.sticky-edge { box-shadow: 1px 0 0 var(--border-soft); } .table-wrap .grid thead th.sticky-col { z-index: 4; background: var(--bg); } /* opaque sticky cells would hide the row hover, so repaint them to match */ diff --git a/app/static/tables.js b/app/static/tables.js index c6a8411be..4a13c5abd 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); @@ -440,7 +443,8 @@ window.NulliusTable = { change, not at load, a screen reader hears what shows once the changes pause, counted in the live region's data-noun. `drawn` runs after each page. Returns first(), to run after a filter or a sort: it - shows the first page. */ + shows the first page. A `table:show` event on the table, its detail.row a + row that passes, turns to the page that holds it. */ pager(table, key, passes = () => true, drawn = () => {}) { const bar = document.querySelector(`[data-pager="${CSS.escape(table.id)}"]`), empty = document.querySelector(`[data-empty="${CSS.escape(table.id)}"]`); const [per, note, prev, next, live] = ['[data-per]', '[data-note]', '[data-prev]', '[data-next]', '[data-live]'].map(s => bar.querySelector(s)); @@ -457,6 +461,7 @@ window.NulliusTable = { next.disabled = (page + 1) * n >= hit.length; empty.hidden = hit.length > 0; say(hit.length ? `${note.textContent} ${live.dataset.noun}` : empty.textContent); + table.dispatchEvent(new CustomEvent('table:drawn', {detail: {rows: hit}})); // the rows that pass, on any page drawn(); }; const first = () => { page = 0; draw(); }; @@ -466,6 +471,10 @@ window.NulliusTable = { }); prev.addEventListener('click', () => { page--; draw(); }); next.addEventListener('click', () => { page++; draw(); }); + table.addEventListener('table:show', e => { + const at = [...table.tBodies[0].rows].filter(passes).indexOf(e.detail.row), n = +per.value || 1; + if (at >= 0 && +per.value && Math.floor(at / n) !== page) { page = Math.floor(at / n); draw(); } + }); draw(); return first; }, diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg index 296181607..c2de2f5d3 100644 --- a/app/templates/_icons.svg +++ b/app/templates/_icons.svg @@ -9,7 +9,8 @@
- + diff --git a/app/templates/base.html b/app/templates/base.html index 063b355fc..6bb93fd5a 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -104,6 +104,7 @@ Runs Compare + Leaderboard
+ +## 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/README.md b/docs/cli/README.md index 533fd34c2..340746581 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -10,7 +10,7 @@ From a source checkout, replace `nullius` with | Page | Command | | --- | --- | | [Launch](../getting-started.md) | `nullius serve [roots...]` | -| [Read jobs](read-jobs.md) | `nullius runs`, `nullius compare`, `nullius workspace`, `nullius standard traces` | +| [Read jobs](read-jobs.md) | `nullius runs`, `nullius compare`, `nullius leaderboard`, `nullius workspace`, `nullius standard traces` | | [Import a run](import.md) | `nullius import` | | [Task flags](flags.md) | `nullius flags list`, `set`, `accept`, `remove`, `copy`, `import`, `feasibility` | | [Definitions](definitions.md) | `nullius standard list`, `check`, `fit`, `pins`, `new` | diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 7caed9c28..35c448d0d 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -11,6 +11,8 @@ Each page's command, or why there is none. | `/trial//` | `nullius runs show [--json]` | | A trial's Conversation, by call | `nullius runs show --calls` | | `/import`, `/use-path` | `nullius import -o [--json]`; `--list` | +| `/leaderboard` | `nullius leaderboard ... [--json]` | +| `/scoring` | Profile `scoring.json` beside `settings.json`; `nullius paths` locates its configuration directory | | `/compare` | `nullius compare ... [--matched] [--json]` | | `/workspaces/open/` | `nullius serve ...`, `WORKSPACE=` | | `/workspaces` | `nullius workspace list [--home DIR] [--json]` | diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index c3e19dfd5..addd1fe6c 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -68,3 +68,26 @@ nullius standard traces ./jobs ``` A trial that ended early kept no ACP events: its trace has the model calls, and its tool calls at their start, with no duration. + +## Leaderboard + +```bash +nullius leaderboard --help +nullius leaderboard --json +nullius leaderboard ./jobs --json +``` + +Supply the result roots of one workspace. This reads completed jobs; it never +launches work. Without roots, catalogue rows have no recorded-run measurements. Exit 0 means +the document was read; an invalid root exits 3, invalid arguments 2. + +The page and command use the same profile's [Scoring settings](../field-guide.md#leaderboard). +JSON includes agent/company/version and execution identity, benchmark entry +versions, all capability and domain weights, effective shares, ranks and +coverage notes, task evidence and selected run IDs. Scores are fractions; +text percentages use one decimal when needed. + +Time and cost include observed counts. The command also reads selected +trajectories for Steps and Tool calls; a missing or malformed trace leaves those +metrics unavailable. Invalid scoring settings use defaults with the same warning +as the page, without replacing the file. See the [scoring contract](../field-guide.md#leaderboard). diff --git a/docs/field-guide.md b/docs/field-guide.md index d86f8c911..5367087e6 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -160,7 +160,7 @@ How the agent worked, not whether it won. Computed over layer 3. | `is_running` | The job records running or pending trials. Numbers are partial. | measured | any | | `n_planned / n_retries` | Planned trials from the run record or task count, and retries recorded by the harness. Repeated attempts are separate trials, not retries. | measured | any | | `retries` | Retries a standard run allows each attempt (`--retries`); 0 elsewhere. | measured | any | -| `identity` | A standard run's setup: benchmark, agent, model, provider, limits. Empty elsewhere. | measured | any | +| `identity` | A standard run's setup: benchmark, agent, backend, model, provider, limits. Empty elsewhere. | measured | any | | `dataset` | The dataset folder, `name@version` for a registry fetch, or the task names' shared prefix. | measured | any | ## Trial metrics, one row per task attempt {#trials} @@ -287,3 +287,68 @@ Thirteen classes. The five marked **yes** under Infrastructure leave the adjuste - [Compare and judge runs](judgement.md) + +## 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, units at a time, a run's total spending cap and retries after +an infrastructure failure 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 unavailable rather than guessing aliases. +A dataset without a task list counts coverage against its declared task count, +by recorded task name. 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 +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. A pass^3 entry selects first among +the runs that recorded three attempts per task, whatever they scored. + +Each axis normalizes positive entry weights over available scores. Each family +(capabilities, domains) has its own Overall: positive axis weights normalized over +its measured axes. The Leaderboard ranks by the family it shows. 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. Each family needs a positive weight on a row that has a benchmark. + +Scoring settings, the Leaderboard's other view, autosave to `scoring.json` beside +`settings.json` (`nullius paths`). A file that cannot be read gives defaults with a warning +and is left intact. + +Every row with an Overall is ranked by it; ties, compared to twelve decimals, share +competition rank. +Incomplete or unknown coverage of the required verified entries across counted +axes is listed beside the rank as a note. +Removed entries and zero weights add no note. + +Average uses available row scores and reports the count. A row comparison uses +the shown family's shared measured axes 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; a row +that never measured the benchmark is unchanged. +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 bbe948b3f..d9abb3ba3 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -73,6 +73,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/` | diff --git a/pyproject.toml b/pyproject.toml index 3c3789794..e56d61a36 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", @@ -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"]