Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
File size: 22,537 Bytes
fe4e0a1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | """Coding environment (HUD v6): a repo workspace with diff-based grading.
The env publishes one ``ssh`` workspace over a git repo; the agent's harness
brings its own bash/file tools. Task setup vaults the repo's real history
(:mod:`coding.repo`) so the agent gets a fresh single-commit repo with working
git but no answer-key refs; grading captures the agent's changes as a diff,
resets to the pre-agent snapshot, re-applies, and runs the hidden board.
Three task templates:
- ``coding-task`` — hidden tests live as refs in the repo's vaulted history
(the ``{task}_baseline`` / ``{task}_test`` / ``{task}_golden`` branch
convention) and a shell command scores by exit code. Runs locally (clones
``REPO_URL`` per process) or from an image that bakes the repo.
- ``sdlc-task`` — adds workflow: a bare mock-GitHub remote the agent pushes
to, ``github_*`` issue/PR tools (:mod:`coding.github`), and grading over
the pushed pull-request branch instead of the worktree.
- one SWE-bench Pro instance template, registered only when an instance dir
is baked in (see ``swe_tasks.py``): grading replays the official evaluator
(:mod:`coding.swe_bench_pro`).
Images set ``REPO_DIR``; locally everything lives in per-process temp dirs.
The image substrate here is sfackler/rust-postgres (a Rust cargo workspace of
nine crates whose lock file carries a few hundred dependencies), so the
agent's cargo environment is declared explicitly on the workspace — see
``AGENT_CARGO_ENV`` — and a PostgreSQL server, which this repository's own
suite needs, is started when the environment comes up. The vault, the hidden
grader, the held-out board crate, the grader's own build trees, the pristine
base checkout and gold.diff sit outside the workspace — under ``/hud`` (root,
mode 700) in images — and agent shells drop to a non-root uid, so only the env
process can read them.
The task this env carries is ``shared_handle_abandoned_operations``,
registered in ``tasks.py``; the three generic templates below come with the
coding-template and are unused here.
"""
from __future__ import annotations
import asyncio
import logging
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Any
from hud.environment import Environment, Workspace
from hud.graders import BashGrader, EvaluationResult, LLMJudgeGrader, SubScore, combine
from hud.settings import settings
from coding import repo as repo_lib
from coding import swe_bench_pro as swe
from coding.github import MockGitHub
from coding.github import serve as serve_github
logger = logging.getLogger(__name__)
# ─── substrate layout ────────────────────────────────────────────────────
# Images set REPO_DIR (and ship the repo); locally everything lives in
# per-process temp dirs and the repo is cloned from REPO_URL at startup.
_explicit_repo = os.environ.get("REPO_DIR")
if _explicit_repo:
REPO_DIR = Path(_explicit_repo)
VAULT_DIR = Path(os.environ.get("VAULT_DIR", "/hud/vault"))
LOGS_DIR = Path(os.environ.get("GRADING_LOGS_DIR", "/hud/logs"))
_LOCAL_SUBSTRATE = False
else:
_LOCAL_ROOT = Path(tempfile.gettempdir()) / "hud-coding"
REPO_DIR = _LOCAL_ROOT / f"repo-{os.getpid()}"
VAULT_DIR = _LOCAL_ROOT / f"vault-{os.getpid()}"
LOGS_DIR = _LOCAL_ROOT / f"logs-{os.getpid()}"
_LOCAL_SUBSTRATE = True
# The SDLC flavor's mock-GitHub remote: a bare repo the agent pushes to. It
# must be writable by the agent, so it lives outside /hud.
REMOTE_DIR = (
Path(os.environ.get("REMOTE_DIR", "/srv/git/project.git"))
if _explicit_repo
else _LOCAL_ROOT / f"remote-{os.getpid()}" / "project.git"
)
REPO_URL = os.environ.get("REPO_URL", "https://github.com/sfackler/rust-postgres")
TESTS_TIMEOUT = float(os.environ.get("GRADING_TIMEOUT", "3600"))
INSTANCE_DIR = Path(os.environ.get("INSTANCE_DIR", "/hud/instance"))
AGENT_UID = 1000
AGENT_HOME = Path("/tmp/agent-home") # noqa: S108 - container-local, created at setup
# S-3: the registry a deploy overwrites is chosen by THIS name, not by the
# directory the package sits in. A clone that keeps its parent's name
# republishes the parent's environment with this image.
env = Environment(name="ec-swe-rust-postgres-abandoned-ops")
# The agent's cargo environment, and why it is spelled out here rather than
# left to the image's ENV.
#
# When shell_uid drops privileges, hud does NOT hand the session the serving
# process's environment: Workspace._session_env() builds a minimal one from
# scratch (PATH, HOME, TERM) and layers this dict on top, precisely so a
# secret the env process holds cannot leak into the agent's shell. So every
# `ENV CARGO_*` line in the Dockerfile reaches the grader and never the agent.
#
# That is harmless for a repo with no dependencies. This workspace's lock file
# carries a few hundred crates and the rollout has nothing to fetch them from:
# with CARGO_HOME left at its default the agent's registry would be
# $HOME/.cargo — empty — and `cargo build` would fail on the first dependency.
# The task would be impossible for reasons that have nothing to do with the
# ticket.
#
# CARGO_HOME points at the registry the image pre-populated. It is root-owned
# and read-only to uid 1000 on purpose: the grader compiles the held-out board
# against the agent's tree offline, and a registry the agent could rewrite
# would be a way to change what that board compiles against. (The one file
# cargo must open read-write on every invocation, $CARGO_HOME/.package-cache,
# is made world-writable in the image; it holds no content.) CARGO_TARGET_DIR
# is the one place the agent must be able to write, so it is a directory of
# its own, owned by the agent and outside both the repository (whose diff is
# what is graded) and $HOME.
AGENT_CARGO_ENV = {
"CARGO_HOME": os.environ.get("AGENT_CARGO_HOME", "/cargo"),
"RUSTUP_HOME": os.environ.get("AGENT_RUSTUP_HOME", "/usr/local/rustup"),
"CARGO_TARGET_DIR": os.environ.get("AGENT_TARGET_DIR", "/agent-target"),
"CARGO_NET_OFFLINE": "true",
# ── memory and cores, not difficulty ──────────────────────────────────
# MEASURED 2026-09-08 on an earlier package: three of five rollouts in a
# 300-step final died with metadata.container_oom_killed=True, i.e. the
# harness lost the run before the grader ever saw a tree. A cargo build of
# this workspace's test targets is not a small one, so the ceiling stays.
# The container's memory limit cannot be raised from this package
# (hud/eval/runtime/hud.py::_runtime_session -- declared `limits` on an
# already-deployed env raise ValueError, and cpu/memory in runtime_config
# are softly ignored with a warning; memory_mb exists only for the
# docker/compose/modal/daytona providers, i.e. locally). So the only honest
# lever is to make the AGENT's toolchain fit the box it is in: two build
# jobs instead of one per core. This is the agent session only -- the
# grader builds with its own environment, so no oracle changes.
"CARGO_BUILD_JOBS": "2",
}
# PATH is deliberately NOT in that dict. An agent session is a LOGIN shell
# (`env -i ... bash -l`), and Debian's /etc/profile assigns PATH
# unconditionally, so anything set here would be thrown away before the first
# command runs -- measured, not assumed. The toolchain therefore goes on PATH
# from inside the image, in /etc/profile.d/10-rust-toolchain.sh, where a login
# shell cannot lose it. That file also repeats the variables above as defaults,
# so the two mechanisms cover each other.
# network=False — hud's own default (Workspace.__init__, workspace.py:321). We had
# True only because the CLI scaffold ships it (hud/cli/templates.py:35).
# ⚠️ MEASURED 2026-09-03: this flag is a NO-OP in our images. `unshare --net` is
# applied only through bwrap (workspace.py:1049, :1292 fall back to a bare shell
# when self._bwrap is None), and bwrap is absent from every image; installing it
# does not help either — usable_bwrap() still returns None because the eval
# substrate denies the privileges (unshare: Operation not permitted).
# Verified inside an image: `git ls-remote https://github.com/... HEAD` → RC 0.
# The agent shell REACHES THE INTERNET regardless of this flag. Kept False so the
# intent is right if the substrate ever grants isolation — but never rely on it,
# and never claim "offline" in a ticket.
_ws = Workspace(
REPO_DIR,
guest_path=str(REPO_DIR),
network=False,
env={"HOME": str(AGENT_HOME), **({} if _LOCAL_SUBSTRATE else AGENT_CARGO_ENV)},
track_files=settings.file_tracking_enabled,
shell_uid=AGENT_UID,
)
SDLC_TOOLS = os.environ.get("SDLC_TOOLS", "") not in ("", "0", "false")
# ─── the database this repository's own suite needs ──────────────────────
# It is a client library for PostgreSQL: `cargo test` in this workspace talks
# to a server, and the repository says which one and where (docker-compose.yml
# in the tree). One is started here, on the loopback interface, with the roles
# and extensions that tree's own setup script creates, so that the agent can
# run the suite it is told not to break. The grader starts it again itself
# (idempotently) so a grading never depends on this having worked.
PG_START = Path("/usr/local/bin/hud-pg.sh")
def _start_database() -> None:
if _LOCAL_SUBSTRATE or not PG_START.exists():
return
try:
done = subprocess.run(
["bash", str(PG_START), "start"], capture_output=True, text=True, timeout=180
)
logger.info("database start rc=%s %s", done.returncode, done.stdout.strip()[-500:])
except (OSError, subprocess.SubprocessError) as exc: # pragma: no cover - startup only
logger.warning("database did not start: %s", exc)
# Hedged on purpose ("can exhaust it", not "is killed"): the note may state the
# size of the box; it may not state a failure nobody measured. Everything here is
# a fact about the MACHINE — the size of it, the shape of a command that fits in
# it, the closed network, the services it does and does not run — and nothing
# here is a fact about the ticket: no symptom, no file name, no identifier, no
# sample (minimal-ticket law, ORG15). Nothing in this note is graded.
#
# The last sentence is law RH-2: a rollout that spends its turns trying to make
# a network-dependent step work, and reads its failure as its own, has been
# misled by the sandbox. Saying so costs nothing and points nowhere.
WORKSPACE_NOTE = (
f"Please make your changes directly in {REPO_DIR}, not in a copy or a "
"separate worktree.\n"
"Environment: this container has about 2 vCPUs and a hard memory limit, and "
"a fully parallel build can exhaust it; cargo is already configured to use "
"two jobs. Build and test crate by crate, e.g. "
"`cargo test -p tokio-postgres`. Compiled artefacts go to a target "
"directory of their own outside the repository, which is already warm, so "
"the first build is an incremental one.\n"
"Treat the sandbox as offline: cargo runs with CARGO_NET_OFFLINE=true "
"against a pre-populated registry, so `cargo build` and `cargo test` work "
"but no new dependency can be fetched. A PostgreSQL server is running "
"inside this container on 127.0.0.1 port 5433, set up the way this "
"repository's own docker-compose file sets one up; that is the only "
"service here, and nothing outside the container can be reached. A test "
"that fails for that reason is a property of the sandbox, not of your "
"change."
)
_github = MockGitHub()
_github_server: asyncio.Task[None] | None = None
@env.initialize
async def _up() -> None:
global _github_server
if _LOCAL_SUBSTRATE and not (REPO_DIR / ".git").exists():
REPO_DIR.parent.mkdir(parents=True, exist_ok=True)
logger.info("cloning %s into %s", REPO_URL, REPO_DIR)
await repo_lib.run("git", "clone", "-q", REPO_URL, str(REPO_DIR), cwd=REPO_DIR.parent)
_start_database()
await _ws.start()
env.add_capability(_ws.capability("shell"))
if _ws.tracks_files:
env.add_capability(_ws.file_tracking_capability())
# The mock-GitHub tools belong to the SDLC flavor, which seeds issues and
# wants a pull request. A plain coding task never uses them, and offering
# them anyway spends agent steps on an empty issue list - every rollout so
# far called github_list_issues and github_list_pull_requests once.
if SDLC_TOOLS:
_github_server, github_capability = serve_github(_github)
env.add_capability(github_capability)
@env.shutdown
async def _down() -> None:
if _github_server is not None:
_github_server.cancel()
await _ws.stop()
if _LOCAL_SUBSTRATE:
for path in (REPO_DIR, VAULT_DIR, LOGS_DIR, REMOTE_DIR.parent):
shutil.rmtree(path, ignore_errors=True)
# ─── shared task lifecycle ───────────────────────────────────────────────
async def _setup(base_ref: str | None = None, *, remote: bool = False) -> None:
"""Check out the task's baseline, vault the history, hand the repo to the agent.
With ``remote=True`` (the SDLC flavor) a bare "GitHub" remote is created
from the baseline first, and the agent's repo is attached to it as a
normal clone would be — realistic history, pushes, and branches, but no
reachable answer-key refs.
"""
if base_ref:
await repo_lib.git(REPO_DIR, "checkout", "-qf", base_ref)
if remote:
await repo_lib.create_remote(REPO_DIR, REMOTE_DIR, base_ref or "HEAD")
await repo_lib.vault_history(REPO_DIR, VAULT_DIR)
if remote:
await repo_lib.attach_to_remote(REPO_DIR, REMOTE_DIR)
if hasattr(os, "geteuid") and os.geteuid() == 0:
AGENT_HOME.mkdir(parents=True, exist_ok=True)
uid = f"{AGENT_UID}:{AGENT_UID}"
paths = [str(REPO_DIR), str(AGENT_HOME)] + ([str(REMOTE_DIR)] if remote else [])
await repo_lib.run("chown", "-R", uid, *paths, cwd=Path("/"))
if remote:
# The grader (root) pushes to and clones from the agent-owned remote.
await repo_lib.run("git", "config", "--global", "--add", "safe.directory", str(REMOTE_DIR), cwd=Path("/"))
# ─── generic flavor ──────────────────────────────────────────────────────
async def _grade_generic(
test_command: str,
base_ref: str | None,
test_ref: str | None,
test_files: list[str] | None,
golden_ref: str | None,
validate_mode: str | None,
) -> EvaluationResult:
setup_commit = await repo_lib.restore_history(REPO_DIR, VAULT_DIR)
if validate_mode == "golden":
if not (base_ref and golden_ref):
raise ValueError('validate_mode="golden" needs base_ref and golden_ref')
_, diff, _ = await repo_lib.git(REPO_DIR, "diff", base_ref, golden_ref)
else:
diff = await repo_lib.capture_agent_diff(REPO_DIR, setup_commit)
await repo_lib.reset_worktree(REPO_DIR, setup_commit)
apply_error = await repo_lib.apply_diff(REPO_DIR, diff, LOGS_DIR / "patch.diff")
if apply_error is not None:
return EvaluationResult(reward=0.0, content="patch failed to apply", info={"git_apply": apply_error})
if test_ref:
# Hidden tests come from the vaulted history, after the agent's diff —
# so agent edits to them never survive into grading.
await repo_lib.git(REPO_DIR, "checkout", test_ref, "--", *(test_files or ["."]))
command = test_command.format(test_files=" ".join(test_files or []))
return await combine(
BashGrader.grade(weight=1.0, command=command, cwd=str(REPO_DIR), timeout_seconds=int(TESTS_TIMEOUT))
)
@env.template(id="coding-task", description="Fix a bug in the repo; hidden tests grade the diff.")
async def coding_task(
description: str,
test_command: str,
base_ref: str | None = None,
test_ref: str | None = None,
test_files: list[str] | None = None,
golden_ref: str | None = None,
validate_mode: str | None = None,
):
"""Generic coding task.
``base_ref`` is the agent's starting state; ``test_ref`` holds the hidden
tests (``test_files`` are checked out from it at grade time);
``test_command`` scores by exit code, with ``{test_files}`` expanded.
``validate_mode="golden"`` grades ``base_ref..golden_ref`` instead of
agent edits.
"""
if validate_mode not in (None, "golden"):
raise ValueError(f"unknown validate_mode: {validate_mode!r}")
await _setup(base_ref)
_ = yield (
f"You are working in a coding repository located at {REPO_DIR}. {WORKSPACE_NOTE}\n\n"
"Use the tools provided to complete the following task. Hidden tests grade your "
f"work when you finish; do not modify existing tests.\n\n{description}"
)
yield await _grade_generic(test_command, base_ref, test_ref, test_files, golden_ref, validate_mode)
# ─── SDLC flavor: issue-driven fix, graded on the pushed PR branch ───────
async def _fetch_hidden_ref(dest: Path, ref: str) -> None:
"""Fetch an answer-key ref from the vaulted history into *dest*."""
full = f"refs/remotes/{ref}" if ref.startswith("origin/") else ref
await repo_lib.git(dest, "fetch", "-q", str(VAULT_DIR / "git"), full)
async def _grade_sdlc(
test_command: str,
test_ref: str,
test_files: list[str],
golden_ref: str | None,
pr_rubric: str | None,
validate_mode: str | None,
) -> EvaluationResult:
if validate_mode == "golden":
# Simulate the workflow the agent is graded on: push the reference
# fix as a branch and open a pull request for it.
if not golden_ref:
raise ValueError('validate_mode="golden" needs golden_ref')
await repo_lib.git(VAULT_DIR / "git", "push", "-q", str(REMOTE_DIR), f"{golden_ref}:refs/heads/golden-fix")
_github.create_pull_request(
"Fix the reported bug", "Applies the reference fix.", head="golden-fix", base="main"
)
pr = _github.latest_pull_request()
if pr is None:
return EvaluationResult(reward=0.0, content="no pull request was opened")
# Hermetic checkout of the PR head from the remote (never the worktree).
grading_dir = LOGS_DIR / "pr-checkout"
shutil.rmtree(grading_dir, ignore_errors=True)
LOGS_DIR.mkdir(parents=True, exist_ok=True)
await repo_lib.run("git", "clone", "-q", str(REMOTE_DIR), str(grading_dir), cwd=LOGS_DIR)
code, _, err = await repo_lib.git(grading_dir, "checkout", "-q", pr.head, check=False)
if code != 0:
return EvaluationResult(
reward=0.0,
content=f"pull request head branch {pr.head!r} was never pushed",
info={"git_checkout": err.strip()[-2000:]},
)
await _fetch_hidden_ref(grading_dir, test_ref)
await repo_lib.git(grading_dir, "checkout", "FETCH_HEAD", "--", *test_files)
command = test_command.format(test_files=" ".join(test_files))
quality: Any
if pr_rubric:
quality = LLMJudgeGrader.grade(weight=0.2, answer=_github.transcript(), criteria=[pr_rubric])
else:
opened_well = bool(pr.title.strip() and pr.body.strip())
quality = SubScore(name="pull_request", value=1.0 if opened_well else 0.0, weight=0.2)
return await combine(
BashGrader.grade(weight=0.8, command=command, cwd=str(grading_dir), timeout_seconds=int(TESTS_TIMEOUT)),
quality,
)
@env.template(
id="sdlc-task",
description="Issue-driven bug fix: fix the code, push a branch, open a pull request.",
)
async def sdlc_task(
description: str,
test_command: str,
base_ref: str,
test_ref: str,
test_files: list[str],
issues: list[dict[str, Any]] | None = None,
golden_ref: str | None = None,
pr_rubric: str | None = None,
validate_mode: str | None = None,
):
"""The generic flavor plus workflow: the repo has an ``origin`` remote (a
bare mock-GitHub repo) and ``github_*`` tools seeded with *issues*; the
deliverable is a pushed branch with a pull request. Grading checks the PR
head out of the remote, brings in the hidden tests, runs ``test_command``
(weight 0.8), and scores the PR itself (weight 0.2) — structurally, or
against ``pr_rubric`` with an LLM judge when provided.
"""
if validate_mode not in (None, "golden"):
raise ValueError(f"unknown validate_mode: {validate_mode!r}")
_github.seed(issues or [])
await _setup(base_ref, remote=True)
_ = yield (
f"You are working in a coding repository located at {REPO_DIR}; its `origin` remote "
"is the team's shared repository, and the `github_*` tools give you the team's "
"issue tracker.\n\n"
"Complete the following task. When you are done, push your work to `origin` as a "
"new branch and open a pull request for it with `github_create_pull_request`. "
"Hidden tests grade your work; do not modify existing tests.\n\n"
f"{description}"
)
yield await _grade_sdlc(test_command, test_ref, test_files, golden_ref, pr_rubric, validate_mode)
# ─── SWE-bench Pro flavor (present only in baked instance images) ────────
if (INSTANCE_DIR / "instance.json").is_file():
INSTANCE = swe.load_instance(INSTANCE_DIR)
@env.template(
id=INSTANCE["instance_id"],
description=f"SWE-bench Pro instance on {INSTANCE['repo']}",
)
async def swe_bench_pro_task(validate_mode: str | None = None):
"""One SWE-bench Pro rollout. ``validate_mode="golden"`` grades the
dataset's golden patch instead of agent edits (gold-patch validation)."""
if validate_mode not in (None, "golden"):
raise ValueError(f"unknown validate_mode: {validate_mode!r}")
await _setup()
_ = yield swe.build_prompt(INSTANCE, REPO_DIR)
yield await swe.grade(
INSTANCE,
INSTANCE_DIR,
REPO_DIR,
VAULT_DIR,
LOGS_DIR,
validate_mode=validate_mode,
tests_timeout=TESTS_TIMEOUT,
)
|