Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/yugos-evals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,20 @@ generation field other than `temperature`, `seed`, `max_tokens`, or
Sandboxed tasks use Inspect's local Docker provider and the pack's pinned
images. Docker has to be installed.

### Coding harnesses

A frozen sandboxed question can be presented to a real coding harness in place
of its task's own agent. `yugos_evals.harnessed.harness_question(question,
harness=..., version=...)` returns a copy whose solver is Claude Code
(`claude_code`), Codex CLI (`codex_cli`) or OpenCode (`opencode`) at one exact
release; samples, sandbox and scorer are unchanged. The harness runs inside the
task's sandbox and its model requests come back to the router, so the sandbox
needs no network and every turn is routed and metered as usual. The copy is a
separate source, `<source>@<harness>`, without difficulty labels.

Install the `harness` extra to use it. The harness release is fetched once on
the host and copied into the sandbox.

**`compare RUN_A RUN_B`** requires both runs to cover the same questions and
to be complete. It prints category net value and the overall lower bound, and
reports when B beats A under the default policy (`--policy FILE` overrides
Expand Down
13 changes: 12 additions & 1 deletion packages/yugos-evals/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,17 @@ dependencies = [
]

[project.optional-dependencies]
dev = ["pytest>=8", "pytest-asyncio>=0.24", "matplotlib>=3.8", "shapely==2.1.2", "ruff>=0.12"]
# Real coding harnesses as solvers for sandboxed tasks (`yugos_evals.harnessed`).
# Inspect's agent bridge needs both SDKs to read the harnesses' provider requests.
harness = ["inspect-swe==0.2.72", "openai>=3,<4", "anthropic>=1,<2"]
dev = [
"yugos-evals[harness]",
"pytest>=8",
"pytest-asyncio>=0.24",
"matplotlib>=3.8",
"shapely==2.1.2",
"ruff>=0.12",
]

[dependency-groups]
dev = ["yugos-evals[dev]"]
Expand All @@ -35,6 +45,7 @@ yugos_evals = "yugos_evals._registry"
# Installed native task construction from prepared data.
[project.entry-points."yugos.inspect_tasks"]
"yugos_evals.prepared" = "yugos_evals.prepared:build"
"yugos_evals.harnessed" = "yugos_evals.harnessed:build"

[tool.setuptools.packages.find]
where = ["src"]
Expand Down
98 changes: 98 additions & 0 deletions packages/yugos-evals/src/yugos_evals/harnessed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Prepared sandboxed tasks solved by a real coding harness instead of the task's own agent.

The harness (Claude Code, Codex CLI or OpenCode, from `inspect-swe`) runs inside the
task's sandbox. Its model requests return to Inspect's model on the host, so they are
routed, metered and logged like any other turn and the sandbox needs no network. The
task's samples, setup, sandbox and scorer are unchanged; only the solver is replaced.
"""

from __future__ import annotations

import re
from importlib.metadata import version as installed_version

from inspect_ai import Task, task_with
from inspect_ai.model import GenerateInput

from yugos.inspect_engine.frozen import _task_builder

BUILDER = "yugos_evals.harnessed"
HARNESSES = ("claude_code", "codex_cli", "opencode")
_RELEASE = re.compile(r"\d+(\.\d+)+")


def _check(harness: str, version: str) -> None:
if harness not in HARNESSES:
raise ValueError(f"unknown harness: {harness}")
if not isinstance(version, str) or not _RELEASE.fullmatch(version):
raise ValueError("a harness is pinned to one exact release")


async def portable_request(model, messages, tools, tool_choice, config):
"""Drop the provider-private headers and body fields a harness adds to its requests.

They carry session and cache hints for the harness's own provider; the routed
model may be any provider, and the router protocol refuses them.
"""
if config.extra_body is None and config.extra_headers is None:
return None
portable = config.model_copy(update={"extra_body": None, "extra_headers": None})
return GenerateInput(messages, tools, tool_choice, portable)


def harness_agent(harness: str, version: str):
"""The named harness at one release, with its model requests made portable."""
_check(harness, version)
import inspect_swe

return getattr(inspect_swe, harness)(version=version, filter=portable_request)


def build(*, options: dict, harness: str, version: str, builder: str, builder_args: dict) -> Task:
"""Build the task `builder` constructs, then replace its solver with the harness."""
if builder == BUILDER:
raise ValueError("a harnessed task wraps a native task builder")
native = _task_builder(builder).load()(options=options, **builder_args)
if native.sandbox is None and any(sample.sandbox is None for sample in native.dataset):
raise ValueError("a harness runs in the task's sandbox; this task has none")
return task_with(native, solver=harness_agent(harness, version))


def harness_question(question, *, harness: str, version: str):
"""A frozen sandboxed question re-presented to a harness, without reloading it.

The copy is a separate source (`<source>@<harness>`) with no difficulty labels:
panel evidence for the task's own agent does not describe a harness.
"""
_check(harness, version)
config = question.inspect_task
if config["builder"] == BUILDER:
raise ValueError("question is already presented to a harness")
if config.get("sandbox") is None and question.inspect_sample.get("sandbox") is None:
raise ValueError("a harness runs in the task's sandbox; this question has none")
source, _, identity = question.question_id.partition(":")
packages = {
**config["packages"],
"yugos-evals": installed_version("yugos-evals"),
"inspect-swe": installed_version("inspect-swe"),
}
builder_args = {
"harness": harness,
"version": version,
"builder": config["builder"],
"builder_args": config["builder_args"],
}
return question.model_copy(
update={
"question_id": f"{source}@{harness}:{identity}",
"source_benchmark": f"{question.source_benchmark or source}@{harness}",
"difficulty_decile": None,
"panel_solve_share": None,
"inspect_task": {
**config,
"builder": BUILDER,
"builder_args": builder_args,
"packages": packages,
},
}
)
105 changes: 105 additions & 0 deletions packages/yugos-evals/tests/test_harnessed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""A frozen sandboxed question can be re-presented to a pinned coding harness."""

import asyncio
import importlib
from importlib.metadata import version

import pytest
from inspect_ai.dataset import MemoryDataset, Sample
from inspect_ai.model import ChatMessageUser, GenerateConfig

from yugos.evaluation import Question
from yugos.inference.chat import ModelInput
from yugos.inspect_engine import restore_tasks
from yugos_evals.catalog import entry, freeze_entry, load_task
from yugos_evals.harnessed import harness_question, portable_request


@pytest.fixture
def sandboxed(monkeypatch) -> Question:
module = importlib.import_module("inspect_evals.humaneval.humaneval")
monkeypatch.setattr(
module,
"hf_dataset",
lambda **kwargs: MemoryDataset(
[Sample(id="HumanEval/0", input="def f():\n", target="pass\n")]
),
)
benchmark = entry("humaneval")
[question] = freeze_entry(benchmark, task=load_task(benchmark))
return question


def test_harnessed_question_keeps_the_native_samples_sandbox_and_scorer(sandboxed):
harnessed = harness_question(sandboxed, harness="claude_code", version="2.1.311")
[(native, _)] = restore_tasks([sandboxed])
[(task, definition)] = restore_tasks([harnessed])

assert harnessed.question_id == "humaneval@claude_code:HumanEval/0"
assert harnessed.source_benchmark == "humaneval@claude_code"
assert (harnessed.prompt, harnessed.expected_answer) == (
sandboxed.prompt,
sandboxed.expected_answer,
)
assert definition.packages["inspect-swe"] == version("inspect-swe")
assert definition.sandbox == sandboxed.inspect_task["sandbox"]
assert definition.scorer == sandboxed.inspect_task["scorer"]
assert task.dataset[0].input == native.dataset[0].input
assert task.solver is not native.solver
# The harness and its release are part of the recipe, so they change the identity.
other = harness_question(sandboxed, harness="claude_code", version="2.1.312")
assert other.inspect_task != harnessed.inspect_task


def test_harnessed_question_drops_evidence_measured_with_the_native_agent(sandboxed):
labelled = sandboxed.model_copy(update={"difficulty_decile": 3, "panel_solve_share": "0.5"})
harnessed = harness_question(labelled, harness="codex_cli", version="0.80.0")
assert harnessed.difficulty_decile is None and harnessed.panel_solve_share is None


@pytest.mark.parametrize(
("harness", "release", "message"),
[
("aider", "1.0.0", "unknown harness"),
("claude_code", "latest", "exact release"),
("claude_code", "stable", "exact release"),
("codex_cli", "sandbox", "exact release"),
],
)
def test_only_known_harnesses_at_exact_releases_are_recorded(sandboxed, harness, release, message):
with pytest.raises(ValueError, match=message):
harness_question(sandboxed, harness=harness, version=release)
forged = harness_question(sandboxed, harness="opencode", version="1.0.0")
forged.inspect_task["builder_args"].update(harness=harness, version=release)
with pytest.raises(ValueError, match=message):
restore_tasks([forged])


def test_a_harness_needs_a_sandbox_and_is_applied_once(sandboxed):
harnessed = harness_question(sandboxed, harness="opencode", version="1.0.0")
with pytest.raises(ValueError, match="already presented"):
harness_question(harnessed, harness="opencode", version="1.0.0")
bare = Question.model_validate_json(sandboxed.model_dump_json())
bare.inspect_task["sandbox"] = None
bare.inspect_sample["sandbox"] = None
with pytest.raises(ValueError, match="has none"):
harness_question(bare, harness="opencode", version="1.0.0")


def test_harness_requests_become_acceptable_to_the_router_protocol():
messages = [ChatMessageUser(content="fix the bug")]
# What Claude Code and Codex attach to their requests.
config = GenerateConfig(
parallel_tool_calls=True,
extra_body={"metadata": {"user_id": "device"}, "prompt_cache_key": "k", "store": False},
extra_headers={"x-session": "s"},
)
with pytest.raises(ValueError, match="provider headers or body"):
ModelInput.from_inspect(messages, [], "auto", config)

filtered = asyncio.run(portable_request(None, messages, [], "auto", config))
request = ModelInput.from_inspect(*filtered)
assert request.config.parallel_tool_calls is True
assert request.config.extra_body is None and request.config.extra_headers is None
plain = GenerateConfig(temperature=0)
assert asyncio.run(portable_request(None, messages, [], "auto", plain)) is None
Loading