From ebeb7279f69d704572b6b20ded50fd775378e428 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Tue, 1 Dec 2026 14:38:47 +0100 Subject: [PATCH] feat(compare): read the Leaderboard from task labels and remove the Scoring weights Page, command, API and MCP tool read the labelled-task projection under one input contract: rows, shared or every task, hidden axes, benchmark versions and runs, unchecked-labels mode. The Scoring view, its routes, DEFAULT_ENTRIES, scopes.py and task_parts are removed. scoring.json is no longer read and is never converted or deleted. Closes #526 --- AGENTS.md | 2 +- app/.env.example | 1 + .../benchmarks/osworld1/standard.json | 20 +- app/nullius/cli.py | 2 +- app/nullius/client.py | 24 +- app/nullius/leaderboard/board.py | 226 +++++----- app/nullius/leaderboard/cli.py | 102 +++-- app/nullius/leaderboard/configuration.py | 188 --------- app/nullius/leaderboard/labels.py | 10 +- app/nullius/leaderboard/metrics.py | 14 +- app/nullius/leaderboard/projection.py | 36 +- app/nullius/leaderboard/scopes.py | 29 -- app/nullius/leaderboard/scoring.py | 151 ------- app/nullius/leaderboard/service.py | 87 ++-- app/nullius/leaderboard/weights.py | 28 +- app/nullius/mcp_server.py | 13 +- app/nullius/settings.py | 1 + app/nullius/standard/cli.py | 6 +- app/nullius/standard/contract/definitions.py | 32 +- app/packaging/verify.py | 2 +- app/site/mkdocs.yml | 1 + app/static/leaderboard/board.js | 307 ++++++++------ app/static/leaderboard/leaderboard.css | 79 +--- app/static/leaderboard/scoring.js | 142 ------- app/templates/base.html | 2 +- app/templates/leaderboard/_scoring.html | 12 - app/templates/leaderboard/board.html | 50 ++- app/tests/test_benchmarks.py | 2 + app/tests/test_client.py | 8 + app/tests/test_leaderboard_board.py | 225 +++++----- app/tests/test_leaderboard_labels.py | 15 + app/tests/test_leaderboard_scoring.py | 147 ------- app/tests/test_leaderboard_service.py | 157 ++++--- app/tests/test_leaderboard_weights.py | 145 ------- app/tests/test_standard_definitions.py | 22 +- app/ui_tests/browser/leaderboard.py | 395 ++++++------------ app/ui_tests/browser/mutations.py | 6 +- app/ui_tests/test_api.py | 43 +- app/ui_tests/test_leaderboard_routes.py | 253 ++++++----- app/web/api.py | 16 +- app/web/leaderboard.py | 75 +--- docs/api.md | 8 +- docs/benchmarks/add-manually.md | 10 - docs/cli/pages.md | 3 +- docs/cli/read-jobs.md | 35 +- docs/field-guide.md | 143 ++++--- docs/releases/next.md | 3 + docs/settings/README.md | 3 +- 48 files changed, 1152 insertions(+), 2129 deletions(-) delete mode 100644 app/nullius/leaderboard/configuration.py delete mode 100644 app/nullius/leaderboard/scopes.py delete mode 100644 app/nullius/leaderboard/scoring.py delete mode 100644 app/static/leaderboard/scoring.js delete mode 100644 app/templates/leaderboard/_scoring.html delete mode 100644 app/tests/test_leaderboard_scoring.py delete mode 100644 app/tests/test_leaderboard_weights.py create mode 100644 docs/releases/next.md diff --git a/AGENTS.md b/AGENTS.md index 95d77197b..00d39be78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +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/leaderboard/` | Reading `labels.json`, scoring each axis over its labelled tasks, the board's selection | | `app/nullius/catalogue/` | A folder per entry under `benchmarks/`, `agents/`, `modules/`: 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/.env.example b/app/.env.example index aedd50d4b..5053bf3a6 100644 --- a/app/.env.example +++ b/app/.env.example @@ -14,6 +14,7 @@ # WORKSPACE: the name the start-up roots open as (or the picker's name field) # DATASET_ROOTS: local dataset checkouts to look in for task files # DEBUG: the Werkzeug debugger (or --no-debug) +# LEADERBOARD_UNCHECKED_LABELS: whether the Leaderboard counts task labels not checked at a run's benchmark version: omit (default) or include # RUNS_DIR: where runs started from the builder keep their script, log and job (default runs/ in the user data directory) # HARBOR_PINS: where the Harbor a recipe pins is built and kept on this machine (default harbor-pins/ beside the runs) # STANDARD_DIR: where the Nullius standard installs agents, Modules and benchmark upstreams (default standard/ in the user data directory) diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 85d611fd0..0f2d64f52 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -405,23 +405,5 @@ "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/cli.py b/app/nullius/cli.py index b815dd7c3..40da8638f 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -15,7 +15,7 @@ "serve": "open the web application", "runs": "inspect run output", "compare": "compare runs", - "leaderboard": "workspace composite agent scores", + "leaderboard": "workspace agent scores over labelled tasks", "flags": "write a run's task flags", "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", diff --git a/app/nullius/client.py b/app/nullius/client.py index f669c4276..ac11cf993 100644 --- a/app/nullius/client.py +++ b/app/nullius/client.py @@ -138,10 +138,14 @@ def artifact(self, job_id: str, trial: str, key: str, workspace: Optional[str] = def compare(self, *job_ids: str, matched: bool = False, workspace: Optional[str] = None) -> dict: return self.request("GET", "/compare", job=list(job_ids), matched=matched, workspace=workspace) - def leaderboard(self, workspace: Optional[str] = None) -> dict: - """The workspace's agents ranked by their composite score, under the server's Scoring settings; ``steps`` and - ``calls`` stay uncounted.""" - return self.request("GET", "/leaderboard", workspace=workspace) + def leaderboard(self, workspace: Optional[str] = None, *, rows=None, every_task: bool = False, hide_axes=(), show_axes=(), + hide_versions=(), hide_runs=(), unchecked_labels: Optional[str] = None) -> dict: + """The workspace's Leaderboard: each row over its labelled tasks, by axis. ``rows``: the keys of the rows + compared on shared tasks, every row by default; ``every_task``: the view asked, never ranked; the rest + leaves an axis, a ``benchmark@version`` or a run out. ``steps`` and ``calls`` stay uncounted.""" + return self.request("GET", "/leaderboard", workspace=workspace, row=list(rows or ()), tasks="every" if every_task else None, + hide_axis=list(hide_axes), show_axis=list(show_axes), hide_version=list(hide_versions), + hide_run=list(hide_runs), unchecked=unchecked_labels) # judgements: reading one is free, asking is a paid model call for each trial @@ -267,8 +271,14 @@ def main(argv=None) -> int: p.add_argument("job_ids", nargs="+") p.add_argument("--matched", action="store_true") p.add_argument("--workspace") - p = sub.add_parser("leaderboard", help="the workspace's agents ranked by composite score") + p = sub.add_parser("leaderboard", help="the workspace's agents over their labelled tasks, ranked on shared tasks") p.add_argument("--workspace") + p.add_argument("--row", dest="rows", action="append", metavar="KEY") + p.add_argument("--every-task", action="store_true") + for flag, dest, value in (("hide-axis", "hide_axes", "AXIS"), ("show-axis", "show_axes", "AXIS"), + ("hide-version", "hide_versions", "BENCHMARK@VERSION"), ("hide-run", "hide_runs", "ID")): + p.add_argument(f"--{flag}", dest=dest, action="append", default=[], metavar=value) + p.add_argument("--unchecked-labels", choices=("omit", "include")) p = sub.add_parser("judgements", help="a judge's records for a job") p.add_argument("job_id") p.add_argument("--lane", choices=("decision", "llm"), default="decision") @@ -320,7 +330,9 @@ def main(argv=None) -> int: "jobs": lambda: nx.jobs(a.workspace), "job": lambda: nx.trial(a.job_id, a.trial, a.workspace) if a.trial else nx.job(a.job_id, a.workspace), "compare": lambda: nx.compare(*a.job_ids, matched=a.matched, workspace=a.workspace), - "leaderboard": lambda: nx.leaderboard(a.workspace), + "leaderboard": lambda: nx.leaderboard(a.workspace, rows=a.rows, every_task=a.every_task, hide_axes=a.hide_axes, + show_axes=a.show_axes, hide_versions=a.hide_versions, hide_runs=a.hide_runs, + unchecked_labels=a.unchecked_labels), "judgements": lambda: nx.judgements(a.job_id, a.lane, a.workspace), "judge": lambda: (nx.judge(a.job_id, a.trial, a.lane, a.workspace) if a.trial else nx.judge_job(a.job_id, a.lane, confirm=a.yes, workspace=a.workspace)), diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py index 791530fee..b7dabc2d2 100644 --- a/app/nullius/leaderboard/board.py +++ b/app/nullius/leaderboard/board.py @@ -1,51 +1,25 @@ -"""One workspace's composite scores, evidence, coverage and rank requirements.""" +"""One workspace's Leaderboard: its rows, each axis over its labelled tasks (``projection``), ranks and the selection. + +One input contract, for the page, the command, the API and the MCP tool. ``rows``: the keys of the rows compared +on shared tasks; None is every row with an evaluated task, and an unknown key is refused. ``tasks``: the view asked, +``shared`` or ``every``; a row holds both. The selection: ``hide_axes``, ``show_axes`` for those hidden unless asked +(``labels.HIDDEN``), ``hide_versions`` as ``benchmark@version``, ``hide_runs``. A hidden run or version is left out +before anything is scored, so another run may count; a hidden axis leaves Overall. ``unchecked``: ``labels.UNCHECKED``. + +A row is ranked in the shared view alone, by its family's Overall Resolved: asked for ``every``, no row has a rank. +Runs set aside are said once per benchmark +version. +""" 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 +from . import labels as labelling, projection, weights + +TASKS = ("shared", "every") def row_identity(job): @@ -66,24 +40,41 @@ 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 _metrics(trials): + """Time and cost per attempt over these trials, each with how many recorded it; steps and calls are read later.""" + out = {name: {"value": None, "count": 0} for name in ("time", "cost", "steps", "calls")} + for metric, field in (("time", "dur_agent"), ("cost", "cost_usd")): + values = [v for v in (getattr(t, field) for t in trials) if v is not None and isfinite(v) and v >= 0] + mean = sum(values) / len(values) if values else None + out[metric] = {"value": mean if mean is None or isfinite(mean) else None, "count": len(values)} + return out -def _entry_key(entry): - return tuple(entry.get(k, "") for k in ("benchmark", "dataset", "version", "metric")) +def _pass3(estimate, name): + """pass^3 as a row or an axis shows it, ``[{name, value, n}]``: over all the tasks when they recorded three attempts + (``name`` ""), else each benchmark version that did, apart; none is too few attempts.""" + reads = lambda e: bool(e) and 3 in e["hat"] + if reads(estimate["all"]): + return [{"name": "", "value": estimate["all"]["hat"][3], "n": estimate["all"]["units"]}] + return [{"name": name(b["benchmark"], b["version"]), "value": b["pass_k"]["hat"][3], "n": b["pass_k"]["units"]} + for b in estimate["benchmarks"] if reads(b["pass_k"])] -def build(jobs, agents, benchmarks, settings, *, workspace_open=True, metric_sources=None): +def build(jobs, agents, benchmarks, labels, *, rows=None, tasks="shared", hide_axes=(), show_axes=(), hide_versions=(), + hide_runs=(), unchecked="omit", listings=None, 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) + if tasks not in TASKS: + raise ValueError(f"tasks: {' or '.join(TASKS)}") + unknown = [a for a in (*hide_axes, *show_axes) if a not in labelling.AXES] + if unknown: + raise ValueError(f"unknown axis {unknown[0]}") + shown = [a for a in labelling.AXES if a not in hide_axes and (a not in labelling.HIDDEN or a in show_axes)] 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: + if not projection.eligible(job) or identity["agent"] not in agents_by: continue key = key_for(identity) grouped.setdefault(key, []).append(job) @@ -97,90 +88,61 @@ def build(jobs, agents, benchmarks, settings, *, workspace_open=True, metric_sou identity = {"agent": agent["key"], "version": agent.get("_version", ""), "catalogue_only": True} key = key_for(identity) grouped[key], identities[key] = [], identity - rows = [] + at = lambda j: (j.identity.get("benchmark") or "", j.identity.get("benchmark_version") or "") + kept = lambda j: j.job_id not in hide_runs and "@".join(at(j)) not in hide_versions + trials = {} + got = projection.project({key: [j for j in runs if kept(j)] for key, runs in grouped.items()}, benchmarks, labels, + cohort=rows, axes=shown, unchecked=unchecked, listings=listings, trials=trials) + names = {(b["key"], definitions.version_identity(b)): (b["label"], definitions.version_label(b)) for b in benchmarks} + + def name(benchmark, version): + # a reader names a version by its release or short commit, never the whole pin + label, said = names.get((benchmark, version), (benchmark, "")) + return " ".join(filter(None, (label, said or version[:7]))) + + out, aside = [], {} for key, runs in grouped.items(): - identity = identities[key] + identity, projected = identities[key], got["rows"][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) + row = {"key": key, "agent": identity["agent"], "name": agent["label"], "company": agent.get("company", ""), + "version": identity["version"], "version_label": definitions.version_label(matching) if matching else identity["version"], + "identity": identity, "has_runs": bool(runs), "runs": projected["runs"], "evaluated": projected["evaluated"], "rank": {}, + # a run set aside is said once for its benchmark version, below + "warnings": [w for w in projected["warnings"] if ": set aside, " not in w], + "coverage": projected["coverage"], "shared": projected["shared"], "every": projected["every"]} + for view in TASKS: + if row[view]: + row[view]["metrics"] = {family: _metrics(ts) for family, ts in trials[key][view].items()} + row[view]["pass3"] = _pass3(row[view]["pass_k"], name) + row[view]["evidence"]["pass3"] = {a: _pass3(e, name) for a, e in row[view]["evidence"]["pass_k"].items()} 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 ""} + metric_sources[key] = {view: {family: tuple(dict.fromkeys(t.trajectory_path for t in ts)) for family, ts in families.items()} + for view, families in trials[key].items() if row[view]} + for j in runs: + if kept(j) and all(at(j)) and j.job_id not in projected["runs"]: + aside.setdefault(at(j), []).append(j.job_id) + out.append(row) + for family in labelling.FAMILIES: + # the every-task view is never ranked: its rows come evaluated first, then by name + ranks = weights.competition([r for r in out if r["shared"]], lambda r: r["shared"]["overall"][family]["resolved"]) if tasks == "shared" else {} + for row in out: + row["rank"][family] = ranks.get(row["key"]) + out.sort(key=lambda r: (r["rank"]["capabilities"] is None, r["rank"]["capabilities"] or 0, not r["evaluated"], r["name"], r["key"])) + compared = next((r["shared"] for r in out if r["shared"]), None) + recorded = sorted({(at(j), j.job_id, key, j.dataset) for key, runs in grouped.items() for j in runs if all(at(j))}) + counted = {id for r in out for id in r["runs"]} + return {"rows": out, "tasks": tasks, "unchecked": got["unchecked"], "cohort": got["cohort"], + "axes": shown, "hidden": [a for a in labelling.AXES if a not in shown], + **{family: [a for a in axes if a in shown] for family, axes in labelling.FAMILIES.items()}, + "n": got["n"], "n_overall": {family: compared["overall"][family]["n"] if compared else 0 for family in labelling.FAMILIES}, + "warnings": got["warnings"] + [f"{name(*version)}: {len(ids)} {'run' if len(ids) == 1 else 'runs'} set aside. Hide a run to count another." + for version, ids in sorted(aside.items())], + "set_aside": [{"benchmark": b, "version": v, "runs": sorted(ids)} for (b, v), ids in sorted(aside.items())], + "versions": [{"id": "@".join(version), "name": name(*version), "hidden": "@".join(version) in hide_versions} + for version in sorted({version for version, *_ in recorded})], + "runs": [{"id": id, "row": key, "benchmark": name(*version), "version": "@".join(version), "dataset": dataset, + "hidden": id in hide_runs, "counts": id in counted} for version, id, key, dataset in recorded], + "selected": out[0]["key"] if out 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 out) + else "" if any(r["every"]["overall"][family]["n"] for r in out for family in labelling.FAMILIES) else "No labelled task in the runs shown"} diff --git a/app/nullius/leaderboard/cli.py b/app/nullius/leaderboard/cli.py index 22ddff045..c092049d9 100644 --- a/app/nullius/leaderboard/cli.py +++ b/app/nullius/leaderboard/cli.py @@ -1,4 +1,4 @@ -"""Read workspace composite scores without launching evaluations.""" +"""Read a workspace's Leaderboard without launching evaluations: each axis over its labelled tasks.""" from __future__ import annotations import argparse @@ -7,46 +7,88 @@ import sys from nullius.runs import parse -from . import configuration, service, weights +from . import labels as labelling, service, weights + + +def options(parser): + """The Leaderboard's input contract as options, the page's query string by other names.""" + parser.add_argument("--row", dest="rows", action="append", metavar="KEY", help="compare only these rows on shared tasks; default: every row with an evaluated task") + parser.add_argument("--every-task", dest="tasks", action="store_const", const="every", default="shared", help="each row over every task it evaluated: not comparable, never ranked") + parser.add_argument("--hide-axis", dest="hide_axes", action="append", default=[], metavar="AXIS", help="leave an axis out, of Overall too") + parser.add_argument("--show-axis", dest="show_axes", action="append", default=[], metavar="AXIS", help=f"show an axis hidden by default: {', '.join(labelling.HIDDEN)}") + parser.add_argument("--hide-version", dest="hide_versions", action="append", default=[], metavar="BENCHMARK@VERSION", help="leave a benchmark version's runs out") + parser.add_argument("--hide-run", dest="hide_runs", action="append", default=[], metavar="ID", help="leave a run out, so another may count") + parser.add_argument("--unchecked-labels", dest="unchecked", choices=labelling.UNCHECKED, help=f"task labels not checked at a run's benchmark version; default: LEADERBOARD_UNCHECKED_LABELS, else omit") + + +def chosen(args) -> dict: + return {name: getattr(args, name) for name in (*service.QUERY.values(), "tasks", "unchecked")} + + +def _rates(cell): + return f"{weights.percent(cell['resolved'])} · mean score {weights.percent(cell['mean_score'])}" + + +def _pass3(parts): + return " · ".join(f"{p['name'] + ' ' if p['name'] else ''}{weights.percent(p['value'])} of {p['n']} tasks" for p in parts) or "too few attempts" + + +def _lines(result, row): + view, shared = row[result["tasks"]], result["tasks"] == "shared" + yield f" key {row['key']}" + setup = " · ".join(str(row["identity"][key]) for key in ("model", "effort") if row["identity"].get(key)) + if setup: + yield f" {setup}" + # a row outside the view still says why: a run that cannot score has its warning + for warning in row["warnings"]: + yield f" Warning: {warning}" + if not view: + return + counted = lambda cell: f"{cell['n']} shared" if shared else f"{cell['n']} tasks, not comparable" + for family in labelling.FAMILIES: + cell, rank = view["overall"][family], row["rank"][family] + yield f" {family.capitalize()} overall: {_rates(cell) + ' · ' if cell['n'] else ''}{counted(cell)}" + (f" · rank {rank}" if rank else "") + yield f" pass^3: {_pass3(view['pass3'])}" + for axis in result["axes"]: + cell, coverage = view["axes"][axis], row["coverage"][axis] + labelled = "?" if coverage["labelled"] is None else coverage["labelled"] + yield (f" {axis}: {_rates(cell) + ' · ' if cell['n'] else ''}{counted(cell)} · coverage {coverage['evaluated']} of {labelled}" + f" · pass^3 {_pass3(view['evidence']['pass3'][axis])}") + for part in cell["benchmarks"]: + name = next(v["name"] for v in result["versions"] if v["id"] == f"{part['benchmark']}@{part['version']}") + yield f" {name}: {_rates(part)} · {part['n']} tasks · runs {', '.join(part['runs'])}" + for family in labelling.FAMILIES: + for metric, data in view["metrics"][family].items(): + yield f" {family.capitalize()} {metric} per attempt: {data['value'] if data['value'] is not None else 'unavailable'} ({data['count']} observed)" 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.") + epilog="Exit 0: read; 2: usage, an unknown row or axis; 3: missing root. Rows are compared on the tasks they all evaluated; --json holds both views.") 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") + options(parser) + parser.add_argument("--json", action="store_true", help="full precision: rows and their keys, both views, N, ranks, coverage, pass^k, runs, warnings 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) + try: + result = service.document(service.qualified(parse.load_all(args.roots)), workspace_open=bool(args.roots), deferred=True, **chosen(args)) + except ValueError as error: + print(error, file=sys.stderr) + return 2 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 + for line in filter(None, (result["notice"], *result["warnings"], result["empty"])): + print(line) + shared = result["tasks"] == "shared" + print(("Shared tasks" if shared else "Every task (not comparable)") + f" · unchecked labels: {result['unchecked']}") + for row in result["rows"]: + overall = row[result["tasks"]]["overall"]["capabilities"]["resolved"] if row[result["tasks"]] else None + print(f"{row['rank']['capabilities'] or ''}\t{row['name']}\t{row['company']}\t{row['version_label']}\t{weights.percent(overall)}") + for line in _lines(result, row): + print(line) return 0 diff --git a/app/nullius/leaderboard/configuration.py b/app/nullius/leaderboard/configuration.py deleted file mode 100644 index 54d6adac1..000000000 --- a/app/nullius/leaderboard/configuration.py +++ /dev/null @@ -1,188 +0,0 @@ -"""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/labels.py b/app/nullius/leaderboard/labels.py index 52eed7976..90f842122 100644 --- a/app/nullius/leaderboard/labels.py +++ b/app/nullius/leaderboard/labels.py @@ -14,13 +14,15 @@ from dataclasses import dataclass from nullius.standard.contract import definitions -from . import configuration FILE = "labels.json" SCHEMA = 1 -# The board's axes, and four it does not show yet. The label skill's definitions.json names the same ones. -CAPABILITIES = configuration.CAPABILITIES + ("Reasoning", "Abstention", "Exactness") -DOMAINS = configuration.DOMAINS + ("Coding",) +# The board's axes; it shows the last three capabilities and the last domain only when asked. The label skill's +# definitions.json names the same ones. +CAPABILITIES = ("Memory", "Safety", "Consistency", "Personalization", "Proactivity", "Retrieval", "Communication", "Execution", + "Reasoning", "Abstention", "Exactness") +DOMAINS = ("Travel", "Dining", "Shopping", "Money", "Health", "Home", "Work", "Coding") +HIDDEN = ("Reasoning", "Abstention", "Exactness", "Coding") FAMILIES = {"capabilities": CAPABILITIES, "domains": DOMAINS} AXES = CAPABILITIES + DOMAINS UNCHECKED = ("omit", "include") diff --git a/app/nullius/leaderboard/metrics.py b/app/nullius/leaderboard/metrics.py index ff0092e60..0c9d0933b 100644 --- a/app/nullius/leaderboard/metrics.py +++ b/app/nullius/leaderboard/metrics.py @@ -37,11 +37,17 @@ def read(self, path): return dict(result) def complete(self, document, sources): + """Steps and tool calls of each row's views, by family, from the trajectories ``board.build`` named, each + read once however many views and families hold it.""" + seen = {} 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)} + for view, families in sources.get(row["key"], {}).items(): + for family, paths in families.items(): + seen.update((path, self.read(path)) for path in paths if path not in seen) + observations = [seen[path] for path in paths] + for field in ("steps", "calls"): + values = [o[field] for o in observations if o[field] is not None] + row[view]["metrics"][family][field] = {"value": sum(values) / len(values) if values else None, "count": len(values)} CACHE = Cache() diff --git a/app/nullius/leaderboard/projection.py b/app/nullius/leaderboard/projection.py index 0736c35af..356972499 100644 --- a/app/nullius/leaderboard/projection.py +++ b/app/nullius/leaderboard/projection.py @@ -1,4 +1,4 @@ -"""Each axis scored over the tasks labelled with it. No page shows this yet; it reads no file. +"""Each axis scored over the tasks labelled with it. It reads no file. A task is ``Job.task_id`` with its dataset replaced by the one its list is cut from (``subset_of``), so a cut's tasks are the whole dataset's. Two versions of a benchmark are two sets of tasks: nothing pools across them, and a @@ -30,7 +30,7 @@ from nullius.runs import attempts, classify from nullius.standard.contract import definitions -from . import labels as labelling, scoring +from . import labels as labelling @dataclass(frozen=True) @@ -44,6 +44,10 @@ class Task: repeats: bool = False # its run passes or fails tasks, so pass^k reads it +def eligible(job) -> bool: + return bool(job.finished_at and not job.is_running and not job.is_preparing and not job.is_control) + + def _recency(job): at = job.finished_at return -(at if at.tzinfo else at.replace(tzinfo=timezone.utc)).timestamp(), job.job_id @@ -53,7 +57,7 @@ def select(jobs) -> tuple[list, list]: """One row's runs that count, most recent first, and a warning for each one that does not.""" pools = {} for j in jobs: - if scoring.eligible(j) and j.identity.get("benchmark"): + if eligible(j) and j.identity.get("benchmark"): pools.setdefault((j.identity["benchmark"], j.identity.get("benchmark_version", ""), j.dataset), []).append(j) winners, warnings = [], [] for (benchmark, version, dataset), runs in pools.items(): @@ -138,14 +142,14 @@ def _pass_k(tasks): def _cell(tasks): - """One cell over evaluated tasks: both rates, and each benchmark version apart. Two versions of one benchmark - are two data points: the cell then has no rate of its own.""" + """One cell over evaluated tasks: both rates, and each benchmark version apart, with the runs its tasks come + from. Two versions of one benchmark are two data points: the cell then has no rate of its own.""" by = {} for t in tasks: by.setdefault(t.id[:2], []).append(t) apart = len({b for b, _ in by}) < len(by) return dict(_rates(tasks), **({"resolved": None, "mean_score": None} if apart else {}), - benchmarks=[dict(benchmark=b, version=v, **_rates(ts)) for (b, v), ts in by.items()]) + benchmarks=[dict(benchmark=b, version=v, runs=sorted({t.job_id for t in ts}), **_rates(ts)) for (b, v), ts in by.items()]) def _view(tasks, shown): @@ -158,11 +162,12 @@ def _view(tasks, shown): def project(rows: Mapping[str, Sequence], benchmarks: Sequence[dict], labels: Mapping[str, labelling.Labels], *, cohort: Sequence[str] | None = None, axes: Sequence[str] = labelling.AXES, unchecked: str = "omit", - listings: Mapping[tuple, Sequence[str]] | None = None) -> dict: + listings: Mapping[tuple, Sequence[str]] | None = None, trials: dict | None = None) -> dict: """``rows``: each row's runs by its key. ``benchmarks``: every version, resolved. ``labels``: ``labels.load``'s. - ``cohort``: the rows compared on shared tasks; None is every row with an evaluated task, and an unknown key is - refused. ``axes``: those shown; another leaves Overall. ``listings``: the unit ids of - (benchmark, version, dataset), for coverage.""" + ``cohort``: the rows compared on shared tasks; None is every row with an evaluated task of a shown axis, and an + unknown key is refused. ``axes``: those shown; another leaves Overall. ``listings``: the unit ids of + (benchmark, version, dataset), for coverage. ``trials``, when given, takes each row's attempts that ran of the + evaluated tasks a shown axis of each family holds, by view: what its time and cost are read from.""" if unchecked not in labelling.UNCHECKED: raise ValueError(f"unchecked labels: {' or '.join(labelling.UNCHECKED)}") unknown = [k for k in cohort or () if k not in rows] @@ -184,7 +189,9 @@ def axes_of(tid): per_row = {key: _tasks(jobs, whole, axes_of) for key, jobs in rows.items()} evaluated = {key: {tid for tid, t in tasks.items() if t.resolved is not None} for key, (tasks, _, _) in per_row.items()} - cohort = list(dict.fromkeys(cohort)) if cohort is not None else [k for k in rows if evaluated[k]] + # nothing asked: the rows a shown axis can score; one with other tasks only would leave no task shared + cohort = (list(dict.fromkeys(cohort)) if cohort is not None else + [k for k in rows if any(per_row[k][0][tid].axes & set(axes) for tid in evaluated[k])]) shared = set.intersection(*(evaluated[k] for k in cohort)) if cohort else set() seen = sorted({(j.identity["benchmark"], j.identity["benchmark_version"]) for _, runs, _ in per_row.values() for j in runs}) warnings = [] @@ -236,9 +243,14 @@ def total(runs, axis): out = {} for key, (tasks, runs, said) in per_row.items(): - out[key] = {"runs": [j.job_id for j in runs], "warnings": said, "every": _view(list(tasks.values()), axes), + out[key] = {"runs": [j.job_id for j in runs], "warnings": said, "evaluated": len(evaluated[key]), + "every": _view(list(tasks.values()), axes), "shared": _view([t for tid, t in tasks.items() if tid in shared], axes) if key in cohort else None, "coverage": {a: {"evaluated": sum(a in tasks[tid].axes for tid in evaluated[key]), "labelled": total(runs, a)} for a in axes}} + if trials is not None: + ran = lambda view: {family: [t for task in view if task.resolved is not None and task.axes & set(names) & set(axes) + for t in attempts.ran(task.trials)] for family, names in labelling.FAMILIES.items()} + trials[key] = {"every": ran(tasks.values()), "shared": ran([t for tid, t in tasks.items() if tid in shared])} return {"unchecked": unchecked, "axes": list(axes), "cohort": cohort, "warnings": warnings, "rows": out, "n": {a: sum(a in axes_of(tid) for tid in shared) for a in axes}} diff --git a/app/nullius/leaderboard/scopes.py b/app/nullius/leaderboard/scopes.py deleted file mode 100644 index 81e608434..000000000 --- a/app/nullius/leaderboard/scopes.py +++ /dev/null @@ -1,29 +0,0 @@ -"""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 deleted file mode 100644 index 55a84e7bd..000000000 --- a/app/nullius/leaderboard/scoring.py +++ /dev/null @@ -1,151 +0,0 @@ -"""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 index 4fc1b5ea1..29f873e40 100644 --- a/app/nullius/leaderboard/service.py +++ b/app/nullius/leaderboard/service.py @@ -1,4 +1,4 @@ -"""Catalogue and profile inputs shared by the Leaderboard page and command.""" +"""Catalogue and profile inputs shared by the Leaderboard page, command and API.""" from __future__ import annotations import hashlib @@ -6,22 +6,35 @@ import os from collections import Counter from dataclasses import replace +from pathlib import Path from urllib.parse import quote +from nullius import paths from nullius.standard.contract import definitions -from . import board, configuration, metrics, weights, scopes +from nullius.standard.runner import units +from . import board, labels as labelling, metrics + +# a query string's names for ``board.build``'s lists, each repeated +QUERY = {"row": "rows", "hide_axis": "hide_axes", "show_axis": "show_axes", "hide_version": "hide_versions", "hide_run": "hide_runs"} +NOTICE = "Saved Scoring weights are no longer used. scoring.json is kept where it is." 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 selection(args) -> dict: + """``board.build``'s inputs from a query string, the page's and the API's: ``?row=KEY&tasks=every&hide_axis=A& + show_axis=A&hide_version=BENCHMARK@VERSION&hide_run=ID&unchecked=include``. No ``row`` is every row; an empty + ``row=`` alone is none.""" + chosen = {name: [v for v in dict.fromkeys(args.getlist(key)) if v] for key, name in QUERY.items()} + return dict(chosen, rows=chosen["rows"] if "row" in args else None, tasks=args.get("tasks") or "shared", unchecked=args.get("unchecked") or None) + + +def unchecked_default() -> str: + """Whether labels not checked at a run's version count when nothing says: the setting, else omit.""" + value = os.environ.get("LEADERBOARD_UNCHECKED_LABELS", "") + return value if value in labelling.UNCHECKED else labelling.UNCHECKED[0] def qualified(jobs): @@ -32,40 +45,38 @@ def under(job, 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 listings(benchmarks, jobs) -> dict: + """The task ids of each whole dataset of the versions these runs record, from the listings already made + (``units.cache_path``). Nothing is listed here: a dataset never listed has no entry.""" + seen = {(j.identity.get("benchmark"), j.identity.get("benchmark_version")) for j in jobs} + out = {} + for b in benchmarks: + version = (b["key"], definitions.version_identity(b)) + for d in b.get("datasets") or [] if version in seen else []: + if d.get("subset_of"): + continue + try: + with open(units.cache_path(b, d, units.option_values(b, d["id"])), encoding="utf-8") as f: + out[(*version, d["id"])] = [t["id"] for t in json.load(f)["tasks"]] + except (OSError, ValueError, KeyError, TypeError, units.Refused): + pass + return out -def document(jobs, *, workspace="", workspace_open=False, deferred=False): +def document(jobs, *, workspace="", workspace_open=False, deferred=False, unchecked=None, **chosen): + """The Leaderboard's document under ``board.build``'s input contract; ``unchecked`` None is the setting's.""" 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"]] + result = board.build(jobs, agents, benchmarks, labelling.load(benchmarks), listings=listings(benchmarks, jobs), workspace_open=workspace_open, + metric_sources=sources, unchecked=unchecked or unchecked_default(), **chosen) + # what a late answer is checked against: everything asked and everything read, before the deferred counts + result["context"] = hashlib.sha256(json.dumps([workspace, result], sort_keys=True, default=str).encode()).hexdigest() + # v0.3.0 saved its weights here: nothing reads the file, converts it or removes it + result["notice"] = NOTICE if (Path(paths.config_dir()) / "scoring.json").exists() else "" + for run in result["runs"]: + # a run told apart by its folder (qualified) has no page of its own: its name opens the first of that name + run["url"] = "" if os.path.isabs(run["id"]) else ("/job/" + quote(run["id"], safe="") + + ("?workspace=" + quote(workspace, safe="") if workspace else "")) if deferred: metrics.CACHE.complete(result, sources) return result diff --git a/app/nullius/leaderboard/weights.py b/app/nullius/leaderboard/weights.py index cea728fab..1a3d498e7 100644 --- a/app/nullius/leaderboard/weights.py +++ b/app/nullius/leaderboard/weights.py @@ -1,16 +1,7 @@ -"""Measured weight shares, percentage formatting and competition ranking.""" +"""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 "—" @@ -30,20 +21,3 @@ def competition(rows, value): 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/mcp_server.py b/app/nullius/mcp_server.py index f6ffa7213..ce05ea4da 100644 --- a/app/nullius/mcp_server.py +++ b/app/nullius/mcp_server.py @@ -19,6 +19,7 @@ PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") # ours first _S, _I, _B = {"type": "string"}, {"type": "integer"}, {"type": "boolean"} +_LIST = {"type": "array", "items": _S} _JOB = {"job_id": dict(_S, description="a job id, as list_jobs returns it")} _TRIAL = {**_JOB, "trial": dict(_S, description="a trial name of that job, as get_job returns it")} _RECIPE = {"recipe": {"description": "a saved recipe's id or name (list_recipes), or a whole recipe object"}} @@ -45,9 +46,15 @@ {"job_ids": {"type": "array", "items": _S, "minItems": 2}, "matched": dict(_B, description="only the tasks every job ran")}, ["job_ids"], lambda nx, a: nx.compare(*a["job_ids"], matched=a.get("matched") is True)), - "get_leaderboard": ("The open workspace's agents that have a scored run, ranked by composite score: each one's overall " - "score, rank and score by axis, with the runs each score reads. A score is partial when `reasons` " - "says so.", {}, [], lambda nx, a: _ranked(nx.leaderboard())), + "get_leaderboard": ("The open workspace's agents that have a run, each over its labelled tasks by axis: Resolved, Mean score, " + "N, rank, coverage, pass^k and the runs read. Rows are compared on the tasks they all evaluated " + "(`shared`); `every` holds each row's own tasks, not comparable. `rows` is applied before scoring.", + {"rows": dict(_LIST, description="row keys to compare; default: every row with an evaluated task"), + "every_task": dict(_B, description="ask the every-task view: never ranked"), + "hide_axes": _LIST, "show_axes": dict(_LIST, description="axes hidden by default"), + "hide_versions": dict(_LIST, description="benchmark@version"), "hide_runs": _LIST, + "unchecked_labels": dict(_S, enum=["omit", "include"])}, [], + lambda nx, a: _ranked(nx.leaderboard(**{k: v for k, v in a.items() if v is not None}))), "get_judgements": ("A judge model's stored answers about a job's trials (lane: decision or llm). Free to read.", {**_JOB, "lane": _S}, ["job_id"], lambda nx, a: nx.judgements(a["job_id"], a.get("lane") or "decision")), "judge_trial": ("Ask a judge model about one trial. A paid model call: ask only when the person wants it.", diff --git a/app/nullius/settings.py b/app/nullius/settings.py index c3f0b7e46..4d053cca1 100644 --- a/app/nullius/settings.py +++ b/app/nullius/settings.py @@ -239,6 +239,7 @@ def validate(self, value: str) -> Optional[str]: "WORKSPACE": "the name the start-up roots open as (or the picker's name field)", "DATASET_ROOTS": "local dataset checkouts to look in for task files", "DEBUG": "the Werkzeug debugger (or --no-debug)", + "LEADERBOARD_UNCHECKED_LABELS": "whether the Leaderboard counts task labels not checked at a run's benchmark version: omit (default) or include", "RUNS_DIR": "where runs started from the builder keep their script, log and job (default runs/ in the user data directory)", "HARBOR_PINS": "where the Harbor a recipe pins is built and kept on this machine (default harbor-pins/ beside the runs)", "STANDARD_DIR": "where the Nullius standard installs agents, Modules and benchmark upstreams (default standard/ in the user data directory)", diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 2c135b3fa..16108ffe7 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -271,13 +271,17 @@ def cmd_check(a): try: d = definitions.read_document(a.path, kind) bad = definitions.problems(dict(d, _here=os.path.dirname(os.path.abspath(a.path))), kind) + notes = definitions.warnings(d, kind) except (OSError, ValueError) as e: - bad = [str(e)] + bad, notes = [str(e)], [] else: got, bad = _all() + notes = list(dict.fromkeys(w for found in got.values() for d in found for w in d.get("_warnings", []))) for k in definitions.kits(): bad += [f"kit {k['key']}: {p}" for p in definitions.problems(k, "benchmark")] bad += catalogue_problems(got["benchmark"]) + for w in notes: # said, never counted: the definition still loads + print(f"warning: {w}") for b in bad: print(b) print("ok" if not bad else f"{len(bad)} problem(s)") diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 09ec8baa3..434a3fa2a 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -171,8 +171,10 @@ def setup_label(bench, which): VERSIONED = ("upstream", "install", "start", "model", "env", "options", "caches", "fidelity", "proven") MAX_RETRIES = 9 # the most retries of a failed attempt (runner.retries, cli run --retries) # 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", "task_parts", "files", "driver", "mcp_servers", "score", "simulator", "limits", "controls", "environments", +BENCH_VERSIONED = ("upstream", "datasets", "files", "driver", "mcp_servers", "score", "simulator", "limits", "controls", "environments", "options", "host", "setups", "proven", "leaderboard", "agent_options") +# What a benchmark definition, or a version of it, may still carry and nothing reads: accepted, ignored, said (warnings). +RETIRED = ("task_parts",) # What a benchmark option may need: embedding and reranker models through the relay, # machine requirements (host), and digest-pinned auxiliary files. NEED_KEYS = ("embeddings", "reranker", "host", "files") @@ -920,7 +922,7 @@ def _versioned(d: dict, kind: str) -> List[str]: if not isinstance(block, dict): bad.append(f"versions.{v}: an object") continue - extra = [k for k in block if k not in own] + extra = [k for k in block if k not in own and not (kind == "benchmark" and k in RETIRED)] if extra: bad.append(f"versions.{v}: {', '.join(extra)} cannot differ between versions (only {', '.join(own)})") if (block.get("upstream") or {}).get("version"): @@ -1627,6 +1629,15 @@ def mount_problems(mount) -> List[str]: return [] +def warnings(d: dict, kind: str) -> List[str]: + """What definition ``d`` of ``kind`` carries that no longer has an effect, each said once; never a problem.""" + if names.kind(kind) != "benchmark" or not isinstance(d, dict): + return [] + versions_ = d.get("versions") + blocks = [d] + [b for b in (versions_.values() if isinstance(versions_, dict) else ()) if isinstance(b, dict)] + return [f"{k}: no longer has an effect; remove it" for k in RETIRED if any(k in b for b in blocks)] + + def problems(d: dict, kind: str) -> List[str]: """What is wrong with definition ``d`` of ``kind``; empty when it may be offered.""" kind = names.kind(kind) @@ -1661,20 +1672,6 @@ 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) @@ -1905,7 +1902,10 @@ def _read(path: str, kind: str, key: str) -> Tuple[Optional[dict], List[str]]: bad.append(f"{said(kind)} {key}: start.driver: only an entry of a benchmark's {AGENTS_FILE}") if bad: return None, bad + notes = warnings(d, kind) d = dict(d, _here=os.path.dirname(path), _kind=kind) + if notes: # carried by each of its versions: ``nullius standard check`` says them once + d["_warnings"] = [f"{said(kind)} {key}: {p}" for p in notes] if kind == "benchmark": d["_origin"] = _entry_origin(os.path.dirname(path)) if kind == "agent": # where it comes from: the user's catalogue, or the bundle diff --git a/app/packaging/verify.py b/app/packaging/verify.py index 446b7ca98..3fb7452ac 100644 --- a/app/packaging/verify.py +++ b/app/packaging/verify.py @@ -59,7 +59,7 @@ def digest(): web.app.config.update(TESTING=True) client = web.app.test_client() pages = ['/', '/benchmarks', '/agents', '/modules', '/settings', - '/leaderboard', '/scoring', '/api/leaderboard', '/api/scoring', + '/leaderboard', '/api/leaderboard', '/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', diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index f6b6f8740..da2e3e848 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -136,6 +136,7 @@ nav: - Metrics: - Metric field guide: field-guide.md - Release notes: + - Next: releases/next.md - v0.3.0: releases/v0.3.0.md - v0.2.0: releases/v0.2.0.md - v0.1.1: releases/v0.1.1.md diff --git a/app/static/leaderboard/board.js b/app/static/leaderboard/board.js index 17dae6dcb..9b7271ba4 100644 --- a/app/static/leaderboard/board.js +++ b/app/static/leaderboard/board.js @@ -2,7 +2,9 @@ (() => { 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; + /* the view asked, in the address: rows compared on the tasks they share, or each over its own, never compared */ + const mode = data.tasks, shared = mode === 'shared'; + let selected = data.selected, versus = shared ? 'average' : 'none', family = new URLSearchParams(location.search).get('family') === 'domains' ? 'domains' : 'capabilities', measure = new URLSearchParams(location.search).get('measure') === 'mean_score' ? 'mean_score' : 'resolved', metric = 'time', generation = 0, focusBefore = null, 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)}%`; @@ -10,27 +12,38 @@ 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)); + const amount = (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); + /* a row's view, none outside the cohort; its cell of an axis or of the shown family's Overall; the cell's shown measure */ + const view = r => r?.[mode] || null; + const cell = (r, axis) => axis === 'Overall' ? view(r)?.overall[family] : view(r)?.axes[axis]; + const value = (r, axis) => cell(r, axis)?.[measure] ?? null; + const overall = r => value(r, 'Overall'); + const rankOf = r => shared ? r.rank[family] : null; + const measures = r => view(r)?.metrics[family] || {}; + const counted = c => shared ? `${c.n} shared` : `${c.n} tasks`; + /* pass^3 over the tasks, or each benchmark version that recorded three attempts, by name */ + const pass3 = parts => parts.length ? parts.map(p => `${p.name ? p.name + ' ' : ''}${percent(p.value)} of ${p.n} tasks`).join(' · ') : 'too few attempts'; + /* every address made here says the unchecked-labels mode, whatever its reader's default */ + const address = (extra = {}) => { const q = new URLSearchParams(location.search); q.set('unchecked', data.unchecked); Object.entries(extra).forEach(([k,v]) => q.set(k,v)); return q; }; /* 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)); + const fieldAverage = axis => { const v=data.rows.filter(shown).map(r=>value(r,axis)).filter(x=>x!=null); return v.length?v.reduce((a,b)=>a+b,0)/v.length:null; }; + const scored = () => data.rows.filter(r => overall(r) != 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; + const compared = axis => versus === 'average' ? fieldAverage(axis) : value(row(versus), axis); + const comparedName = () => 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'); @@ -49,39 +62,28 @@ 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;}; + /* a score's evidence: its tasks by benchmark version, each with both rates and its runs, then coverage and pass^3 */ + const c = cell(current, axisName); + pop.replaceChildren(element('strong', `${axisName} · ${label(current)}`)); + if (!c) { dismiss(); return; } + pop.append(element('p', shared ? `${c.n} shared tasks` : `${c.n} tasks, not comparable`)); 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))); + ['Benchmark','Tasks','Resolved','Mean score'].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)); - } + const scoreCell=score=>{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','–',{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;}; + c.benchmarks.forEach(b => { + const id=`${b.benchmark}@${b.version}`, tr=element('tr'), name=element('td',data.versions.find(v=>v.id===id)?.name||id), small=element('small'); + data.runs.filter(x=>b.runs.includes(x.id)).forEach((run,i,all)=>small.append(i?' · ':'',run.url?element('a',all.length>1?`Open run ${i+1}`:'Open run',{href:run.url,title:run.id}):element('span',run.id,{class:'mono'}))); + if(small.childNodes.length)name.append(small); + tr.append(name,element('td',String(b.n),{class:'lb-ev-num'}),scoreCell(b.resolved),element('td',whole(b.mean_score),{class:'lb-ev-num'}));body.append(tr); + }); + if(body.children.length){ + const foot=element('tfoot'),tr=element('tr');tr.append(element('td',axisName),element('td',String(c.n),{class:'lb-ev-num'}),element('td',percent(c.resolved),{class:'lb-ev-num'}),element('td',percent(c.mean_score),{class:'lb-ev-num'}));foot.append(tr);table.append(foot); + pop.append(table); } - if(body.children.length)pop.append(table); + const covered=current.coverage[axisName]; + if(covered)pop.append(element('p',`Coverage ${covered.evaluated} of ${covered.labelled??'?'} labelled tasks`)); + pop.append(element('p',`pass^3 ${pass3(axisName==='Overall'?view(current).pass3:view(current).evidence.pass3[axisName])}`)); 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 @@ -177,36 +179,61 @@ 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; } + /* a cell with no task says so, never a rate: none shared, or none of the row's own */ + const none = (td, c) => { td.replaceChildren(element('span', c && shared && !c.n ? '0 shared' : '–', {class:'lb-none'})); }; + const own = (td, c) => { if (!shared) td.append(element('span', counted(c), {class:'lb-n muted small'})); }; + function chip(td, r, axis) { + const c = cell(r, axis), v = value(r, axis); + if (!c?.n) { none(td, c); return; } + td.replaceChildren(); + /* two versions of one benchmark keep their rates apart: the cell has none of its own, its evidence has each */ + if (v == null) { td.append(element('span','–',{class:'lb-none',tabindex:'0','data-axis':axis})); 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); + const t=heat(v), ink=v>=.6?' lb-top':''; + const span=element('span',whole(v),{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,(v-.6)/.4).toFixed(3));td.append(span);own(td,c); + } + /* Overall is always Resolved, the rank's key; Mean score has its own column */ + function drawOverall(td, r) { + const c = cell(r, 'Overall'); + if (!c?.n) { none(td, c); return; } + td.replaceChildren(element('span',c.resolved==null?'–':`${(c.resolved*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=`${(c.resolved||0)*100}%`;bar.append(fill);td.append(bar);own(td,c); } - 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); + /* shared tasks: each score column says how many under its name */ + function counts() { + heads().forEach(th => { + const n = th.dataset.col === 'overall' ? data.n_overall[family] : data.n[th.dataset.col]; + if (!shared || n == null) return; + th.dataset.label ??= th.textContent.trim(); + th.replaceChildren(th.dataset.label, element('span', `${n} shared`, {class:'lb-n muted small'})); + }); } - /* 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; + /* the rank is the server's, over the cohort the address names: a search or filter that asks reads the board again for + the rows that pass, and a redraw that does not ask never renumbers */ 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 keys=new Set(e.detail.rows.map(tr=>tr.dataset.key)); + if(asked){asked=false;cohort(keys);} 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(); }); + /* the agents a filter or a search leaves are the cohort: the board is read again for them, compared on the tasks they + share, and the address says who. Only the reader's own change of the search or a filter asks: a cohort the address + came with stays until then, and so does the one asked when its scores, drawn, move a row past a filter. */ + let asked=false; + function cohort(keys) { + /* every evaluated row is the default, no row at all is an empty `row=`: never the default's N */ + const all=data.rows.filter(r=>r.evaluated).map(r=>r.key), on=all.filter(k=>keys.has(k)), want=on.length===all.length?[]:on.length?on:['']; + const q=address(); + if(JSON.stringify([...want].sort())===JSON.stringify(q.getAll('row').sort()))return; + q.delete('row');want.forEach(k=>q.append('row',k));history.replaceState(null,'','?'+q); + fetchBoard().then(got=>{if(got)apply(got);}).catch(()=>{}); + } 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));} + const first=scored().sort((a,b)=>(rankOf(a)??1e9)-(rankOf(b)??1e9))[0]||data.rows.find(shown); + if(row(versus)&&!shown(row(versus))){versus='average';document.querySelectorAll('[data-vs-select]').forEach(v=>setSelect(v,versus));} + /* no row matches: the chosen agent's detail goes with them, and comes back with a row */ + const none=!data.rows.some(shown);['lb-card','leaderboard-strips','leaderboard-radars'].forEach(id=>{const at=document.getElementById(id);if(at)at.hidden=none;}); if(row(selected)&&!shown(row(selected))&&first)choose(first.key);else draw(); } function updateTable() { @@ -215,19 +242,21 @@ 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.dataset.sortGroup = rankOf(r) ? 0 : overall(r) != null ? 1 : 2; + tr.dataset.fStatus = `${rankOf(r) ? '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-col="rank"]').replaceChildren(medal(rankOf(r))); + tr.querySelector('[data-col="rank"]').dataset.sort=rankOf(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`; } + const total=cell(r,'Overall'), o=tr.querySelector('[data-col="overall"]');drawOverall(o,r);o.dataset.sort=level(total?.resolved); + const mean=tr.querySelector('[data-col="mean"]');mean.replaceChildren(element('span',total?.mean_score==null?'–':percent(total.mean_score),{class:'lb-m'}));mean.dataset.sort=level(total?.mean_score); + const again=tr.querySelector('[data-col="pass3"]');again.replaceChildren(element('span',view(r)?pass3(view(r).pass3):'–',{class:'lb-m'}));again.dataset.sort=level(view(r)?.pass3[0]?.value); + data.axes.forEach(name=>{const td=tr.querySelector(`[data-col="${name}"]`);chip(td,r,name);td.dataset.sort=level(value(r,name));}); + for(const field of ['steps','time','calls','cost']) { const m=measures(r)[field]||{value:null,count:0}, td=tr.querySelector(`[data-col="${field}"]`);td.replaceChildren(element('span',amount(field,m.value),{class:'lb-m'}));td.dataset.sort=m.value??'';td.title=`${m.count} observed`; } table.tBodies[0].append(tr); }); - columns(); + counts(); 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; @@ -235,27 +264,14 @@ 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'); - }); - } + Object.entries({input:'[data-search]',change:'[data-filter-menu]',click:'[data-clear],[data-all],[data-none]'}).forEach(([type,asks])=>tools?.addEventListener(type,e=>{if(e.target.closest(asks))asked=true;},true)); 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 */ + /* Sort by lists 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; @@ -273,11 +289,11 @@ /* 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}; + const fixed={rank,agent:phone?Math.max(112,Math.min(168,room-rank-overall)):238,overall,mean:104,pass3:132,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; + const name=th.dataset.label||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); @@ -329,7 +345,7 @@ 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 */ + /* the efficiency scatter, on the mockup's 640 by 426 grid: Overall up, time or cost per attempt 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; @@ -343,8 +359,8 @@ 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 time=metric==='time', spent=r=>measures(r)[metric]?.value, x=r=>time?spent(r)/60:spent(r); + const points=scored().filter(r=>spent(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})); @@ -352,19 +368,21 @@ 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'})); + /* better and worse are a comparison: each row over its own tasks has none */ + if(shared)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); + 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=>overall(r)*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`)); + if(shared)plot.append(svg('text',{x:PL.l+10,y:PL.t+20,class:'lb-better','data-node':'better'},'BETTER')); + plot.append(svg('text',{x:PL.l-34,y:PL.t-14,'data-node':'ylabel'},`Overall, ${measureName()}`),svg('text',{x:(PL.l+PL.r)/2,y:PL.b+36,'text-anchor':'middle','data-node':'xlabel'},`${time?'Minutes':'Cost'} per attempt`)); /* 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 R=13, H=27, spots=points.map(r=>({r,x:X(x(r)),y:Y(overall(r))})), 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(); @@ -379,7 +397,7 @@ 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))}`)); + group.append(svg('title',{},`${label(r)} · ${percent(overall(r))} · ${amount(metric,spent(r))} per attempt`)); 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]; @@ -399,21 +417,22 @@ /* 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'; + const other=!!row(versus); 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); + /* each over its own tasks, the others are no comparison: the chosen agent stands alone */ + const average=shared?fieldAverage(name):null, mine=value(current,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)}`}); + if(shared)data.rows.filter(r=>value(r,name)!=null&&r.key!==selected&&shown(r)).forEach(r=>put('r:'+r.key,'i','',value(r,name)*100,{role:'button',tabindex:'0','data-select':r.key,'aria-label':`${label(r)} ${whole(value(r,name))}`,title:`${label(r)} ${whole(value(r,name))}`})); + if(mine!=null)put('r:'+selected,'i','lb-me',mine*100,{role:'button',tabindex:'0','data-select':selected,'aria-label':`${label(current)} ${whole(mine)}`,title:`${label(current)} ${whole(mine)}`}); 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))); + const said=line.children[2];said.replaceChildren(document.createTextNode(whole(mine))); + if(other&&versusScore!=null)said.append(element('small',whole(versusScore))); }); } /* radars: rings at half and whole, a spoke per axis, the chosen agent filled, the comparison dashed */ @@ -430,8 +449,8 @@ 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))); + text.append(document.createTextNode(name),svg('tspan',{x:lx,dy:19,class:'lb-me'},whole(value(current,name)))); + const v=compared(name);if(row(versus)&&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)=>{ @@ -441,8 +460,9 @@ 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'); + if(shared)series(name=>compared(name),true); + series(name=>value(current,name),false); + plot.classList.toggle('lb-versus-agent',!!row(versus)); 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 */ @@ -450,7 +470,7 @@ 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);} + if(live){live.classList.toggle('lb-versus-agent',!!row(versus));motion.morph(live,plot);} else {container.append(plot);motion.reveal(plot,'radars');} pills(container.querySelector('svg')); } @@ -462,7 +482,7 @@ }); } function swatches() { - const agent=versus!=='average'; + const agent=!!row(versus); 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(); @@ -479,32 +499,35 @@ 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); + /* the server's rank, of the ranked rows of the cohort it scored */ + const rank=rankOf(current), ranked=data.rows.filter(r=>rankOf(r)).length; + const total=cell(current,'Overall'), figure=element('div',null,{class:'lb-figure'}); + figure.append(element('span',total?.resolved==null?'–':`${(total.resolved*100).toFixed(1)}%`,{class:'lb-fig'}),element('span',!shared?'not comparable':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=`${(total?.resolved||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 differences=data[family].map(name=>({name,d:value(current,name)!=null&&compared(name)!=null?value(current,name)-compared(name):null})).filter(v=>v.d!=null).sort((a,b)=>b.d-a.d); + const baseline=row(versus)?overall(row(versus)):null; 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;})); + if(total)lines.push(['Tasks',[counted(total)]],['Mean score',[total.mean_score==null?'–':percent(total.mean_score)]],['pass^3',[pass3(view(current).pass3)]]); + if(baseline!=null&&overall(current)!=null)lines.push([`Overall against ${against}`,[change(overall(current)-baseline)]]); + if(shared)lines.push([`Best against ${against}`,named(differences[0])],[`Weakest against ${against}`,named(differences.at(-1))]); + lines.push(['Time per attempt',[amount('time',measures(current).time?.value)]],['Cost per attempt',[amount('cost',measures(current).cost?.value)]]); + box.replaceChildren(who,figure,bar,...lines.map(([k,v])=>{const line=element('div',null,{class:'lb-kv'});const said=element('b');said.append(...v);line.append(element('span',k),said);return line;}), + ...current.warnings.map(w=>element('p',w,{class:'muted small'}))); } /* 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;} + const others=rows.filter(r=>r.key!==selected); + if(shared&&versus!=='average'&&!others.some(r=>r.key===versus))versus='average'; + document.querySelectorAll('[data-versus]').forEach(e=>{e.hidden=!shared;}); 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);}); + document.querySelectorAll('[data-vs-select]').forEach(s=>{s.replaceChildren(element('option','Average',{value:'average'}),...others.map(option));setSelect(s,versus);}); } function draw() { if(!row(selected))return; @@ -518,7 +541,7 @@ 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(); + useFamily();addressed(); /* 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;} @@ -528,27 +551,37 @@ 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-vs-select]').forEach(s=>{s.onchange=()=>{versus=s.value;document.querySelectorAll('[data-vs-select]').forEach(v=>setSelect(v,versus));draw();};}); + /* the table's score columns and every chart show one measure, and each chart's title says which */ + const measureName=()=>measure==='resolved'?'Resolved':'Mean score'; + const showMeasure=()=>{press('lb-measure','data-measure',measure);document.querySelectorAll('[data-measure-name]').forEach(e=>{e.textContent=measureName();});}; + /* the measure, the family and the unchecked-labels mode are in the address, like the rest of the view */ + const addressed=()=>{const q=address();if(measure==='resolved')q.delete('measure');else q.set('measure',measure);if(family==='capabilities')q.delete('family');else q.set('family',family);history.replaceState(null,'','?'+q);}; + showMeasure();addressed(); + document.querySelectorAll('[data-measure]').forEach(b=>b.onclick=()=>{measure=b.dataset.measure;showMeasure();addressed();updateTable();draw();}); + /* the view, the unchecked labels and the selection are the address: a change opens the board it names */ + document.querySelectorAll('[data-set]').forEach(b=>b.onclick=()=>{location.assign('?'+address({[b.dataset.set]:b.value}));}); + tools?.addEventListener('change',e=>{ + if(!e.target.matches('[data-choose]'))return; + const q=address(), boxes=[...tools.querySelectorAll('[data-choose]')]; + /* an axis hidden unless asked is named when ticked; anything else when not */ + new Set(boxes.map(b=>b.dataset.choose)).forEach(name=>{q.delete(name);boxes.filter(b=>b.dataset.choose===name&&b.checked===(name==='show_axis')).forEach(b=>q.append(name,b.value));}); + location.assign('?'+q); + }); 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 */ + /* the measures answer for the board they were asked about; when it changed meanwhile (a run that wrote a trial), the + board is read again, once; an answer for another board is dropped */ let reread=false; - async function deferred(turn) { const response=await nulliusFetch(`/api/leaderboard/metrics?context=${encodeURIComponent(data.context)}`); + async function deferred(turn) { const response=await nulliusFetch(`/api/leaderboard/metrics?${address({context: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);}); + 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);for(const v of ['shared','every'])if(existing?.[v]&&r[v])existing[v].metrics=r[v];});updateTable();card();drawScatter(); } + async function fetchBoard(){const turn=++generation;const response=await nulliusFetch(`/api/leaderboard?${address()}`);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 ranking orders the rows */ + function useFamily(){data.rows.sort((a,b)=>(rankOf(a)??1e9)-(rankOf(b)??1e9)||!a.evaluated-!b.evaluated||a.name.localeCompare(b.name)||a.key.localeCompare(b.key));} + function apply({next,turn}){if(turn!==generation)return;data=next;useFamily();if(!row(selected))selected=data.selected;updateTable();draw();deferred(turn).catch(()=>{});} 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); @@ -556,5 +589,7 @@ /* 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();}); + if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',applyFamily); + /* weights saved by an earlier release are said once: the file stays, nothing reads it */ + try{if(data.notice&&!localStorage.getItem('leaderboard.scoring-notice')){localStorage.setItem('leaderboard.scoring-notice','1');window.nulliusNotify?.(data.notice,{key:'scoring-notice'});}}catch{} })(); diff --git a/app/static/leaderboard/leaderboard.css b/app/static/leaderboard/leaderboard.css index 0a4f00892..168ecc82a 100644 --- a/app/static/leaderboard/leaderboard.css +++ b/app/static/leaderboard/leaderboard.css @@ -1,4 +1,3 @@ -.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; } @@ -58,6 +57,10 @@ /* 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 column's or a cell's task count sits under its name or its rate */ +.lb-n { display: block; } +/* pass^3 names its benchmark when it reads one alone: the name wraps */ +.lb-table td[data-col="pass3"] { white-space: normal; } /* a cell's contents are boxes, so they can slide when their row moves */ .lb-none, .lb-m { display: inline-block; } @@ -180,63 +183,6 @@ tr:hover .lb-medal .lb-disc { animation: lb-glow .9s ease-in-out .25s; } :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 */ @@ -248,7 +194,6 @@ tr:hover .lb-medal .lb-disc { animation: lb-glow .9s ease-in-out .25s; } .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 */ @@ -257,22 +202,6 @@ tr:hover .lb-medal .lb-disc { animation: lb-glow .9s ease-in-out .25s; } .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/scoring.js b/app/static/leaderboard/scoring.js deleted file mode 100644 index 8ac4a2e6a..000000000 --- a/app/static/leaderboard/scoring.js +++ /dev/null @@ -1,142 +0,0 @@ -/* 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/templates/base.html b/app/templates/base.html index 848b8fb25..455a8bc6f 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -104,7 +104,7 @@ Runs Compare - Leaderboard + 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/pages.md b/docs/cli/pages.md index 4ee5d0867..8379ce187 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -11,8 +11,7 @@ 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]`; `nullius remote leaderboard` against a served Nullius | -| `/scoring` | Profile `scoring.json` beside `settings.json`; `nullius paths` locates its configuration directory | +| `/leaderboard?row=&tasks=&hide_axis=&show_axis=&hide_version=&hide_run=&unchecked=`; `&measure=mean_score` and `&family=domains` show the other of the two numbers and of the two families the command prints | `nullius leaderboard ... [--row KEY]... [--every-task] [--hide-axis AXIS] [--show-axis AXIS] [--hide-version BENCHMARK@VERSION] [--hide-run ID] [--unchecked-labels omit\|include] [--json]`; `nullius remote leaderboard` against a served Nullius | | `/compare` | `nullius compare ... [--matched] [--exclude KIND]... [--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 52562ff0c..6d16183e6 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -73,21 +73,32 @@ A trial that ended early kept no ACP events: its trace has the model calls, and ```bash nullius leaderboard --help -nullius leaderboard --json -nullius leaderboard ./jobs --json +nullius leaderboard ./jobs +nullius leaderboard ./jobs --row KEY --row KEY --json +nullius leaderboard ./jobs --every-task --hide-axis Safety --show-axis Coding ``` 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 document was read; an invalid root exits 3, invalid arguments or an unknown row 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 +| Option | Meaning | +| --- | --- | +| `--row KEY` | A row to compare, repeatable; every row with an evaluated task on a shown axis by default. Keys are printed | +| `--every-task` | Each row over its own tasks, never ranked; shared tasks by default | +| `--hide-axis AXIS`, `--show-axis AXIS` | Leave an axis out of the columns and Overall; show one hidden by default | +| `--hide-version BENCHMARK@VERSION`, `--hide-run ID` | Leave a benchmark version or a run out | +| `--unchecked-labels omit\|include` | Count labels not checked at a run's version; the `LEADERBOARD_UNCHECKED_LABELS` setting by default | + +The page takes the same options in its address and gives the same numbers: see +the [Leaderboard](../field-guide.md#leaderboard). JSON carries, per row, its +key, identity, runs, rank and both views (`shared`, `every`): each axis's count +of tasks, Resolved and Mean score per benchmark version, Overall per family, +pass^3 with its count, and coverage. Rates are fractions; text percentages use +one decimal when needed. + +Text gives each axis its pass^3 and each family its means per attempt with +their observed counts; a row outside the view keeps its warnings. The command also reads the counted 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). +metrics unavailable. When the profile holds a `scoring.json`, the first line says +saved Scoring weights are no longer used; the file is kept. diff --git a/docs/field-guide.md b/docs/field-guide.md index ebf82dbe6..028818b0a 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -294,65 +294,84 @@ Thirteen classes. The five marked **yes** under Infrastructure leave the adjuste ## Leaderboard -Leaderboard scores describe one workspace's completed runs of catalogue agents. -Controls, example agents, preparing/running jobs and standalone Module -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. +The Leaderboard reads one workspace's completed runs of catalogue agents. +Controls, example agents, preparing or running jobs and standalone Module +results do not count. Agent versions and execution setups are separate rows. + +**Labels.** A benchmark's `labels.json`, beside its definition, gives its tasks +their axes: capabilities and domains. A rule labels the whole benchmark, one +dataset, or listed tasks of one dataset. A rule on listed tasks names the +benchmark versions it was checked at; at another version it counts only with +unchecked labels included. A benchmark without labels scores nothing. Each +axis is defined under [Leaderboard axes](#leaderboard-axes). + +**Runs.** Per row, the most recent finished run of each benchmark version and +dataset counts. Every other run is set aside, with one warning per benchmark +version: hide a run to count another. A run must record its benchmark version. +Two versions of a benchmark are never pooled. + +**Rows compared.** With nothing asked, the rows are those with an evaluated task +on a shown axis. Filters and the search on the page, `--row` on the command and +`row` on the API choose them, before anything is scored; an empty `row=` chooses +none. Clear filters resets the filters, not the search. An unknown row is +refused. + +| View | Reads | Ranked | +| --- | --- | --- | +| Shared tasks (default) | The tasks every compared row evaluated | Yes | +| Every task (not comparable) | Each row's own tasks | Never: no rank, medal or difference | + +- **N** under a column head is the number of shared tasks on that axis. At + N = 0 the cell says "0 shared" and has no rate. One row with a disjoint set of + tasks makes N 0 for all: narrow the rows. +- **Resolved** is the share of tasks fully resolved. **Mean score** is the mean + task score; a graded task below full score is not resolved. Each chart says + which it shows. Infrastructure failures are excluded. +- **Overall** covers the tasks of the shown axes of one family, each task once. + Hiding an axis changes it. Every row with shared tasks is ranked by Overall + Resolved; ties share a rank. +- **pass^3** needs three recorded attempts per task. It is given over all the + tasks, or for each benchmark version that recorded them, with its count of + tasks. It enters no axis. +- **Evidence** of a score: tasks, Resolved and Mean score per benchmark version, + the runs those tasks come from (a run whose name two folders hold is named by + its folder, without a link), coverage (evaluated over labelled tasks, "?" when the dataset was + never listed) and pass^3. +- **Selection.** Axes, benchmark versions and runs can be hidden. The page's + address carries the selection, the rows, the view, the family and measure + shown and the unchecked-labels mode. + +Time and cost are means per attempt over the observed trials of the tasks +counted, each with its own count. Steps and Tool calls load later from trajectories on the page; the +command reads them at once. A missing or malformed trace is unavailable, not +zero. + +Saved Scoring weights (`scoring.json`, v0.3.0) are no longer used. The file is +kept where it is; the page and the command say so once. + +## Leaderboard axes {#leaderboard-axes} + +The `/label-benchmark` skill proposes labels from these definitions, kept in +its `definitions.json`. + +| Axis | Family | Definition | On the board | +| --- | --- | --- | --- | +| Memory | Capability | Uses what it was told earlier and kept, and only where it applies | Shown | +| Safety | Capability | Prevents harm to the user, the party it acts for, or third parties: to health or physical safety, to money, to privacy, or through an irreversible step. Acts only on confirmed intent; asks before anything costly or irreversible | Shown | +| Consistency | Capability | When information has changed, acts on the newest and removes what is outdated | Shown | +| Personalization | Capability | Chooses as the user, or the person served, would | Shown | +| Proactivity | Capability | Takes a step nobody asked for but the situation requires, and takes it correctly | Shown | +| Retrieval | Capability | Gets facts right from an outside source, any source other than the prompt and the system's own past | Shown | +| Communication | Capability | The messages a task requires reach the right people with the right content | Shown | +| Execution | Capability | Carries out what was asked in an environment, with tools used correctly | Shown | +| Reasoning | Capability | Derives a conclusion that none of the given facts states | Hidden until selected | +| Abstention | Capability | Says that a thing cannot be done or is not known, instead of inventing a result | Hidden until selected | +| Exactness | Capability | Does every stated part of the request, each exactly once, with tools used correctly | Hidden until selected | +| Travel | Domain | Getting somewhere and staying there | Shown | +| Dining | Domain | Meals prepared by others, out or delivered | Shown | +| Shopping | Domain | Acquiring goods, and acting on recalls and safety notices | Shown | +| Money | Domain | Money itself | Shown | +| Health | Domain | The care of a person's or an animal's body or mind | Shown | +| Home | Domain | Keeping a household or family running | Shown | +| Work | Domain | Someone's job, business or studies, as such | Shown | +| Coding | Domain | Building or operating software | Hidden until selected | diff --git a/docs/releases/next.md b/docs/releases/next.md new file mode 100644 index 000000000..f4cd99093 --- /dev/null +++ b/docs/releases/next.md @@ -0,0 +1,3 @@ +**Next release** + +- **Leaderboard.** Scores come from task labels (`labels.json`), compared on the tasks rows share. Saved Scoring weights stop counting: `scoring.json` is no longer read and is kept where it is. The Scoring view is gone; `task_parts` in a benchmark definition no longer has an effect: `nullius standard check` warns, the definition still loads. `/api/leaderboard/comparison` is gone: choose versions with `hide_version` on `/api/leaderboard`. diff --git a/docs/settings/README.md b/docs/settings/README.md index 0a93c4df5..fcb844579 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -54,6 +54,7 @@ and job roots also have command-line options. The app does not load `app/.env`. | `NULLIUS_CATALOGUE` | `catalogue/` in the user data directory; whole-entry overrides of the bundled catalogue | | `NULLIUS_PRICES` | `prices.json` in the configuration directory; the [model price list](model-prices.md), your own prices beside it | | `DEBUG` | Development debugger and reloader; off by default, enabled by `1` | +| `LEADERBOARD_UNCHECKED_LABELS` | `omit`; `include` counts task labels not checked at a run's benchmark version on the [Leaderboard](../field-guide.md#leaderboard) | ## Save @@ -74,7 +75,7 @@ credential values. Linux defaults: | Stores | Default | | --- | --- | -| Composite scoring | `~/.config/nullius/scoring.json` | +| Saved Scoring weights of v0.3.0, no longer used and never removed | `~/.config/nullius/scoring.json` | | Saved settings | `~/.config/nullius/settings.json` | | Benchmark credentials | `~/.config/nullius/secrets//` | | Hugging Face token | `~/.config/nullius/secrets/data-provider-huggingface/` |