diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9a1c9995..1096f0ec 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,4 +1,4 @@ -# The application's two suites and installable package, on every non-draft PR +# The application's backend, route and browser suites and installable package, on every non-draft PR # (again when a draft is marked ready) and by hand. There are no model calls # or containers: the docker tier is the nightly docker-tests workflow. uv is a test tool; Flask # is the app's only Python dependency. @@ -6,7 +6,7 @@ # Nothing shared is installed, because nothing shared is imported: the backend # is this repository's own code under app/nullius/ and imports only the # standard library. The Harbor build tests invoke uv against offline fixtures; -# only the route suite needs Flask. +# the web suites need Flask; browser interactions also use test-only Playwright. name: tests on: @@ -55,6 +55,11 @@ jobs: - name: route suite # Includes the recipe-compilation tests, which need Node. run: python3 app/tests/parallel.py app/ui_tests + - name: Leaderboard browser interactions + run: | + uv run --no-project --with-requirements app/ui_tests/browser/requirements.txt python -m playwright install --with-deps chromium + uv run --no-project --with-requirements app/requirements.txt --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/leaderboard.py + uv run --no-project --with-requirements app/requirements.txt --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/mutations.py - name: installed package # Temporary installs only; no publication or stored artifact. run: | diff --git a/AGENTS.md b/AGENTS.md index ad99e5e7..0b87c0cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,6 +59,7 @@ is: `grep -m1 '"""' app/nullius/*.py app/nullius/runs/*.py`. | --- | --- | | `app/nullius/` itself | What all share: settings, paths, providers, hosts, running a recipe | | `app/nullius/runs/`, `traces/`, `compare/` | Reading one job tree, a trial's trace, several runs | +| `app/nullius/leaderboard/` | Composite scoring, selected task evidence and profile scoring documents | | `app/nullius/catalogue/` | A folder per entry under `benchmarks/`, `agents/`, `capabilities/`: its definition and code | | `app/nullius/recipes/`, `harbor/` | What the builder offers and saves; the Harbor a recipe pins | | `app/nullius/importers/`, `judge/` | Foreign results in; questions to a judge model | @@ -79,6 +80,14 @@ python3 app/tests/parallel.py uv run --no-project --with-requirements app/requirements.txt \ python app/tests/parallel.py app/ui_tests +# real-browser interactions (test-only dependency; install Chromium once) +uv run --no-project --with-requirements app/ui_tests/browser/requirements.txt \ + python -m playwright install chromium +uv run --no-project --with-requirements app/requirements.txt \ + --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/leaderboard.py +uv run --no-project --with-requirements app/requirements.txt \ + --with-requirements app/ui_tests/browser/requirements.txt python app/ui_tests/browser/mutations.py + # one module; a route module under uv as above, with -s app/ui_tests NULLIUS_HOME=$(mktemp -d) python3 -m unittest discover -s app/tests -t app -p test_live.py diff --git a/app/app.py b/app/app.py index 101100cb..d0f4aa89 100644 --- a/app/app.py +++ b/app/app.py @@ -28,11 +28,11 @@ if __package__: # the wheel's private web namespace from .web.core import app from .web import shared - from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure + from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure, leaderboard else: # python app/app.py, and the source route suite from web.core import app from web import shared - from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure + from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure, leaderboard from nullius import execution, workspace # noqa: E402 - recorded runs, picked up again at start; the workspace left open diff --git a/app/nullius/catalogue/agents/codex/agent.json b/app/nullius/catalogue/agents/codex/agent.json index 0546056c..9ce68684 100644 --- a/app/nullius/catalogue/agents/codex/agent.json +++ b/app/nullius/catalogue/agents/codex/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "codex", "label": "Codex", + "company": "OpenAI", "summary": "OpenAI's coding agent.", "upstream": { "license": "Apache-2.0" diff --git a/app/nullius/catalogue/agents/digitalmate/agent.json b/app/nullius/catalogue/agents/digitalmate/agent.json index d5b17c23..a7a47346 100644 --- a/app/nullius/catalogue/agents/digitalmate/agent.json +++ b/app/nullius/catalogue/agents/digitalmate/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "digitalmate", "label": "DigitalMate", + "company": "ThinkFlowLab", "summary": "DigitalMate's Personal Agent service, run as Hive Home with its owned WorkSwarm runtimes.", "model": { "apis": [ diff --git a/app/nullius/catalogue/agents/goose/agent.json b/app/nullius/catalogue/agents/goose/agent.json index c20a9925..84462c5c 100644 --- a/app/nullius/catalogue/agents/goose/agent.json +++ b/app/nullius/catalogue/agents/goose/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "goose", "label": "Goose", + "company": "Agentic AI Foundation", "summary": "The AAIF's open-source agent, formerly Block's.", "upstream": { "package": "@aaif/goose-acp", diff --git a/app/nullius/catalogue/agents/jiuwenswarm/agent.json b/app/nullius/catalogue/agents/jiuwenswarm/agent.json index 42a257bd..c9b7e460 100644 --- a/app/nullius/catalogue/agents/jiuwenswarm/agent.json +++ b/app/nullius/catalogue/agents/jiuwenswarm/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "jiuwenswarm", "label": "JiuwenSwarm", + "company": "openJiuwen", "summary": "openJiuwen's WorkSwarm agent.", "start": { "acp": [ diff --git a/app/nullius/catalogue/agents/mini-swe-agent/agent.json b/app/nullius/catalogue/agents/mini-swe-agent/agent.json index d7d51c83..4bec14f0 100644 --- a/app/nullius/catalogue/agents/mini-swe-agent/agent.json +++ b/app/nullius/catalogue/agents/mini-swe-agent/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "mini-swe-agent", "label": "mini-swe-agent", + "company": "Princeton and Stanford", "summary": "Princeton's 100-line agent, bash only.", "upstream": { "package": "mini-swe-agent", diff --git a/app/nullius/catalogue/agents/opencode/agent.json b/app/nullius/catalogue/agents/opencode/agent.json index 42a873ab..f83d5ccc 100644 --- a/app/nullius/catalogue/agents/opencode/agent.json +++ b/app/nullius/catalogue/agents/opencode/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "opencode", "label": "OpenCode", + "company": "Anomaly", "summary": "The open-source terminal coding agent.", "upstream": { "package": "opencode-ai", diff --git a/app/nullius/catalogue/agents/swe-agent/agent.json b/app/nullius/catalogue/agents/swe-agent/agent.json index 3b33e010..5fca9fb3 100644 --- a/app/nullius/catalogue/agents/swe-agent/agent.json +++ b/app/nullius/catalogue/agents/swe-agent/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "swe-agent", "label": "SWE-agent", + "company": "Princeton and Stanford", "summary": "Princeton\u2019s software engineering agent with its upstream tool bundles.", "upstream": { "repository": "https://github.com/SWE-agent/SWE-agent", diff --git a/app/nullius/catalogue/agents/terminus-2/agent.json b/app/nullius/catalogue/agents/terminus-2/agent.json index de10d38d..434dd219 100644 --- a/app/nullius/catalogue/agents/terminus-2/agent.json +++ b/app/nullius/catalogue/agents/terminus-2/agent.json @@ -2,6 +2,7 @@ "schema": "nullius.agent/v1", "key": "terminus-2", "label": "Terminus 2", + "company": "Harbor", "summary": "Harbor's terminal agent, used by Terminal-Bench.", "upstream": { "package": "harbor", diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 42b94424..42d49969 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -367,5 +367,23 @@ "branch": "main" } } - } + }, + "task_parts": [ + { + "id": "os", + "label": "OS tasks", + "prefixes": [ + "os__" + ] + }, + { + "id": "office", + "label": "Office tasks", + "prefixes": [ + "libreoffice_calc__", + "libreoffice_impress__", + "libreoffice_writer__" + ] + } + ] } diff --git a/app/nullius/charts.py b/app/nullius/charts.py index 849d270b..60a5aed9 100644 --- a/app/nullius/charts.py +++ b/app/nullius/charts.py @@ -47,6 +47,7 @@ class Value: baseline: bool = False tag: str = "" # a short name, where the full one does not fit (a scatter's dot) series: int = 0 # its colour, 1 on, the same in every chart; 0 for none + key: str = "" def cls(self, shape: str) -> str: """A mark's classes: its shape, its series (``s1`` to ``s``, cycling) and whether it is a check.""" @@ -105,6 +106,7 @@ class Mark: y2: float = 0.0 cls: str = "" title: str = "" + key: str = "" @dataclass(frozen=True) @@ -115,6 +117,7 @@ class Text: anchor: str = "start" cls: str = "" leading: float = _LINE + key: str = "" @dataclass(frozen=True) @@ -256,24 +259,25 @@ def dot(v, scale, mid): _TAG_W, _TAG_H = 7.5, 13.0 # a tag's width per character and its height, at the template's font size -def _tag_box(px: float, py: float, width: float, side: str) -> tuple: +def _tag_box(px: float, py: float, width: float, side: str, radius=_DOT, extra=0) -> tuple: """Where a tag ``width`` wide goes on ``side`` of a dot at (px, py): (x, baseline, anchor, box).""" - gap = _DOT + 3 + gap = radius + 3 x, base, anchor = {"right": (px + gap, py + 4, "start"), "left": (px - gap, py + 4, "end"), - "above": (px, py - gap - 2, "middle"), "below": (px, py + gap + 10, "middle")}[side] + "above": (px, py - gap - 2 - extra, "middle"), "below": (px, py + gap + 10, "middle")}[side] x0 = {"start": x, "end": x - width, "middle": x - width / 2}[anchor] - return x, base, anchor, (x0, base - _TAG_H + 3, x0 + width, base + 3) + return x, base, anchor, (x0, base - _TAG_H + 3, x0 + width, base + 3 + extra) def _overlaps(a: tuple, b: tuple) -> bool: return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] -def scatter(x: Metric, y: Metric) -> Panel: +def scatter(x: Metric, y: Metric, *, tiles=False) -> Panel: """A dot per item at (x, y), and its tag (``Value.tag``, else its place in the order) beside it, spelled out in a key under the plot. Every item keeps its own dot: items at one place are set in a ring around it, each tag outward from its dot. Any other tag takes the first side of its dot inside the plot and clear of the dots and tags before it.""" + radius = 11 if tiles else _DOT pairs = list(zip(x.values, y.values)) tags = [a.tag or str(i + 1) for i, (a, _) in enumerate(pairs)] shown = [(t, a, b) for t, (a, b) in zip(tags, pairs) if a.value is not None and b.value is not None] @@ -291,29 +295,42 @@ def scatter(x: Metric, y: Metric) -> Panel: places.setdefault((sx(item[1].value), sy(item[2].value)), []).append(item) dots = [] # (x, y, the tag's place on its ring or None, tag, x value, y value) for (px, py), group in places.items(): - ring = max(_DOT * 2, len(group) * (2 * _DOT + 4) / (2 * math.pi)) if len(group) > 1 else 0.0 + ring = max(radius * 2, len(group) * (2 * radius + 4) / (2 * math.pi)) if len(group) > 1 else 0.0 for k, item in enumerate(group): turn = 2 * math.pi * k / len(group) - math.pi / 2 at = (round(px + (ring + 11) * math.cos(turn), 2), round(py + (ring + 11) * math.sin(turn) + 4, 2)) if ring else None dots.append((round(px + ring * math.cos(turn), 2), round(py + ring * math.sin(turn), 2), at, *item)) - taken = [(px - _DOT, py - _DOT, px + _DOT, py + _DOT) for px, py, *_ in dots] - taken += [(tx - _TAG_W, ty - _TAG_H + 3, tx + _TAG_W, ty + 3) for _, _, (tx, ty), *_ in (d for d in dots if d[2])] + if tiles: + placed = [] + for px, py, *rest in dots: + candidates = [(max(left + radius, min(right - radius, px + dx)), + max(top + radius, min(bottom - radius, py + dy))) + for distance in range(0, 100, 2) + for dx, dy in ((distance, 0), (-distance, 0), (0, distance), (0, -distance))] + px, py = next(((cx, cy) for cx, cy in candidates if all(math.hypot(cx-ox, cy-oy) >= 2*radius+2 for ox, oy, *_ in placed)), candidates[-1]) + placed.append((px, py, *rest)) + dots = placed + taken = [(px - radius, py - radius, px + radius, py + radius) for px, py, *_ in dots] + taken += [(tx - _TAG_W, ty - _TAG_H + 3, tx + _TAG_W, ty + 3) for _, _, (tx, ty), *_ in (d for d in dots if d[2] and not tiles)] for px, py, at, tag, a, b in dots: - marks.append(Mark("circle", px, py, r=_DOT, cls=a.cls("dot"), + marks.append(Mark("tile" if tiles else "circle", px, py, r=radius, cls=a.cls("dot"), key=a.key, title=f"{tag} {a.name}: {x.label} {a.reading}, {y.label} {b.reading}")) - if at: # on a ring, the tag sits outward from its dot + if at and not tiles: # on a ring, the tag sits outward from its dot texts.append(Text(*at, (tag,), "middle", "tag")) continue - width = _TAG_W * len(tag) - spots = [_tag_box(px, py, width, side) for side in ("right", "left", "above", "below")] + width = _TAG_W * max(len(tag), len(a.note) if tiles else 0) + extra = 15 if tiles and a.note else 0 + offsets = [0] if not tiles else [0] + [sign*d for d in range(15, 211, 15) for sign in (1, -1)] + spots = [_tag_box(px, py + offset, width, side, radius, extra) + for offset in offsets for side in ("right", "left", "above", "below")] inside = [s for s in spots if s[3][0] >= left and s[3][2] <= right and s[3][1] >= top and s[3][3] <= bottom] tx, base, anchor, box = next((s for s in inside if not any(_overlaps(s[3], t) for t in taken)), (inside or spots)[0]) taken.append(box) - texts.append(Text(tx, base, (tag,), anchor, "tag")) + texts.append(Text(tx, base, (tag, a.note) if tiles and a.note else (tag,), anchor, "tag", key=a.key)) key_y = _S_HEIGHT + 8 key = _LEFT + (12 if any(a.series for a, _ in pairs) else 0) drawn = {id(d[4]) for d in dots} - for tag, (a, _) in zip(tags, pairs): + for tag, (a, _) in ([] if tiles else zip(tags, pairs)): # a name the caller numbered already (two runs of one agent) is not numbered twice lines = tuple(textwrap.wrap(a.name if a.name.startswith(f"{tag}. ") else f"{tag}. {a.name}", _CHARS)) if a.series: # its colour beside its name diff --git a/app/nullius/cli.py b/app/nullius/cli.py index aa960909..708a46c2 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -15,6 +15,7 @@ "serve": "open the web application", "runs": "inspect run output", "compare": "compare runs", + "leaderboard": "workspace composite agent scores", "flags": "write a run's task flags", "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", @@ -26,6 +27,7 @@ MODULES = { "runs": "nullius.runs.cli", "compare": "nullius.compare.cli", + "leaderboard": "nullius.leaderboard.cli", "flags": "nullius.runs.flags_cli", "import": "nullius.importers.cli", "standard": "nullius.standard.cli", diff --git a/app/nullius/leaderboard/__init__.py b/app/nullius/leaderboard/__init__.py new file mode 100644 index 00000000..e2b637ea --- /dev/null +++ b/app/nullius/leaderboard/__init__.py @@ -0,0 +1 @@ +"""Workspace agent scores and their selected task evidence.""" diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py new file mode 100644 index 00000000..98d49485 --- /dev/null +++ b/app/nullius/leaderboard/board.py @@ -0,0 +1,164 @@ +"""One workspace's composite scores, evidence, coverage and rank requirements.""" +from __future__ import annotations + +import hashlib +import json +import copy +from math import isfinite +from nullius.standard.contract import definitions + +from . import configuration, scoring, weights, scopes + + +def project(jobs, agents, benchmarks, settings, benchmark, version, *, all_scores=False): + """A comparison projection: missing changed evidence invalidates its affected axis.""" + draft = copy.deepcopy(settings) + affected = set() + for name, axis in draft["axes"].items(): + for entry in axis["entries"]: + if entry.get("benchmark") == benchmark: + entry["version"] = version + if entry["weight"] > 0: + affected.add(name) + result = build(jobs, agents, benchmarks, draft, all_scores=all_scores) + for row in result["rows"]: + for name in affected: + axis = row["axes"][name] + if any(e.get("benchmark") == benchmark and e["weight"] > 0 and e["score"] is None for e in axis["entries"]): + axis["score"] = None + axis["share"] = 0 + if axis["weight"] > 0: + row["overall"] = None + row["rank"] = None + return result + + +def row_identity(job): + identity = job.identity + limits = {k: v for k, v in identity.get("limits", {}).items() + if k not in ("repeat", "n_tasks", "task_names", "sample", "seed")} + return {"agent": identity.get("agent", job.agent_name), "version": identity.get("agent_version", job.agent_version), + "model": identity.get("model", job.model_name), "effort": job.reasoning_effort, + "provider": identity.get("provider"), "options": identity.get("agent_options"), + "backend": job.launch.get("environment"), "limits": limits} + + +def key_for(identity): + return hashlib.sha256(json.dumps(identity, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + + +def _empty_metrics(): + return {name: {"value": None, "count": 0} for name in ("time", "cost", "steps", "calls")} + + +def _entry_key(entry): + return tuple(entry.get(k, "") for k in ("benchmark", "dataset", "version", "metric")) + + +def build(jobs, agents, benchmarks, settings, *, all_scores=False, workspace_open=True, metric_sources=None): + """Pure board projection. Inputs belong to a single workspace and profile.""" + config = configuration.validate(settings, benchmarks, allow_unavailable=True) + agents = [a for a in agents if not a.get("example") and a["key"] not in ("nop", "oracle")] + agents_by = {a["key"]: a for a in agents} + benchmarks_by = {(b["key"], definitions.version_identity(b)): b for b in benchmarks} + customs = {c["id"]: c for c in config["custom"]} + grouped, identities = {}, {} + for job in jobs: + identity = row_identity(job) + if not scoring.eligible(job) or identity["agent"] not in agents_by: + continue + key = key_for(identity) + grouped.setdefault(key, []).append(job) + identities[key] = identity + measured_agents = {identity["agent"] for identity in identities.values()} + for agent in agents: + if agent.get("_version", "") != agent.get("_default", agent.get("_version", "")): + continue + if agent["key"] in measured_agents: + continue + identity = {"agent": agent["key"], "version": agent.get("_version", ""), "catalogue_only": True} + key = key_for(identity) + grouped[key], identities[key] = [], identity + rows = [] + for key, runs in grouped.items(): + identity = identities[key] + agent = agents_by[identity["agent"]] + row = {"key": key, "agent": identity["agent"], "name": agent["label"], "company": agent.get("company", ""), + "version": identity["version"], "identity": identity, "has_runs": bool(runs), "axes": {}, + "metrics": _empty_metrics(), "reasons": [], "custom_names": []} + matching = next((a for a in agents if a["key"] == identity["agent"] and a.get("_version", "") == identity["version"]), None) + row["version_label"] = definitions.version_label(matching) if matching else identity["version"] + trials = {} + for name in configuration.AXES: + axis = config["axes"][name] + entries = [] + for entry in axis["entries"]: + evidence = dict(entry, score=None, share=0, tasks=None, covered=0, runs=[], reason="not run", unverified=False, available=True) + if "custom" in entry: + custom = customs[entry["custom"]] + value = custom["scores"].get(key) + evidence.update(name=custom["name"], score=value / 100 if all_scores and value is not None else None, + reason="not verified" if all_scores and value is not None else "not run", + unverified=all_scores and value is not None and entry["weight"] > 0) + else: + bench = benchmarks_by.get((entry["benchmark"], entry["version"])) + evidence["name"] = bench["label"] if bench else entry["benchmark"] + evidence["available"] = bench is not None + if bench is None: + evidence["reason"] = "Benchmark version unavailable" + else: + manifests, normalized, dataset = scopes.select(bench, entry["dataset"], runs) + got = scoring.contribution(normalized, benchmark=entry["benchmark"], version=entry["version"], datasets=manifests, + dataset=dataset, metric=entry["metric"], graded=bench.get("score", {}).get("kind") == "score") + evidence.update(score=got.score, tasks=got.total, covered=got.covered, excluded=got.excluded, + runs=list(got.run_ids), reason=got.reason, note=got.note) + if entry["weight"] > 0 and got.score is not None: + for run_id, _, attempts in got.tasks: + for trial in attempts: + if not trial.is_infra: + trials[(run_id, trial.trial_name)] = trial + entries.append(evidence) + score, shares = weights.combine((e["score"], e["weight"]) for e in entries) + for evidence, share in zip(entries, shares): + evidence["share"] = share + if evidence["unverified"] and evidence["name"] not in row["custom_names"]: + row["custom_names"].append(evidence["name"]) + row["axes"][name] = {"score": score, "weight": axis["weight"], "share": 0, "entries": entries, + "unverified": any(e["unverified"] and e["share"] > 0 for e in entries)} + row["overall"], shares = weights.combine((a["score"], a["weight"]) for a in row["axes"].values()) + for axis, share in zip(row["axes"].values(), shares): + axis["share"] = share + row["unverified"] = any(a["unverified"] and a["share"] > 0 for a in row["axes"].values()) + for metric, field in (("time", "dur_agent"), ("cost", "cost_usd")): + values = [getattr(t, field) for t in trials.values() if getattr(t, field) is not None and isfinite(getattr(t, field)) and getattr(t, field) >= 0] + row["metrics"][metric] = {"value": sum(values) / len(values) if values else None, "count": len(values)} + rows.append(row) + if metric_sources is not None: + metric_sources[key] = tuple(dict.fromkeys(t.trajectory_path for t in trials.values())) + required = {name: {_entry_key(e) for row in rows for e in row["axes"][name]["entries"] + if "custom" not in e and e["available"] and e["weight"] > 0 and e["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 or "custom" in entry: + continue + reason = (f"{entry['name']} not run" if entry["score"] is None else + f"{entry['name']} full task coverage unavailable" if entry["tasks"] is None else + f"{entry['name']} {entry['covered']} of {entry['tasks']} tasks" if entry["covered"] < entry["tasks"] else "") + if reason and reason not in row["reasons"]: + row["reasons"].append(reason) + for family, axes in (("capabilities", configuration.CAPABILITIES), ("domains", configuration.DOMAINS)): + needed = [a for a in axes if required.get(a)] + present = sum(row["axes"][a]["score"] is not None for a in needed) + if present < len(needed): + row["reasons"].append(f"{present} of {len(needed)} {family}") + rows = weights.rank(rows) + averages = {} + for name in configuration.AXES: + values = [r["axes"][name]["score"] for r in rows if r["axes"][name]["score"] is not None] + averages[name] = {"score": sum(values) / len(values) if values else None, "count": len(values)} + return {"rows": rows, "axes": list(configuration.AXES), "domains": list(configuration.DOMAINS), + "capabilities": list(configuration.CAPABILITIES), "averages": averages, + "selected": rows[0]["key"] if rows else None, "all_scores": all_scores, + "empty": "No workspace open" if not workspace_open else "No scored runs in this workspace" if not any(r["has_runs"] for r in rows) else ""} diff --git a/app/nullius/leaderboard/cli.py b/app/nullius/leaderboard/cli.py new file mode 100644 index 00000000..574ccea8 --- /dev/null +++ b/app/nullius/leaderboard/cli.py @@ -0,0 +1,54 @@ +"""Read workspace composite scores without launching evaluations.""" +from __future__ import annotations + +import argparse +import json +import os +import sys + +from nullius.runs import parse +from . import configuration, service, weights + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="nullius leaderboard", description=__doc__, + epilog="Configuration: scoring.json in the profile configuration directory (nullius paths). Edit it through Scoring settings or as a complete JSON document. Exit 0: read; 2: usage; 3: missing root. Unavailable measurements and invalid-settings fallback are disclosed in the output.") + parser.add_argument("roots", nargs="*", help="result roots in one workspace; omit for catalogue rows without recorded-run measurements; --all-scores can still include saved manual scores") + parser.add_argument("--json", action="store_true", help="full precision scores, identity, evidence, ranks/reasons and observed metric counts") + parser.add_argument("--all-scores", action="store_true", help="include unverified manual scores; default: verified only") + args = parser.parse_args(argv) + if any(not os.path.isdir(root) for root in args.roots): + print("A result root does not exist or is not a directory.", file=sys.stderr) + return 3 + result = service.document(parse.load_all(args.roots), workspace_open=bool(args.roots), all_scores=args.all_scores, deferred=True) + if args.json: + print(json.dumps(result, ensure_ascii=False, allow_nan=False)) + else: + if result["warning"]: + print(result["warning"]) + if result["empty"]: + print(result["empty"]) + for row in result["rows"]: + print(f"{row['rank'] or ''}\t{row['name']}\t{row['company']}\t{row['version_label']}\t{weights.percent(row['overall'])}") + setup = " · ".join(str(row["identity"][key]) for key in ("model", "effort") if row["identity"].get(key)) + if setup: + print(f" {setup}") + for name in configuration.AXES: + axis = row["axes"][name] + print(f" {name}: {weights.percent(axis['score'])} · weight {axis['weight']:g} · share {weights.percent(axis['share'])}") + for entry in axis["entries"]: + version = f" · {entry['version'] or 'Official'}" if "custom" not in entry else "" + reading = weights.percent(entry["score"]) if entry["score"] is not None else entry["reason"] + trust = " · not verified" if entry["unverified"] else "" + tasks = f" · {entry['covered']}/{entry['tasks']} tasks" if entry["tasks"] is not None else "" + runs = " · runs " + ", ".join(entry["runs"]) if entry["runs"] else "" + print(f" {entry['name']}{version} · {reading}{trust} · weight {entry['weight']:g} · share {weights.percent(entry['share'])}{tasks}{runs}") + for reason in row["reasons"]: + print(f" Not ranked: {reason}") + for metric, data in row["metrics"].items(): + print(f" {metric}: {data['value'] if data['value'] is not None else 'unavailable'} ({data['count']} observed)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/nullius/leaderboard/configuration.py b/app/nullius/leaderboard/configuration.py new file mode 100644 index 00000000..cc63d730 --- /dev/null +++ b/app/nullius/leaderboard/configuration.py @@ -0,0 +1,131 @@ +"""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 +OVERALL = (.12, .12, .08, .15, .15, .10, .08, .20, 0, 0, 0, 0, 0, 0, 0) +DEFAULT_ENTRIES = { + "Consistency": [("tau3-bench", "", "pass^3")], + "Retrieval": [("gaia", "", "Score"), ("tau3-bench", "banking_knowledge", "Score")], + "Communication": [("tau3-bench", "telecom", "Score")], + "Execution": [(k, "", "Score") for k in ("osworld1", "osworld2", "swe-bench-verified", "terminal-bench")], + "Travel": [("tau3-bench", "airline", "Score")], + "Shopping": [("tau3-bench", "retail", "Score")], + "Money": [("tau3-bench", "banking_knowledge", "Score")], + "Home": [("tau3-bench", "telecom", "Score"), ("osworld1", "os", "Score")], + "Work": [("osworld1", "office", "Score"), ("swe-bench-verified", "", "Score"), + ("terminal-bench", "", "Score"), ("open-telco", "teleqna-lite", "Score")], +} + + +def location(): + return Path(paths.config_dir()) / "scoring.json" + + +def defaults(benchmarks): + versions = {b["key"]: definitions.version_identity(b) for b in benchmarks + if b.get("_version") == b.get("_default")} + return {"schema": 1, "custom": [], "axes": { + axis: {"weight": weight, "entries": [ + {"benchmark": key, "dataset": dataset, "version": versions[key], "metric": metric, "weight": 1} + for key, dataset, metric in DEFAULT_ENTRIES.get(axis, []) if key in versions]} + for axis, weight in zip(AXES, OVERALL)}} + + +def _number(value, label, upper=None): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0 or (upper is not None and value > upper): + raise ValueError(f"{label}: enter a finite number between 0 and {upper}" if upper is not None else f"{label}: enter a finite nonnegative number") + + +def validate(document, benchmarks, *, previous=None, allow_unavailable=False): + """Validate every field before a write; preserve removed catalogue references.""" + if not isinstance(document, dict) or set(document) != {"schema", "custom", "axes"} or document["schema"] != 1: + raise ValueError("Invalid scoring document") + doc = copy.deepcopy(document) + if not isinstance(doc["axes"], dict) or set(doc["axes"]) != set(AXES) or not isinstance(doc["custom"], list): + raise ValueError("Scoring requires all fifteen axes and a custom benchmark list") + ids, names = set(), set() + for custom in doc["custom"]: + if not isinstance(custom, dict) or set(custom) != {"id", "name", "scores"}: + raise ValueError("Invalid custom benchmark") + key, name = custom["id"], custom["name"] + if not isinstance(key, str) or not key or key in ids or not isinstance(name, str) or not name.strip() or name.strip().casefold() in names: + raise ValueError("Custom benchmarks need unique IDs and nonempty unique names") + custom["name"] = name.strip() + ids.add(key) + names.add(name.strip().casefold()) + if not isinstance(custom["scores"], dict) or not all(isinstance(k, str) and k for k in custom["scores"]): + raise ValueError("Custom scores require stable row keys") + for value in custom["scores"].values(): + if value is not None: + _number(value, "Custom score", 100) + available = {(b["key"], 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 = set() + for entry in axis["entries"]: + if not isinstance(entry, dict): + raise ValueError(f"{name}: invalid entry") + _number(entry.get("weight"), f"{name} entry weight") + if "custom" in entry: + if set(entry) != {"custom", "weight"} or entry["custom"] not in ids: + raise ValueError("Unknown custom benchmark") + identity = ("custom", entry["custom"]) + else: + if set(entry) != {"benchmark", "dataset", "version", "metric", "weight"} or not all(isinstance(entry[k], str) for k in ("benchmark", "dataset", "version", "metric")) or not entry["benchmark"]: + raise ValueError("Invalid benchmark entry") + bench = available.get((entry["benchmark"], entry["version"])) + if entry["metric"] not in ("Score", "pass^3") or (entry["metric"] == "pass^3" and bench is not None and (bench.get("score") or {}).get("kind") != "pass"): + raise ValueError("Choose Score or supported pass^3") + identity = tuple(entry[k] for k in ("benchmark", "dataset", "version", "metric")) + if bench is None and not allow_unavailable and identity not in preserved: + raise ValueError("Choose a catalogue benchmark version") + if (bench is not None and entry["dataset"] and entry["dataset"] not in {c["id"] for c in scopes.choices(bench)} + and not allow_unavailable and identity not in preserved): + raise ValueError("Choose a declared dataset or task-name part") + if identity in seen: + raise ValueError(f"{name}: duplicate entry") + seen.add(identity) + if not any(axis["weight"] > 0 for axis in doc["axes"].values()): + raise ValueError("At least one Weight in Overall must be positive") + return doc + + +def remove_custom(document, key): + doc = copy.deepcopy(document) + doc["custom"] = [c for c in doc["custom"] if c["id"] != key] + for axis in doc["axes"].values(): + axis["entries"] = [e for e in axis["entries"] if e.get("custom") != key] + return doc + + +def load(path, benchmarks): + try: + return validate(json.loads(Path(path).read_text()), benchmarks, allow_unavailable=True), "" + except FileNotFoundError: + return defaults(benchmarks), "" + except (OSError, ValueError, TypeError): + return defaults(benchmarks), "Scoring settings could not be read; defaults are active." + + +def save(path, document, benchmarks): + previous, _ = load(path, benchmarks) + doc = validate(document, benchmarks, previous=previous) + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + ondisk.write_whole(path, json.dumps(doc, ensure_ascii=False, indent=2, allow_nan=False) + "\n", mode=0o600) + return doc diff --git a/app/nullius/leaderboard/metrics.py b/app/nullius/leaderboard/metrics.py new file mode 100644 index 00000000..5abfd836 --- /dev/null +++ b/app/nullius/leaderboard/metrics.py @@ -0,0 +1,47 @@ +"""Deferred trajectory counts, cached by file identity and content digest.""" +from __future__ import annotations + +import hashlib +from pathlib import Path +from threading import RLock + +from nullius.traces import trajectory + + +class Cache: + def __init__(self): + self._entries = {} + self._lock = RLock() + + def read(self, path): + missing = {"steps": None, "calls": None} + try: + target = Path(path) + info = target.stat() + signature = (info.st_dev, info.st_ino, hashlib.sha256(target.read_bytes()).hexdigest()) + except OSError: + return missing + with self._lock: + previous = self._entries.get(path) + if previous and previous[0] == signature: + return dict(previous[1]) + try: + trace = trajectory.load(path) + result = missing if trace.error else {"steps": trace.n_steps, "calls": trace.n_tool_calls} + # A writer may have changed the file while its parser read it. + if hashlib.sha256(target.read_bytes()).hexdigest() != signature[2]: + return missing + except (OSError, ValueError, TypeError, KeyError): + result = missing + self._entries[path] = (signature, result) + return dict(result) + + def complete(self, document, sources): + for row in document["rows"]: + observations = [self.read(path) for path in sources.get(row["key"], ())] + for field in ("steps", "calls"): + values = [o[field] for o in observations if o[field] is not None] + row["metrics"][field] = {"value": sum(values) / len(values) if values else None, "count": len(values)} + + +CACHE = Cache() diff --git a/app/nullius/leaderboard/scopes.py b/app/nullius/leaderboard/scopes.py new file mode 100644 index 00000000..316db2de --- /dev/null +++ b/app/nullius/leaderboard/scopes.py @@ -0,0 +1,24 @@ +"""Declared dataset and task-name parts, with no guessed task aliases.""" +from dataclasses import replace + + +def choices(benchmark): + return [{"id": d["id"], "label": d.get("label", d["id"])} + for d in benchmark.get("datasets", []) + benchmark.get("task_parts", [])] + + +def select(benchmark, dataset, runs): + manifests = {d["id"]: d.get("tasks") if isinstance(d.get("tasks"), dict) else None + for d in benchmark.get("datasets", [])} + recorded = {f"{benchmark['key']}/{d}": d for d in manifests} + normalized = [replace(j, dataset=recorded.get(j.dataset, j.dataset)) for j in runs] + part = next((p for p in benchmark.get("task_parts", []) if p["id"] == dataset), None) + if part: + prefixes = tuple(part["prefixes"]) + matches = lambda name: name.startswith(prefixes) + manifests = {d: {n: canonical for n, canonical in m.items() if matches(n)} if m is not None else None + for d, m in manifests.items()} + normalized = [replace(j, trials=[t for t in j.trials if matches(t.task_name)]) for j in normalized] + normalized = [j for j in normalized if j.trials] + dataset = "" + return manifests, normalized, dataset diff --git a/app/nullius/leaderboard/scoring.py b/app/nullius/leaderboard/scoring.py new file mode 100644 index 00000000..3e395c4d --- /dev/null +++ b/app/nullius/leaderboard/scoring.py @@ -0,0 +1,131 @@ +"""Select one run per dataset and score distinct tasks with their recorded attempts. + +Dataset manifests map recorded task names to canonical identities. None means +identity/coverage is unknown; it never means an empty dataset. This module reads +no files and does not modify the jobs whose raw metrics other pages display. +""" +from __future__ import annotations + +from dataclasses import dataclass +from datetime import timezone +from math import isfinite +from typing import Mapping, Sequence + +from nullius.runs import attempts, classify +from nullius.runs.parse import Job, Trial + + +@dataclass(frozen=True) +class Contribution: + score: float | None = None + covered: int = 0 + total: int | None = None + excluded: int = 0 + run_ids: tuple[str, ...] = () + reason: str = "not run" + note: str = "" + # Selected task evidence, for efficiency deduplication and run links. + tasks: tuple[tuple[str, str, tuple[Trial, ...]], ...] = () + + +def eligible(job: Job) -> bool: + return bool(job.finished_at and not job.is_running and not job.is_preparing and not job.is_control) + + +def _groups(job, manifest=None): + result = {} + for trial in job.trials: + key = manifest.get(trial.task_name, trial.task_name) if manifest is not None else trial.task_name + result.setdefault(key, []).append(trial) + return result + + +def _precedence(job, manifest=None): + count = sum(bool(attempts.ran(ts)) for ts in _groups(job, manifest).values()) + at = job.finished_at + stamp = (at if at.tzinfo else at.replace(tzinfo=timezone.utc)).timestamp() + return -count, -stamp, job.job_id + + +def _score(ts, graded): + ran = attempts.ran(ts) + if not graded: + grouped = attempts.Attempts(tuple(ts)) + return grouped.rate if grouped.has_verdicts else None + values = [] + for t in ran: + if t.outcome == classify.AGENT_ERROR: + values.append((0, t.n_parts or 1)) + elif t.score is not None: + if isinstance(t.score, bool) or not isinstance(t.score, (int, float)) or not isfinite(t.score) or not 0 <= t.score <= 1: + raise ValueError("Unsupported score scale") + values.append((t.score, t.n_parts or 1)) + return sum(score * parts for score, parts in values) / sum(parts for _, parts in values) if values else None + + +def contribution(jobs: Sequence[Job], *, benchmark: str, version: str, + datasets: Mapping[str, Mapping[str, str] | None], dataset: str = "", + metric: str = "Score", graded: bool = False) -> Contribution: + """Select by coverage, finish and qualified run id, never by outcome. + +The caller passes one agent/version/setup row and qualified job ids. A selected +dataset reads only that dataset. Whole entries require explicit identities to +join several datasets; they cannot infer overlap from short task names. +""" + if metric not in ("Score", "pass^3") or (graded and metric != "Score"): + raise ValueError("Choose Score or supported pass^3") + scope = {dataset: datasets[dataset]} if dataset in datasets else ({} if dataset else dict(datasets)) + if not scope: + return Contribution(reason="Dataset unavailable") + manifests = list(scope.values()) + total = len({canonical for manifest in manifests for canonical in manifest.values()}) if all(m is not None for m in manifests) else None + pool = [j for j in jobs if eligible(j) and j.dataset in scope + and j.identity.get("benchmark") == benchmark + and 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]) + for j in sorted(pool, key=precedence): + selected.setdefault(j.dataset, j) + ids = tuple(j.job_id for j in selected.values()) + if not selected: + 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()) + groups = [ts for _, _, ts in tasks] + excluded = sum(not attempts.ran(ts) for ts in groups) + covered = sum(bool(attempts.ran(ts)) for ts in groups) + note = "" + if graded: + n_grades = sum(t.score is not None and not t.is_infra for ts in groups for t in ts) + crashes = sum(t.outcome == classify.AGENT_ERROR for ts in groups for t in ts) + note = f"{n_grades} graded, {crashes} agent crashes; crashes count as 0" + reason = "" + if metric == "pass^3": + estimate = attempts.for_tasks(groups) + score = estimate["hat"].get(3) if estimate else None + if score is None: + reason = "Three recorded attempts per eligible task required" + # An infra attempt makes the entire unit ineligible for pass^k. + covered = sum(bool(ts) and len(ts) >= 3 and not any(t.is_infra or t.outcome == classify.SCORED for t in ts) for ts in groups) + else: + try: + scores = [_score(ts, graded) for ts in groups] + measured = [v for v in scores if v is not None] + score = sum(measured) / len(measured) if measured else None + if score is None: + reason = "No measured outcomes" + except ValueError as error: + score, reason = None, str(error) + return Contribution(score, covered, total, excluded, ids, reason, note, tasks) diff --git a/app/nullius/leaderboard/service.py b/app/nullius/leaderboard/service.py new file mode 100644 index 00000000..c2f91205 --- /dev/null +++ b/app/nullius/leaderboard/service.py @@ -0,0 +1,58 @@ +"""Catalogue and profile inputs shared by the Leaderboard page and command.""" +from __future__ import annotations + +import hashlib +import json +from dataclasses import asdict +from urllib.parse import quote + +from nullius.standard.contract import definitions +from nullius import charts +from . import board, configuration, metrics, weights, scopes + + +def catalogue(): + return definitions.load("agent", every=True)[0], definitions.load("benchmark", every=True)[0] + + +def revision(): + try: + raw = configuration.location().read_bytes() + except FileNotFoundError: + raw = b"" + return hashlib.sha256(raw).hexdigest() + + +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)} + for b in benchmarks] + + +def document(jobs, *, workspace="", workspace_open=False, all_scores=False, deferred=False): + agents, benchmarks = catalogue() + settings, warning = configuration.load(configuration.location(), benchmarks) + sources = {} + result = board.build(jobs, agents, benchmarks, settings, all_scores=all_scores, workspace_open=workspace_open, metric_sources=sources) + context = {"workspace": workspace, "settings": settings, "all_scores": all_scores, + "jobs": [(j.job_id, j.uid, str(j.finished_at), len(j.trials), j.identity, j.dir) for j in jobs]} + result["context"] = hashlib.sha256(json.dumps(context, sort_keys=True).encode()).hexdigest() + result["warning"], result["revision"] = warning, revision() + result["versions"] = [{"benchmark": b["key"], "version": definitions.version_identity(b), + "label": b["label"] + " · " + ((definitions.version_label(b) or definitions.version_identity(b)[:7]) or "Official")} + for b in benchmarks if any(e.get("benchmark") == b["key"] for a in settings["axes"].values() for e in a["entries"])] + for row in result["rows"]: + for axis in row["axes"].values(): + for entry in axis["entries"]: + entry["links"] = [{"id": id, "url": "/job/" + quote(id, safe="") + ("?workspace=" + quote(workspace, safe="") if workspace else "")} for id in entry["runs"]] + if deferred: + metrics.CACHE.complete(result, sources) + result["scatter"] = {} + for field, label in (("time", "Time (seconds)"), ("cost", "Cost (USD)")): + x = charts.Metric(label, tuple(charts.Value(r["name"], r["metrics"][field]["value"], str(r["metrics"][field]["value"]), + note=r["version_label"], tag=r["name"], key=r["key"]) for r in result["rows"]), bounds=(0, None)) + y = charts.Metric("Overall", tuple(charts.Value(r["name"], r["overall"], weights.percent(r["overall"])) for r in result["rows"]), + fmt=lambda v, step, top: weights.percent(v), bounds=(0, 1)) + result["scatter"][field] = asdict(charts.scatter(x, y, tiles=True)) + return result diff --git a/app/nullius/leaderboard/weights.py b/app/nullius/leaderboard/weights.py new file mode 100644 index 00000000..575d4971 --- /dev/null +++ b/app/nullius/leaderboard/weights.py @@ -0,0 +1,36 @@ +"""Measured weight shares, percentage formatting and competition ranking.""" +from __future__ import annotations + + +def combine(values): + """A missing measurement has no effective share, including a positive weight.""" + values = list(values) + scale = max((w for score, w in values if score is not None and w > 0), default=0) + total = sum(w / scale for score, w in values if score is not None and w > 0) if scale else 0 + shares = [(w / scale) / total if total and score is not None and w > 0 else 0 for score, w in values] + return (sum(score * share for (score, _), share in zip(values, shares) if share) if total else None), shares + + +def percent(value): + return f"{100 * value:.1f}".rstrip("0").rstrip(".") + "%" if value is not None else "—" + + +def rank(rows, sort="overall", descending=True): + """Assign ranks from full precision, then sort within eligibility groups.""" + rows = [dict(row, rank=None) for row in rows] + eligible = sorted((r for r in rows if r["overall"] is not None and not r["reasons"]), + key=lambda r: (-r["overall"], r["name"], r["key"])) + previous, assigned = None, None + for i, row in enumerate(eligible, 1): + if row["overall"] != previous: + assigned = i + row["rank"], previous = assigned, row["overall"] + groups = [eligible, [r for r in rows if r["overall"] is not None and r["reasons"]], + [r for r in rows if r["overall"] is None]] + result = [] + for group in groups: + group.sort(key=lambda r: (r["name"], r["key"])) + present = [r for r in group if r.get(sort) is not None] + absent = [r for r in group if r.get(sort) is None] + result.extend(sorted(present, key=lambda r: r[sort], reverse=descending) + absent) + return result diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index ad5f8918..c344a3bb 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -166,7 +166,7 @@ def setup_label(bench, which): # What a version may say for itself; the rest of the file is shared. VERSIONED = ("upstream", "install", "start", "model", "env", "options", "caches", "fidelity", "proven") # What a benchmark's version may say for itself: its data, its driver, how it scores, who plays its user, its environments. -BENCH_VERSIONED = ("upstream", "datasets", "files", "driver", "mcp_servers", "score", "simulator", "limits", "controls", "environments", +BENCH_VERSIONED = ("upstream", "datasets", "task_parts", "files", "driver", "mcp_servers", "score", "simulator", "limits", "controls", "environments", "options", "host", "setups", "proven", "leaderboard") # What a benchmark option may need: embedding and reranker models through the relay, # machine requirements (host), and digest-pinned auxiliary files. @@ -250,6 +250,11 @@ def _version_upstream(d: dict, v: str) -> dict: return dict(up, **own, version=v) +def version_identity(d: dict) -> str: + """The explicit release identity, or the pinned source commit of an unversioned definition.""" + return str(d.get("_version") or (d.get("upstream") or {}).get("tested") or "") + + def version_label(d: dict) -> str: """A version as a reader names it: its release tag, else its branch and short commit (``main (044bc33)``), else its key.""" @@ -1552,6 +1557,8 @@ def problems(d: dict, kind: str) -> List[str]: bad.append(f"{f}: say it") if "example" in d and (kind == "benchmark" or not isinstance(d["example"], bool)): bad.append("example: true or false, an agent's or a capability's") + if "company" in d and (kind != "agent" or not isinstance(d["company"], str) or not d["company"].strip()): + bad.append("company: nonempty text on an agent definition") bad += _upstream(d.get("upstream")) if kind == "benchmark": if d.get("family") not in FAMILIES: @@ -1560,6 +1567,20 @@ def problems(d: dict, kind: str) -> List[str]: bad += _ports("needs", needs, d.get("family")) if isinstance(needs, list) and not needs: bad.append("needs: at least one port") + parts = d.get("task_parts", []) + seen_parts = {x.get("id") for x in (d.get("datasets") or []) if isinstance(x, dict)} + if not isinstance(parts, list): + bad.append("task_parts: a list of named task-prefix selections") + else: + for part in parts: + if (not isinstance(part, dict) or set(part) != {"id", "label", "prefixes"} + or not isinstance(part["id"], str) or not part["id"] or part["id"] in seen_parts + or not isinstance(part["label"], str) or not part["label"].strip() + or not isinstance(part["prefixes"], list) or not part["prefixes"] + or any(not isinstance(p, str) or not p for p in part["prefixes"])): + bad.append("task_parts: unique id, label and nonempty task-name prefixes required") + else: + seen_parts.add(part["id"]) bad += _host(d) bad += _files(d) bad += _bench_options(d) diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index ab4ad58f..b9d449ad 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -32,6 +32,7 @@ from nullius import ondisk from nullius.standard.calls import ledger +from nullius.standard.contract import definitions from nullius.traces import otel from nullius.traces.breakdown import breakdown @@ -225,9 +226,8 @@ def agent_name(other: dict) -> str: def _version(bench: dict) -> dict: - """A benchmark with versions says which one ran (``benchmark_version``), and the - ``key@version`` that names it; one without says nothing more than its key.""" - v = bench.get("_version") if "@" in str(bench.get("_ref") or "") else None + """Record the explicit benchmark release or source pin, never an inferred current default.""" + v = definitions.version_identity(bench) return {"benchmark_version": v, "benchmark_ref": bench["_ref"]} if v else {} diff --git a/app/packaging/verify.py b/app/packaging/verify.py index 8df53432..49f6ab86 100644 --- a/app/packaging/verify.py +++ b/app/packaging/verify.py @@ -59,6 +59,8 @@ def digest(): web.app.config.update(TESTING=True) client = web.app.test_client() pages = ['/', '/benchmarks', '/agents', '/capabilities', '/settings', + '/leaderboard', '/scoring', '/api/leaderboard', '/api/scoring', + '/static/catalogue/agents/swe-agent.ico', '/static/catalogue/agents/digitalmate.svg', '/static/style.css', '/static/fonts/DMSans-Regular.woff2', '/static/fonts/dmsans-OFL.txt', '/static/brand/favicon.svg', '/static/brand/typesafe.png'] diff --git a/app/static/catalogue/agents/README.md b/app/static/catalogue/agents/README.md index 35fd9b58..d4210226 100644 --- a/app/static/catalogue/agents/README.md +++ b/app/static/catalogue/agents/README.md @@ -7,6 +7,8 @@ rendering a logo makes no request to its upstream website. | Agent | Asset source | | --- | --- | +| DigitalMate | ThinkFlowLab supplied ThinkFlow Orbit artwork: cream rounded tile, charcoal orb and ring, orange satellite (`digitalmate.svg`) | +| SWE-agent | [Official repository favicon](https://github.com/SWE-agent/SWE-agent/blob/3ea751c087f32b16e039a2233dd6eefecef325d5/docs/assets/favicon.ico), copied unchanged (`swe-agent.ico`) | | Codex | OpenAI's mark in `../../brand/marks.svg`, identifying its maker | | Goose | [Official repository logo](https://github.com/block/goose/blob/775b3958c394ae2747cfb01791d3a45ac579139a/documentation/static/img/logo.svg) | | JiuwenSwarm | [Official application logo](https://github.com/openJiuwen-ai/jiuwenswarm/blob/ffc539d74ba6fe034c60b6eac5ae3ea1da04b7dc/jiuwenswarm/channels/web/frontend/public/logo.svg) | @@ -14,5 +16,5 @@ rendering a logo makes no request to its upstream website. | OpenCode | [Official favicon](https://github.com/anomalyco/opencode/blob/66f1fa816d583fdfa0f52eff1c7d56c8458b1c4e/packages/ui/src/assets/favicon/favicon.svg) | | Terminus 2 | Harbor's mark in `../../brand/marks.svg`, identifying its maker | -The four SVG files are copied unchanged from these pinned sources. These marks +Upstream assets are copied unchanged from these pinned sources. These marks belong to their respective owners; inclusion does not imply endorsement. diff --git a/app/static/catalogue/agents/digitalmate.svg b/app/static/catalogue/agents/digitalmate.svg new file mode 100644 index 00000000..0354755a --- /dev/null +++ b/app/static/catalogue/agents/digitalmate.svg @@ -0,0 +1 @@ +ThinkFlow Orbit diff --git a/app/static/catalogue/agents/marks.json b/app/static/catalogue/agents/marks.json index e1dda87d..8c4b41d4 100644 --- a/app/static/catalogue/agents/marks.json +++ b/app/static/catalogue/agents/marks.json @@ -4,5 +4,7 @@ "mini-swe-agent": "catalogue/agents/mini-swe-agent.svg", "opencode": "catalogue/agents/opencode.svg", "codex": "brand/marks.svg#openai", - "terminus-2": "brand/marks.svg#harbor" + "terminus-2": "brand/marks.svg#harbor", + "digitalmate": "catalogue/agents/digitalmate.svg", + "swe-agent": "catalogue/agents/swe-agent.ico" } diff --git a/app/static/catalogue/agents/swe-agent.ico b/app/static/catalogue/agents/swe-agent.ico new file mode 100644 index 00000000..b3342de0 Binary files /dev/null and b/app/static/catalogue/agents/swe-agent.ico differ diff --git a/app/static/leaderboard/board.js b/app/static/leaderboard/board.js new file mode 100644 index 00000000..24b9118b --- /dev/null +++ b/app/static/leaderboard/board.js @@ -0,0 +1,158 @@ +/* Shared row selection; filters affect the table alone. Text is always inserted as text. */ +(() => { + let data = JSON.parse(document.getElementById('lb-data').textContent); + const marks = JSON.parse(document.getElementById('lb-marks').textContent), table = document.getElementById('leaderboard-table'); + let selected = data.selected, versus = 'average', family = 'capabilities', metric = 'time', generation = 0, focusBefore = null, projection = null, comparisonGeneration = 0, returningFocus = false, tableMotion = null; + const motion=window.LeaderboardMotion; + const percent = v => v == null ? '—' : `${Number((v * 100).toFixed(1))}%`; + const element = (tag, text, attrs = {}) => { const e = document.createElement(tag); if (text != null) e.textContent = text; Object.entries(attrs).forEach(([k,v]) => e.setAttribute(k,v)); return e; }; + const svg = (tag, attrs = {}, text) => { const e = document.createElementNS('http://www.w3.org/2000/svg',tag); Object.entries(attrs).forEach(([k,v]) => e.setAttribute(k,v)); if (text != null) e.textContent = text; return e; }; + const row = key => data.rows.find(r => r.key === key); + const compared = axis => versus === 'average' ? data.averages[axis]?.score : versus.startsWith('version:') ? projection?.rows.find(r=>r.key===selected)?.axes[axis]?.score : row(versus)?.axes[axis]?.score; + const delta = (a,b) => a == null || b == null ? '—' : `${a >= b ? '+' : ''}${((a-b)*100).toFixed(1)} pp`; + const pop = document.getElementById('lb-evidence'); + function dismiss() { pop.hidden = true; } + function evidence(target) { + const current = row(target.closest('tr')?.dataset.key || selected); if (!current) return; + const axisName = target.dataset.axis; if (!axisName) return; + pop.replaceChildren(element('strong', axisName)); + if (axisName === 'Overall') { + current.reasons.forEach(reason => pop.append(element('p', `Not ranked: ${reason}`))); + pop.append(element('p',[current.identity.model,current.identity.effort].filter(Boolean).join(' · '))); + data.axes.map(name=>[name,current.axes[name]]).filter(([,a]) => a.weight > 0).forEach(([name,a]) => { + const names = a.entries.filter(e => e.unverified && e.share > 0).map(e => e.name); + pop.append(element('p', `${name} · ${percent(a.score)} · weight ${a.weight} · share ${percent(a.share)}${names.length ? ' · '+names.join(', ')+' · not verified' : ''}`)); + }); + } else { + const axis = current.axes[axisName]; + if (!axis.entries.length) pop.append(element('p','No benchmark')); + axis.entries.forEach(e => { + const line = element('p', `${e.name}${e.version ? ' · '+e.version : ''} · ${e.score == null ? e.reason || 'not run' : percent(e.score)}${e.unverified ? ' · not verified' : ''} · ${innerWidth <= 700 ? 'x' : 'weight'} ${e.weight} · share ${percent(e.share)}`); + if (!e.custom && e.tasks != null) line.append(element('span', ` · ${e.covered}/${e.tasks} tasks`, {class:e.covered === e.tasks ? 'lb-complete-count' : ''})); + (e.links || []).forEach(link => { line.append(document.createTextNode(' · '),element('a',link.id,{href:link.url})); }); + if (e.note) line.append(document.createTextNode(` · ${e.note}`)); + pop.append(line); + }); + } + focusBefore = target; pop.hidden = false; + const box = target.getBoundingClientRect(); + pop.style.left = `${Math.max(12,Math.min(box.left,innerWidth-pop.offsetWidth-12))}px`; + pop.style.top = `${Math.max(12,Math.min(box.bottom+6,innerHeight-pop.offsetHeight-12))}px`; + } + document.addEventListener('keydown', e => { if (e.key === 'Escape') { dismiss(); returningFocus=true;focusBefore?.focus();returningFocus=false; } }); + document.addEventListener('pointerdown', e => { if (!pop.contains(e.target) && !e.target.closest('[data-axis]')) dismiss(); }); + document.addEventListener('focusin', e => { const target=e.target.closest('[data-axis]'); if(target&&!returningFocus) evidence(target); }); + document.addEventListener('pointerover', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); + document.addEventListener('click', e => { const target=e.target.closest('[data-axis]'); if(target) evidence(target); }); + function medal(rank) { + if (!rank) return document.createTextNode(''); + if (rank > 4) return document.createTextNode(String(rank)); + const names=['gold','silver','bronze','chocolate']; + const span=element('span',null,{class:`lb-medal lb-medal-${rank}`,'aria-label':`Rank ${rank}, ${names[rank-1]}`}); + const icon=svg('svg',{'aria-hidden':'true',viewBox:'0 0 24 24'});icon.append(svg('use',{href:rank===4?'#i-medal-bitten':'#i-medal'}));span.append(icon,element('span',rank));return span; + } + function updateTable() { + tableMotion?.capture(); + const focused=document.activeElement; + data.rows.forEach(r => { + const tr = [...table.tBodies[0].rows].find(t => t.dataset.key === r.key); if (!tr) return; + tr.dataset.sortTie = r.name + ' ' + r.version_label + ' ' + r.key; + tr.dataset.sortGroup = r.rank ? 0 : r.overall != null ? 1 : 2; + tr.dataset.fStatus = `${r.rank ? 'ranked' : 'not-ranked'}${!r.has_runs?'\nno-run':''}`; + tr.querySelector('[data-col="rank"]').replaceChildren(medal(r.rank)); + tr.querySelector('[data-col="rank"]').dataset.sort=r.rank || ''; + const same = data.rows.filter(v=>v.agent===r.agent && v.version===r.version).length>1; + tr.querySelector('[data-name]').textContent = r.name + (same ? ' · '+[r.identity.model,r.identity.effort].filter(Boolean).join(' ') : ''); + tr.querySelectorAll('[data-axis]').forEach(cell => { + const a=cell.dataset.axis==='Overall'?{score:r.overall,unverified:r.unverified}:r.axes[cell.dataset.axis]; + let value=cell.querySelector('.lb-value');if(!value){cell.replaceChildren();value=element('span',null,{class:'lb-value'});cell.append(value);} + value.textContent=percent(a.score);cell.dataset.sort=a.score??''; + cell.classList.toggle('lb-unverified',Boolean(a.unverified)); + cell.style.setProperty('--lb-shade',`${a.score==null?0:Math.max(0,Math.min(1,(a.score-.2)/.6))*20}%`); + let bar=cell.querySelector('.lb-bar'); + if(a.score!=null){if(!bar){bar=element('span',null,{class:'lb-bar'});cell.append(bar);}bar.style.setProperty('--lb-value',`${a.score*100}%`);} + else bar?.remove(); + }); + for(const [field,m] of Object.entries(r.metrics)) { const cell=tr.querySelector(`[data-col="${field}"]`);cell.textContent=m.value==null?'—':field==='cost'?`$${m.value.toFixed(2)}`:Number(m.value.toFixed(1))+(field==='time'?'s':'');cell.dataset.sort=m.value??'';cell.title=`${m.count} observed`; } + table.tBodies[0].append(tr); + }); + let explicit=false;try {explicit=localStorage.getItem(table.id+'.cols')!==null;} catch {} + if(!explicit) data.axes.forEach(name=>{ + const cb=document.querySelector(`#${table.id}-tools input[data-col="${name}"]`); + if(cb) {cb.checked=data.averages[name].score!=null;table.querySelectorAll(`[data-col="${name}"]`).forEach(cell=>cell.style.display=cb.checked?'':'none');} + }); + table.dispatchEvent(new Event('table:update')); + document.getElementById('lb-trust-key').hidden=!data.rows.some(r=>r.custom_names.length); + applyFamily(); + if(focused?.isConnected&&document.activeElement!==focused)focused.focus({preventScroll:true}); + } + function applyFamily() { + document.querySelectorAll('[data-family]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.family===family))); + table.querySelectorAll('[data-col]').forEach(cell=> { if(data.axes.includes(cell.dataset.col)) cell.hidden=!data[family].includes(cell.dataset.col); }); + } + function choose(key) { if(!row(key)) return; selected=key;document.querySelectorAll('[data-agent-select]').forEach(s=>s.value=selected);draw(); } + document.addEventListener('click',e=>{const target=e.target.closest('[data-select]');if(target) choose(target.dataset.select);}); + function selectable(node,key,x,y) { node.setAttribute('tabindex','0');node.setAttribute('role','button');node.dataset.select=key;node.dataset.cx=x;node.dataset.cy=y;node.classList.add('lb-point');node.setAttribute('aria-label',`${row(key)?.name} ${row(key)?.version_label}`);node.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();choose(key);}});return node; } + function nearest(plot) { plot.addEventListener('click',e=>{if(e.target.closest('text[data-select]'))return;const pt=plot.createSVGPoint();pt.x=e.clientX;pt.y=e.clientY;const p=pt.matrixTransform(plot.getScreenCTM().inverse());const points=[...plot.querySelectorAll('[data-cx]')].map(n=>({n,d:Math.hypot(p.x-Number(n.dataset.cx),p.y-Number(n.dataset.cy))})).sort((a,b)=>a.d-b.d||a.n.dataset.select.localeCompare(b.n.dataset.select));if(points[0]&&points[0].d<30){e.stopPropagation();choose(points[0].n.dataset.select);}},true); } + function drawScatter() { + const live=document.getElementById('lb-scatter'),plot=svg('svg'), panel=data.scatter[metric];live.setAttribute('viewBox',`0 0 360 ${panel.height}`); + const defs=svg('defs'), gradient=svg('linearGradient',{id:'lb-efficiency-tint',x1:0,y1:0,x2:1,y2:1}); + gradient.append(svg('stop',{offset:'0%','stop-color':'var(--good)','stop-opacity':'.12'}),svg('stop',{offset:'50%','stop-color':'var(--bg)','stop-opacity':'0'}),svg('stop',{offset:'100%','stop-color':'var(--bad)','stop-opacity':'.12'}));defs.append(gradient);plot.append(defs,svg('rect',{x:48,y:22,width:304,height:210,fill:'url(#lb-efficiency-tint)'})); + plot.append(svg('text',{x:54,y:38,class:'lb-better'},'BETTER')); + for(const m of panel.marks) { + if(m.shape==='tile') { + const group=selectable(svg('g',{'data-node':'point:'+m.key}),m.key,m.x,m.y), mark=marks[m.key];group.append(svg('title',{},m.title)); + group.append(svg('rect',{x:m.x-11,y:m.y-11,width:22,height:22,rx:4,fill:'var(--bg)',class:m.key===selected?'lb-selected':''})); + if(mark?.includes('#')) {const icon=svg('svg',{x:m.x-9,y:m.y-9,width:18,height:18,viewBox:'0 0 24 24'});icon.append(svg('use',{href:mark}));group.append(icon);} + else if(mark) group.append(svg('image',{x:m.x-9,y:m.y-9,width:18,height:18,href:mark})); + else group.append(svg('text',{x:m.x,y:m.y+4,'text-anchor':'middle'},row(m.key)?.name.slice(0,1))); + plot.append(group); + } else plot.append(svg('line',{x1:m.x,y1:m.y,x2:m.x2,y2:m.y2,class:m.cls})); + } + for(const t of panel.texts) {const text=svg('text',{x:t.x,y:t.y,'text-anchor':t.anchor,class:t.cls});t.lines.forEach((line,i)=>text.append(svg('tspan',{x:t.x,dy:i?15:0,class:i?'small':''},line)));if(t.key) {text.dataset.node='name:'+t.key;text.dataset.select=t.key;text.setAttribute('tabindex','0');text.addEventListener('keydown',e=>{if(e.key==='Enter')choose(t.key);});}plot.append(text);} + motion.morph(live,plot); + } + nearest(document.getElementById('lb-scatter')); + function chart(kind,group) { + const container=document.querySelector(`[data-chart="${kind}-${group}"]`), names=data[group], current=row(selected);if(!current)return; + const plot=svg('svg',{viewBox:`0 0 360 ${kind==='strips'?names.length*42+20:320}`,role:'group','aria-label':`${group} ${kind}`}); + if(kind==='strips') names.forEach((name,i)=>{ + const y=30+i*42, label=svg('text',{x:0,y:y-10,tabindex:0,'data-axis':name},name);plot.append(label,svg('line',{x1:0,y1:y,x2:350,y2:y,class:'grid'})); + data.rows.forEach(r=>{const score=r.axes[name].score;if(score==null)return;const node=selectable(svg('circle',{cx:score*340+5,cy:y,'data-node':name+':'+r.key,'data-reveal':i,r:r.key===selected?5:3,class:r.key===selected?'lb-selected':''}),r.key,score*340+5,y);node.append(svg('title',{},`${r.name} ${r.version_label} ${r.identity.model||''}: ${percent(score)}${r.axes[name].unverified?' · not verified':''}`));plot.append(node);}); + const score=compared(name);if(score!=null){const x=score*340+5;plot.append(versus==='average'?svg('line',{x1:x,y1:y-8,x2:x,y2:y+8,class:'lb-comparison','stroke-dasharray':'2 2'}):svg('path',{d:`M${x} ${y-6}l6 6-6 6-6-6Z`,class:'lb-comparison'}));} + plot.append(svg('text',{x:350,y:y-10,'text-anchor':'end'},`${percent(current.axes[name].score)} / ${percent(score)}${versus==='average'?' (n='+data.averages[name].count+')':''}`)); + }); + else { + const at=(i,value)=>[180+Math.sin(i/names.length*2*Math.PI)*90*value,155-Math.cos(i/names.length*2*Math.PI)*90*value]; + names.forEach((name,i)=>{const [x,y]=at(i,1),[lx,ly]=at(i,1.3);plot.append(svg('line',{x1:180,y1:155,x2:x,y2:y,class:'grid'}));const label=svg('text',{x:Math.max(name.length*4,Math.min(360-name.length*4,lx)),y:ly,tabindex:0,'text-anchor':'middle','data-axis':name},name);plot.append(label);}); + for(const compare of [false,true]) names.forEach((name,i)=>{const score=compare?compared(name):current.axes[name].score;if(score==null)return;const [x,y]=at(i,score),next=(i+1)%names.length,v=compare?compared(names[next]):current.axes[names[next]].score;if(v!=null){const [nx,ny]=at(next,v);plot.append(svg('line',{x1:x,y1:y,x2:nx,y2:ny,'data-node':'segment:'+compare+':'+name,'data-reveal':i,class:'lb-radar-line'+(compare?' lb-comparison':'')}));}const point=svg('circle',{cx:x,cy:y,r:4,tabindex:0,'data-node':'point:'+compare+':'+name,'data-reveal':i,'data-axis':name,class:'lb-point'+(compare?' lb-comparison':'')});point.append(svg('title',{},`${name}: ${percent(score)}`));plot.append(point);}); + } + plot.querySelectorAll('text[data-axis]').forEach(label=>{ + const grow=on=>plot.querySelectorAll(`circle[data-axis="${label.dataset.axis}"]`).forEach(point=>point.classList.toggle('lb-hover',on)); + label.addEventListener('pointerenter',()=>grow(true));label.addEventListener('pointerleave',()=>grow(false)); + label.addEventListener('focus',()=>grow(true));label.addEventListener('blur',()=>grow(false)); + }); + const live=container.querySelector('svg'); + if(live)motion.morph(live,plot); + else {container.append(plot);nearest(plot);motion.reveal(plot,kind);} + } + function draw() { + const current=row(selected);if(!current)return; + const card=document.getElementById('lb-card');card.replaceChildren(element('h2',current.name),element('p',`${percent(current.overall)}${!current.rank?' · not ranked':''}`),element('p',[current.company,current.version_label,current.identity.model,current.identity.effort].filter(Boolean).join(' · '))); + card.append(element('p',`Covered: ${current.reasons.join('; ')||'All required entries'}`)); + const values=data.rows.map(r=>r.overall).filter(v=>v!=null), baseline=versus==='average'?(values.length?values.reduce((a,b)=>a+b,0)/values.length:null):versus.startsWith('version:')?projection?.rows.find(r=>r.key===selected)?.overall:row(versus)?.overall; + card.append(element('p',`Overall against ${versus==='average'?'Average':versus.startsWith('version:')?'benchmark version':row(versus)?.name}: ${delta(current.overall,baseline)}`)); + const differences=data.capabilities.map(name=>({name,a:current.axes[name].score,b:compared(name)})).filter(v=>v.a!=null&&v.b!=null).sort((a,b)=>(b.a-b.b)-(a.a-a.b)); + if(differences.length) card.append(element('p',`Best: ${differences[0].name} ${delta(differences[0].a,differences[0].b)}`),element('p',`Weakest: ${differences.at(-1).name} ${delta(differences.at(-1).a,differences.at(-1).b)}`)); + if(current.custom_names.length)card.append(element('p',`Not verified: ${current.custom_names.join(', ')}`)); + drawScatter();for(const kind of ['strips','radars'])for(const group of ['domains','capabilities'])chart(kind,group); + } + document.querySelectorAll('[data-family]').forEach(b=>b.onclick=()=>{family=b.dataset.family;applyFamily();table.querySelectorAll('td[data-axis]:not([hidden])').forEach(cell=>{if(cell.dataset.axis!=='Overall')motion.fade(cell,[{opacity:0},{opacity:1}],200);});}); + document.querySelectorAll('[data-agent-select]').forEach(s=>s.onchange=()=>choose(s.value)); + async function compareChoice() { const turn=++comparisonGeneration;projection=null;if(versus.startsWith('version:')) {const [benchmark,version]=JSON.parse(versus.slice(8));const response=await nulliusFetch('/api/leaderboard/comparison?'+new URLSearchParams({benchmark,version,all_scores:data.all_scores?'1':'0'}));if(response.ok){const result=await response.json();if(turn!==comparisonGeneration)return;projection=result;}}draw();} + document.querySelectorAll('[data-vs-select]').forEach(s=>{data.versions.forEach(v=>s.append(element('option',`Same agent: ${v.label}`,{value:'version:'+JSON.stringify([v.benchmark,v.version])})));s.onchange=()=>{versus=s.value;document.querySelectorAll('[data-vs-select]').forEach(v=>v.value=versus);compareChoice().catch(()=>{});};}); + document.getElementById('lb-metric').onchange=e=>{metric=e.target.value;drawScatter();}; + async function deferred(turn) { const response=await nulliusFetch(`/api/leaderboard/metrics?all_scores=${data.all_scores?1:0}&context=${encodeURIComponent(data.context)}`);if(!response.ok)return;const result=await response.json();if(turn!==generation||result.context!==data.context)return;result.rows.forEach(r=>{const existing=row(r.key);if(existing)existing.metrics=r.metrics;});updateTable(); } + document.getElementById('lb-mode').onchange=async e=>{const turn=++generation;const response=await nulliusFetch(`/api/leaderboard?all_scores=${e.target.value}`);if(!response.ok)return;const next=await response.json();if(turn!==generation)return;data=next;updateTable();compareChoice().catch(()=>{});draw();deferred(turn).catch(()=>{});}; + updateTable();choose(selected);tableMotion=motion.table(table);deferred(generation).catch(()=>{}); +})(); diff --git a/app/static/leaderboard/leaderboard.css b/app/static/leaderboard/leaderboard.css new file mode 100644 index 00000000..383f69b4 --- /dev/null +++ b/app/static/leaderboard/leaderboard.css @@ -0,0 +1,63 @@ +.lb-head-link { min-width: 10rem; justify-content: center; } +.lb-controls, .lb-mode { display: flex; gap: 1rem; align-items: center; justify-content: space-between; flex-wrap: wrap; } +.lb-mode { margin-left: auto; } +.lb-mark { display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; flex-shrink: 0; } +.lb-mark img, .lb-mark svg { width: 100%; height: 100%; object-fit: contain; } +.lb-agent { display: flex; align-items: center; gap: .5rem; text-align: left; } +.lb-subtitle { display: block; } +.lb-table { table-layout: fixed; width: 100%; } +.lb-table [data-col="rank"] { width: 40px; } +.lb-table [data-col="agent"] { width: 170px; } +.lb-table [data-col="overall"] { width: 75px; } +.lb-table [data-col="steps"], .lb-table [data-col="time"], .lb-table [data-col="calls"], .lb-table [data-col="cost"] { width: 65px; } +.lb-table th, .lb-table td { overflow-wrap: anywhere; white-space: normal; transition: opacity .2s, background-color .32s; } +.lb-table [data-axis] { cursor: help; background: color-mix(in srgb, var(--series-1) var(--lb-shade, 0%), var(--bg)); color: var(--text); } +.lb-unverified { outline: 1px dashed var(--text-dim); outline-offset: -2px; } +.lb-bar { display: block; height: 3px; width: var(--lb-value); background: var(--accent); transition: width .32s cubic-bezier(.2,.7,.2,1); } +.lb-efficiency { display: grid; grid-template-columns: minmax(0, 2fr) minmax(220px, 1fr); gap: 2rem; margin: 2rem 0; } +.lb-chart-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 2rem; margin: 1rem 0 2rem; } +.lb-chart-pair > :last-child { border-left: 1px solid var(--border); padding-left: 2rem; } +.lb-chart-pair svg, #lb-scatter { width: 100%; display: block; overflow: visible; } +.lb-chart-pair svg { min-height: 260px; } +.lb-chart-pair text, #lb-scatter text { fill: var(--text); } +.lb-chart-pair .grid, #lb-scatter .grid { stroke: var(--border-soft); fill: none; } +.lb-point { fill: var(--accent); stroke: var(--bg); cursor: pointer; transform-box: fill-box; transform-origin: center; transition: transform 150ms; } +.lb-point:hover, .lb-point:focus, .lb-point.lb-hover { transform: scale(1.35); } +.lb-selected { stroke: var(--accent-strong); stroke-width: 3; } +.lb-comparison { stroke: var(--series-2); fill: var(--series-2); } +.lb-radar-line { fill: none; stroke: var(--accent); stroke-width: 2; } +.lb-radar-line.lb-comparison { stroke: var(--series-2); stroke-dasharray: 5 4; } +.lb-series-solid, .lb-series-dashed { width: 24px; border-top: 2px solid var(--accent); } +.lb-series-dashed { border-top-style: dashed; border-color: var(--series-2); } +.lb-evidence { position: fixed; z-index: 100; max-width: min(600px, calc(100vw - 24px)); max-height: min(440px, calc(100vh - 24px)); overflow: auto; padding: 1rem; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); color: var(--text); box-shadow: 0 4px 16px color-mix(in srgb, var(--text) 15%, transparent); } +.lb-evidence p { margin: .5rem 0; } +.lb-medal { position: relative; display: inline-block; width: 28px; height: 32px; color: var(--lb-medal-gold); } +.lb-medal svg { width: 100%; height: 100%; stroke: currentColor; fill: color-mix(in srgb, currentColor 20%, var(--bg)); } +.lb-medal span { position: absolute; inset: 12px 0 0; text-align: center; color: var(--text); } +.lb-medal-2 { color: var(--lb-medal-silver); }.lb-medal-3 { color: var(--lb-medal-bronze); }.lb-medal-4 { color: var(--lb-medal-chocolate); } +.lb-medal:hover { animation: lb-swing .55s ease-in-out; transform-origin: top; } +@keyframes lb-swing { 25% { transform: rotate(-14deg); } 75% { transform: rotate(12deg); } } +:root { --lb-medal-gold: #e8c85a; --lb-medal-silver: #c0c5cf; --lb-medal-bronze: #dca475; --lb-medal-chocolate: #b88568; } +:root[data-theme="light"] { --lb-medal-gold: #906500; --lb-medal-silver: #687282; --lb-medal-bronze: #975525; --lb-medal-chocolate: #633f2d; } +#scoring-form fieldset { border: 0; padding: 0; min-width: 0; } +#scoring-form section { margin: 1.5rem 0; } +.scoring-entry { display: grid; grid-template-columns: 2fr 2fr 1fr 1fr 1fr auto; gap: .5rem; margin: .7rem 0; align-items: end; } +.scoring-entry label { display: grid; gap: .3rem; min-width: 0; } +.scoring-entry select, .scoring-entry input { width: 100%; min-width: 0; } +.scoring-custom-scores { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: .6rem; } +[aria-invalid="true"] { outline: 2px solid var(--bad); } +@media (max-width: 700px) { + .lb-chart-pair, .lb-efficiency { grid-template-columns: minmax(0,1fr); } + .lb-chart-pair > :last-child { border-left: 0; border-top: 1px solid var(--border); padding: 1.5rem 0 0; } + .lb-company { display: none; } + .lb-table { min-width: 900px; } + .lb-table [data-col="agent"] { position: static; } + .scoring-entry { grid-template-columns: minmax(0,1fr); } + .scoring-no-choice { display: none; } + .lb-complete-count { display: none; } +} +@media (prefers-reduced-motion: reduce) { + .lb-medal, .lb-point, .lb-bar, .lb-table th, .lb-table td { animation: none !important; transition: none !important; } +} + +#lb-scatter .lb-better { fill: var(--good); } diff --git a/app/static/leaderboard/motion.js b/app/static/leaderboard/motion.js new file mode 100644 index 00000000..ae08f9d6 --- /dev/null +++ b/app/static/leaderboard/motion.js @@ -0,0 +1,103 @@ +/* Persistent SVG nodes and cancellable geometry transitions for the composite view. */ +window.LeaderboardMotion = (() => { + const reduced = matchMedia('(prefers-reduced-motion: reduce)'); + const active = new Map(), timing = {duration:320, easing:'cubic-bezier(.2,.7,.2,1)'}; + const numeric = new Set(['x','y','cx','cy','x1','y1','x2','y2','r','data-cx','data-cy']); + function cancel(node, finish=false) { const old=active.get(node);if(old){old.cancel(finish);active.delete(node);} } + function fade(node, frames, duration=320, delay=0) { + cancel(node,true);if(reduced.matches)return; + const animation=node.animate(frames,{...timing,duration,delay}); + const controller={cancel:()=>animation.cancel()};active.set(node,controller); + animation.finished.then(()=>{if(active.get(node)===controller)active.delete(node);},()=>{}); + } + function geometry(node, from, to, delay=0) { + cancel(node);const keys=Object.keys(to).filter(k=>from[k]!=null && from[k]!==to[k]); + const set=values=>Object.entries(values).forEach(([k,v])=>node.setAttribute(k,v)); + if(!keys.length||reduced.matches){set(to);return;} + const pairs=keys.map(k=>[k,Number(from[k]),Number(to[k])]).filter(([,a,b])=>Number.isFinite(a)&&Number.isFinite(b)); + if(!pairs.length){set(to);return;} + set(from); + const animation=node.animate([{opacity:.7},{opacity:1}],{...timing,delay}); + let frame, start=null; + const controller={cancel:finish=>{cancelAnimationFrame(frame);animation.cancel();if(finish)set(to);}}; + active.set(node,controller); + const draw=now=>{ + start??=now;const t=Math.max(0,Math.min(1,(now-start-delay)/timing.duration)); + // Use the Web Animation's computed easing for the same curve as table motion. + const p=animation.effect.getComputedTiming().progress ?? t; + pairs.forEach(([k,a,b])=>node.setAttribute(k,a+(b-a)*p)); + if(t<1)frame=requestAnimationFrame(draw); + else {set(to);animation.cancel();if(active.get(node)===controller)active.delete(node);} + }; + frame=requestAnimationFrame(draw); + } + function key(node, index) { return node.nodeType===1 ? node.getAttribute('data-node') || `${node.tagName}:${index}` : `text:${index}`; } + function children(live, next) { + const old=new Map([...live.childNodes].map((n,i)=>[key(n,i),n])); + let cursor=live.firstChild; + [...next.childNodes].forEach((fresh,i)=>{ + const id=key(fresh,i);let node=old.get(id); + if(!node||node.nodeType!==fresh.nodeType||node.nodeName!==fresh.nodeName)node=fresh; + else { + old.delete(id); + if(node.nodeType===3)node.textContent=fresh.textContent; + else { + const from={},to={}; + for(const a of fresh.attributes)if(numeric.has(a.name)){from[a.name]=node.getAttribute(a.name);to[a.name]=a.value;} + cancel(node); + for(const a of [...node.attributes])if(!fresh.hasAttribute(a.name))node.removeAttribute(a.name); + for(const a of fresh.attributes)node.setAttribute(a.name,a.value); + children(node,fresh);geometry(node,from,to); + } + } + if(node!==cursor)live.insertBefore(node,cursor); + cursor=node.nextSibling; + }); + old.forEach(n=>{n.querySelectorAll?.('*').forEach(x=>cancel(x));cancel(n);n.remove();}); + } + function morph(live,next) { + const focus=document.activeElement,axis=focus?.dataset?.axis; + children(live,next); + if(focus!==document.activeElement){ + if(focus.isConnected)focus.focus({preventScroll:true}); + else if(axis)live.querySelector(`text[data-axis="${axis}"]`)?.focus({preventScroll:true}); + } + } + function reveal(plot,kind) { + if(reduced.matches)return; + const observer=new IntersectionObserver(entries=>{ + if(!entries.some(e=>e.isIntersecting))return;observer.disconnect(); + plot.querySelectorAll('[data-reveal]').forEach(node=>{ + if(kind==='strips')fade(node,[{transform:'translateX(-24px)',opacity:0},{transform:'translateX(0)',opacity:1}]); + else { + const from={},to={}; + for(const k of ['cx','cy','x1','y1','x2','y2'])if(node.hasAttribute(k)){to[k]=node.getAttribute(k);from[k]=k.startsWith('x')||k==='cx'?180:155;} + geometry(node,from,to,Number(node.dataset.reveal)*35); + } + }); + });observer.observe(plot); + } + function table(table) { + const measure=()=>new Map([...table.querySelectorAll('tr,th,td')].map(n=>[n,{rect:n.getBoundingClientRect(),text:n.textContent}])); + let previous=measure(),frame; + const capture=()=>{previous=measure();}; + const update=()=>{ + cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>{ + const next=measure(); + next.forEach(({rect,text},node)=>{ + const old=previous.get(node);if(!old||!rect.width||!rect.height)return; + const dx=old.rect.width?old.rect.x-rect.x:0,dy=node.tagName==='TR'?old.rect.y-rect.y:0; + if(Math.abs(dx)+Math.abs(dy)>.5)fade(node,[{transform:`translate(${dx}px,${dy}px)`},{transform:'translate(0,0)'}]); + else if(old.text!==text)fade(node,[{opacity:.25},{opacity:1}]); + });previous=next; + }); + }; + new MutationObserver(update).observe(table,{subtree:true,childList:true,attributes:true,attributeFilter:['hidden','style']}); + for(const event of ['click','input','change','keydown'])document.addEventListener(event,e=>{ + if(e.target.closest(`#${table.id}, #${table.id}-tools`))capture(); + },true); + return {capture}; + } + reduced.addEventListener('change',()=>{if(reduced.matches)[...active.keys()].forEach(n=>cancel(n,true));}); + return {morph,reveal,table,fade,reduced}; +})(); diff --git a/app/static/leaderboard/scoring.js b/app/static/leaderboard/scoring.js new file mode 100644 index 00000000..aa632207 --- /dev/null +++ b/app/static/leaderboard/scoring.js @@ -0,0 +1,81 @@ +/* Complete-document autosave: serialize writes and retain the latest local draft. */ +(() => { + const data=JSON.parse(document.getElementById('scoring-data').textContent), form=document.getElementById('scoring-form'); + let draft=data.settings, revision=data.revision, timer, writing=false, dirty=false, resetting=false; + const writable=form.dataset.writable==='true', status=form.querySelector('[data-changes]'), retry=form.querySelector('[data-settings-retry]'); + const el=(tag,text,attrs={})=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;Object.entries(attrs).forEach(([k,v])=>n.setAttribute(k,v));return n;}; + const input=(value,change,attrs={})=>{const n=el('input',null,{type:'number',min:0,step:'any',...attrs});n.value=value??'';n.oninput=()=>{change(n.value===''?null:Number(n.value));edited();};return n;}; + const select=(choices,value,change)=>{const n=el('select');choices.forEach(([v,label])=>{const o=el('option',label,{value:v});o.selected=v===value;n.append(o);});if(!choices.some(([v])=>v===value))n.append(el('option',value||'Unavailable',{value,selected:''}));n.onchange=()=>{change(n.value);render();edited();};return n;}; + const labelled=(text,control)=>{const l=el('label',text);l.append(control);return l;}; + const button=(text,action)=>{const b=el('button',text,{type:'button',class:'btn ghost sm'});b.onclick=action;return b;}; + const number=v=>Number.isFinite(v)&&v>=0; + function valid() { + let ok=true;const names=new Set(); + form.querySelectorAll('input').forEach(n=>n.setCustomValidity('')); + draft.custom.forEach(c=>{const normalized=c.name.trim().toLocaleLowerCase();const n=[...form.querySelectorAll('[data-custom-name]')].find(n=>n.dataset.customName===c.id);if(!normalized||names.has(normalized)){n?.setCustomValidity('Enter a unique name.');ok=false;}names.add(normalized);if(Object.values(c.scores).some(v=>v!=null&&(!number(v)||v>100)))ok=false;}); + if(!Object.values(draft.axes).some(a=>a.weight>0)) {form.querySelector('[data-overall]')?.setCustomValidity('At least one Weight in Overall must be positive.');ok=false;} + Object.values(draft.axes).forEach(a=>{if(!number(a.weight)||a.entries.some(e=>!number(e.weight)))ok=false;}); + form.querySelectorAll('input').forEach(n=>{n.setAttribute('aria-invalid',String(!n.checkValidity()));}); + return ok&&form.checkValidity(); + } + function shares() { + const normalized = values => { + const scale=Math.max(0,...values.filter(number)); + const total=scale?values.reduce((n,w)=>n+(number(w)?w/scale:0),0):0; + return values.map(w=>total&&number(w)?Number((w/scale/total*100).toFixed(1)):0); + }; + const overall=normalized(Object.values(draft.axes).map(a=>a.weight)); + Object.entries(draft.axes).forEach(([name,a],i)=>{ + form.querySelector(`[data-overall-share="${name}"]`).textContent=`share ${overall[i]}%`; + const shares=normalized(a.entries.map(e=>e.weight)); + form.querySelectorAll(`[data-scoring-axis="${name}"] [data-share]`).forEach((n,j)=>n.textContent=`share ${shares[j]}%`); + }); + } + function report(message,error=false) {status.textContent=message;status.closest('.st-savebar').hidden=!error;} + function edited() {resetting=false;dirty=true;shares();clearTimeout(timer);if(!valid())return;timer=setTimeout(save,300);} + async function save(reset=false) { + if(!writable||writing||(!reset&&(!dirty||!valid())))return; + writing=true;dirty=false;const body=reset?{reset:true}:structuredClone(draft); + if(reset){resetting=true;form.querySelector('fieldset').disabled=true;} + try { + const response=await nulliusFetch('/api/scoring',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':form.elements.csrf.value,'If-Match':revision},body:JSON.stringify(body)}); + const result=await response.json();if(!response.ok)throw new Error(result.error||'Scoring settings could not be saved. Retry.'); + revision=result.revision;if(reset){draft=result.settings;resetting=false;render();document.getElementById('reset-confirm').hidden=true;} + report('Scoring saved');window.nulliusNotify('Scoring saved',{key:'scoring'}); + } catch(error) {dirty=true;report(error.message,true);return;} + finally {writing=false;if(reset){form.querySelector('fieldset').disabled=!writable;}} + if(dirty&&valid())save(); + } + function render() { + const custom=document.getElementById('scoring-custom');custom.replaceChildren(); + draft.custom.forEach(c=>{ + const section=el('section'),name=el('input',null,{type:'text',required:'','data-custom-name':c.id});name.value=c.name;name.oninput=()=>{c.name=name.value;edited();}; + section.append(labelled('Name',name),button('Remove',()=>{draft.custom=draft.custom.filter(x=>x.id!==c.id);Object.values(draft.axes).forEach(a=>a.entries=a.entries.filter(e=>e.custom!==c.id));render();edited();})); + const scores=el('div',null,{class:'scoring-custom-scores'});data.rows.forEach(r=>scores.append(labelled([r.name,r.version_label,r.identity.model,r.identity.effort].filter(Boolean).join(' · '),input(c.scores[r.key],v=>c.scores[r.key]=v,{max:100,'aria-label':`${c.name}: ${r.name} ${r.version_label}`}))));section.append(scores);custom.append(section); + }); + document.querySelectorAll('[data-scoring-axis]').forEach(section=>{ + const axis=draft.axes[section.dataset.scoringAxis], container=section.querySelector('[data-entries]');container.replaceChildren(); + axis.entries.forEach((entry,index)=>{ + const line=el('div',null,{class:'scoring-entry'}), choices=[...new Map(data.options.map(o=>[o.key,o.label])).entries(),...draft.custom.map(c=>['custom:'+c.id,c.name])]; + const source=select(choices,entry.custom?'custom:'+entry.custom:entry.benchmark,value=>{if(value.startsWith('custom:'))axis.entries[index]={custom:value.slice(7),weight:entry.weight};else {const b=data.options.find(b=>b.key===value);axis.entries[index]={benchmark:value,dataset:'',version:b.version,metric:'Score',weight:entry.weight};}}); + line.append(labelled('Benchmark',source)); + if(entry.custom) for(const name of ['Dataset','Version','Metric'])line.append(el('span',`${name}: —`,{class:'scoring-no-choice'})); + else { + const versions=data.options.filter(o=>o.key===entry.benchmark), bench=versions.find(o=>o.version===entry.version); + line.append(labelled('Dataset',select([['','Whole benchmark'],...(bench?.datasets||[]).map(d=>[d.id,d.label])],entry.dataset,v=>entry.dataset=v))); + line.append(labelled('Version',select(versions.map(v=>[v.version,v.version_label||'—']),entry.version,v=>entry.version=v))); + line.append(labelled('Metric',select((bench?.metrics||['Score']).map(m=>[m,m]),entry.metric,v=>entry.metric=v))); + } + const weight=labelled('Weight',input(entry.weight,v=>entry.weight=v,{required:''}));weight.append(el('output','',{'data-share':''}));line.append(weight,button('Remove',()=>{axis.entries.splice(index,1);render();edited();}));container.append(line); + }); + const weight=section.querySelector('[data-overall]');weight.value=axis.weight;weight.oninput=()=>{axis.weight=weight.value===''?null:Number(weight.value);edited();}; + section.querySelector('[data-add-entry]').onclick=()=>{const b=data.options[0];if(!b)return;axis.entries.push({benchmark:b.key,dataset:'',version:b.version,metric:'Score',weight:1});render();edited();}; + });shares(); + } + document.getElementById('custom-add').onclick=()=>{draft.custom.push({id:crypto.randomUUID(),name:'',scores:{}});render();edited();}; + document.getElementById('reset-ask').onclick=()=>document.getElementById('reset-confirm').hidden=false; + document.getElementById('reset-no').onclick=()=>{resetting=false;document.getElementById('reset-confirm').hidden=true;}; + document.getElementById('reset-yes').onclick=()=>save(true); + retry.onclick=()=>save(resetting); + form.onsubmit=e=>e.preventDefault();render(); +})(); diff --git a/app/static/tables.js b/app/static/tables.js index c6a8411b..b7a75540 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -28,8 +28,10 @@ window.NulliusTable = { if (col === null) return; const type = heads[col].dataset.type || 'text'; [...body.rows].sort((a, b) => { + const group = Number(a.dataset.sortGroup || 0) - Number(b.dataset.sortGroup || 0); + if (group) return group; const x = key(a, type), y = key(b, type); - return (x < y ? -1 : x > y ? 1 : 0) * dir; + return (x < y ? -1 : x > y ? 1 : 0) * dir || (a.dataset.sortTie || "").localeCompare(b.dataset.sortTie || ""); }).forEach(r => body.appendChild(r)); after(); }; @@ -239,6 +241,7 @@ window.NulliusTable = { const ticks = table.querySelector('[data-check-all]') ? this.checks(table) : () => {}; let first = () => {}; const t = this.toolbar(table, tools, () => first()); + table.addEventListener("table:update", () => { t.resort(); first(); }); const pick = Boolean(table.querySelector('[data-pick]')); if (pick) this.picks(table, 'tr'); first = this.pager(table, table.id + '.per', pick ? r => t.passes(r) || this.chosen(r) : t.passes, ticks); diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg index 29618160..b8050de1 100644 --- a/app/templates/_icons.svg +++ b/app/templates/_icons.svg @@ -9,7 +9,10 @@ Runs Compare + Leaderboard + +## Task-name parts + +A benchmark can declare `task_parts` for scoring a subset across its datasets. +Each part has a unique `id`, a display `label`, and nonempty `prefixes` matching +the task names its driver records. Part IDs must differ from dataset IDs. +Versions may override the parts. OSWorld uses `os__` for OS tasks and the +`libreoffice_calc__`, `libreoffice_impress__`, and `libreoffice_writer__` prefixes +for office tasks. A part does not establish full task coverage without a task +manifest. diff --git a/docs/cli/README.md b/docs/cli/README.md index 533fd34c..34074658 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -10,7 +10,7 @@ From a source checkout, replace `nullius` with | Page | Command | | --- | --- | | [Launch](../getting-started.md) | `nullius serve [roots...]` | -| [Read jobs](read-jobs.md) | `nullius runs`, `nullius compare`, `nullius workspace`, `nullius standard traces` | +| [Read jobs](read-jobs.md) | `nullius runs`, `nullius compare`, `nullius leaderboard`, `nullius workspace`, `nullius standard traces` | | [Import a run](import.md) | `nullius import` | | [Task flags](flags.md) | `nullius flags list`, `set`, `accept`, `remove`, `copy`, `import`, `feasibility` | | [Definitions](definitions.md) | `nullius standard list`, `check`, `fit`, `pins`, `new` | diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 7caed9c2..64e955fa 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -11,6 +11,8 @@ Each page's command, or why there is none. | `/trial//` | `nullius runs show [--json]` | | A trial's Conversation, by call | `nullius runs show --calls` | | `/import`, `/use-path` | `nullius import -o [--json]`; `--list` | +| `/leaderboard` | `nullius leaderboard ... [--json] [--all-scores]` | +| `/scoring` | Profile `scoring.json` beside `settings.json`; `nullius paths` locates its configuration directory | | `/compare` | `nullius compare ... [--matched] [--json]` | | `/workspaces/open/` | `nullius serve ...`, `WORKSPACE=` | | `/workspaces` | `nullius workspace list [--home DIR] [--json]` | diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index c3e19dfd..87b9d707 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -68,3 +68,29 @@ nullius standard traces ./jobs ``` A trial that ended early kept no ACP events: its trace has the model calls, and its tool calls at their start, with no duration. + +## Leaderboard + +```bash +nullius leaderboard --help +nullius leaderboard --json +nullius leaderboard ./jobs --json +nullius leaderboard ./jobs --all-scores +``` + +Supply the result roots of one workspace. This reads completed jobs; it never +launches work. Without roots, catalogue rows have no recorded-run measurements. With +`--all-scores`, saved manual scores can still contribute and rank those rows. Exit 0 means +the document was read; an invalid root exits 3, invalid arguments 2. + +Verified only is the default. `--all-scores` includes saved manual scores. +The page and command use the same profile's [Scoring settings](../settings/README.md#scoring-settings). +JSON includes agent/company/version and execution identity, benchmark entry +versions, all capability and domain weights, effective shares, ranks and +not-ranked reasons, task evidence and selected run IDs. Scores are fractions; +text percentages use one decimal when needed. + +Time and cost include observed counts. The command also reads selected +trajectories for Steps and Tool calls; a missing or malformed trace leaves those +metrics unavailable. Invalid scoring settings use defaults with the same warning +as the page, without replacing the file. See the [scoring contract](../field-guide.md#leaderboard). diff --git a/docs/field-guide.md b/docs/field-guide.md index f1755b8d..1c56b115 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -287,3 +287,65 @@ Thirteen classes. The five marked **yes** under Infrastructure leave the adjuste - [Compare and judge runs](judgement.md) + +## Leaderboard + +Leaderboard scores describe one workspace's completed runs of catalogue agents. +Controls, example agents, preparing/running jobs and standalone capability +results do not contribute. Agent versions and execution setups are separate +rows; sampling limits affect coverage rather than identity. + +For each dataset and benchmark version, select the compatible run with the most +distinct non-infrastructure tasks, then the latest finish, then its stable run +ID. A better score never wins selection. Repeated attempts stay with their task; +repeated runs are not pooled. Explicit merged runs replace their source shards. +A whole-benchmark entry unions selected datasets by canonical task identity; +an overlap uses the same run precedence and retains that task's attempts. +Unknown identities make aggregation or full coverage unavailable rather than +guessing aliases. A dataset entry reads only that dataset. 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. + +Each axis normalizes positive entry weights over available scores. Overall +normalizes positive axis weights over measured axes. Missing values are never +zero. Evidence gives effective shares, configured weights, benchmark versions, +task coverage and links to each selected run. An all-zero entry column is +unavailable. All-zero Overall weights are invalid. + +Rank requires Overall and complete known coverage of the required verified +entries across counted axes, including positive-weight domains. Unknown full +coverage prevents ranking. Removed entries and zero weights do not gate rank. +Manual sources cannot replace required verified evidence, and their absence +does not disqualify another row. Exact Overall ties share competition rank; +scored unranked rows follow ranked rows and retain their score bars. + +Verified only excludes custom scores everywhere. All scores includes them with +the configured weights; affected values identify unverified influence and name +the sources. Custom scores supply no tasks, runs or efficiency measurements. +They bind to stable agent/version/setup keys and never transfer to a new setup. + +Average uses available row scores and reports the count. A row comparison uses +shared measured capabilities for best and weakest differences in percentage +points. Benchmark-version comparisons are temporary: settings and ranks do not +change. Missing evidence for a replacement version leaves affected axes and +Overall differences absent, rather than renormalizing a partial comparison. +Radar segments connect only adjacent measured axes, including wraparound. + +Efficiency averages distinct selected real trials, deduplicated across mappings, +with infrastructure excluded. Time uses observed agent durations; cost uses +observed costs, each with its own count. Steps and Tool calls load later from +trajectories on the page; the command completes that read synchronously. Missing +or malformed traces are unavailable, not zero. Changed trace content invalidates +its cached metrics without reparsing unchanged traces. diff --git a/docs/settings/README.md b/docs/settings/README.md index bbe948b3..2940d83b 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -13,6 +13,7 @@ Existing results open without credentials. | [Hosts](run-hosts.md) | SSH machines | | [Data providers](data-providers.md) | Hugging Face and Docker Hub connections | | [Sandbox](sandbox.md) | Docker on this machine, the Boat key | +| [Scoring settings](#scoring-settings) | Leaderboard mappings, weights and custom scores | | [General](other.md) | Tour and checklist | ## Variables @@ -73,6 +74,7 @@ credential values. Linux defaults: | Stores | Default | | --- | --- | +| Composite scoring | `~/.config/nullius/scoring.json` | | Saved settings | `~/.config/nullius/settings.json` | | Benchmark credentials | `~/.config/nullius/secrets//` | | Hugging Face token | `~/.config/nullius/secrets/data-provider-huggingface/` | @@ -130,3 +132,41 @@ Set `NULLIUS_HOME` before both commands to migrate into a separate profile. Start-up options. + +## Scoring settings + +Open **Scoring settings** from the Leaderboard head; **Leaderboard** returns to +its table and charts. The dedicated page orders Custom benchmarks, Capabilities, +then Domains. Read-only clients can inspect it; only local clients can write. + +Each entry chooses a benchmark, dataset or declared task-name part, pinned version, supported metric and +independent weight in that axis. Score is always offered; pass^3 is offered for +pass/fail benchmarks. Zero weight disables an entry without removing it. +Weight in Overall controls each axis separately, including domains. +Configured shares update while editing; the Leaderboard evidence shows effective +shares among the sources actually measured for that row. + +Valid complete documents autosave, followed by **Scoring saved**. There is no +Save button. Invalid inputs stay in the draft and do not change active scoring. +A failed write keeps the draft and shows Retry. A conflicting edit from another +page requires reloading before editing again. + +Manual benchmarks have a unique trimmed name and optional scores from 0 to 100 +per agent/version/setup. Blank means absent; zero is measured. Rename preserves +scores; removing a custom benchmark removes its scores and mappings together. +Verified only ignores these scores; All scores includes them and identifies +their unverified influence. + +Scoring is profile-wide in `scoring.json`, beside `settings.json` in the directory +shown by `nullius paths`. Writes replace the complete validated document +atomically. Malformed content uses defaults with a warning and is left intact. +Removed catalogue references remain unavailable and can be removed without +blocking unrelated edits. New mappings must name a declared dataset/part and +version. Legacy entries with an empty version remain unavailable until a pinned +version is selected; runs also need that recorded identity. Negative or nonfinite weights, duplicate identical +entries, duplicate custom names, invalid scores and all-zero Overall weights +are refused. + +**Reset to defaults** asks in place before resetting mappings and weights and +removing all custom benchmarks and scores. Cancel and failed writes preserve the +previous document. diff --git a/pyproject.toml b/pyproject.toml index 3c378979..e56d61a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,7 @@ managed = false include-package-data = false packages = [ "nullius", "nullius.catalogue", "nullius.compare", "nullius.harbor", - "nullius.importers", "nullius.judge", "nullius.recipes", "nullius.runs", + "nullius.importers", "nullius.judge", "nullius.leaderboard", "nullius.recipes", "nullius.runs", "nullius.standard", "nullius.standard.backends", "nullius.standard.calls", "nullius.standard.contract", "nullius.standard.pages", "nullius.standard.proofs", "nullius.standard.protocols", "nullius.standard.requirements", "nullius.standard.runner", @@ -56,4 +56,4 @@ dependencies = {file = ["app/requirements.txt"]} "nullius.catalogue" = ["agents/*/*.json", "agents/*/*.py", "agents/*/*.toml", "agents/*/*.yaml", "agents/*/*.txt", "benchmarks/*/env/*", "benchmarks/*/*.json", "benchmarks/*/*.py", "benchmarks/*/*.yml", "benchmarks/*/startup/*.py", "capabilities/*/*.json", "capabilities/*/*.py"] "nullius.standard" = ["kits/*/*.json", "kits/*/*.py", "kits/*/*.Dockerfile", "kits/*/*.txt"] "nullius.judge" = ["floors.json"] -_nullius_app = ["templates/**/*.html", "templates/*.svg", "static/**/*.css", "static/**/*.js", "static/**/*.svg", "static/**/*.png", "static/**/*.json", "static/**/*.woff2", "static/**/*.ttf", "static/**/*.txt", "static/**/*.md", "requirements.txt", ".env.example"] +_nullius_app = ["templates/**/*.html", "templates/*.svg", "static/**/*.css", "static/**/*.js", "static/**/*.svg", "static/**/*.png", "static/**/*.ico", "static/**/*.json", "static/**/*.woff2", "static/**/*.ttf", "static/**/*.txt", "static/**/*.md", "requirements.txt", ".env.example"]