zhiyuanhucs's picture
Publish clean five-benchmark evaluation code, fixed tasks and metric definitions
fb361ec verified
Raw History Blame Contribute Delete
8.44 kB
import json
import os
from pathlib import Path
import secrets
import shlex
import time
from harbor.agents.installed.opencode import OpenCode
from harbor.agents.installed.base import NonZeroAgentExitCodeError
ROOT=Path(os.environ['BENCH_OUTPUT'])
from harness.settings import MODEL
CLEAN = r'''set -euo pipefail
rm -rf /solution /root/.bash_history /root/.git-credentials /root/.ssh /root/.aws
for p in /root/test.patch /root/test_patch.patch /root/solution.patch /tmp/test.patch /tmp/test_patch.patch /tmp/solution.patch; do
[ ! -f "$p" ] || rm -f -- "$p"
done
mkdir -p /logs/artifacts
if git -C /app rev-parse --is-inside-work-tree >/dev/null 2>&1; then repo=/app
elif git -C /testbed rev-parse --is-inside-work-tree >/dev/null 2>&1; then repo=/testbed
else repo=''; fi
if [ -n "$repo" ]; then
git config --global --add safe.directory "$repo"
cd "$repo"
git config core.hooksPath /dev/null
git config gc.auto 0
git config maintenance.auto false
git config user.name 'Task Agent'
git config user.email 'agent@localhost'
git config commit.gpgsign false
HEAD_SHA=$(git rev-parse HEAD)
printf '%s\n' "$HEAD_SHA" > /opt/collection/base-sha
git checkout -B clean-base "$HEAD_SHA"
git for-each-ref --format='%(refname)' | while read -r ref; do
[ "$ref" = refs/heads/clean-base ] || git update-ref -d "$ref"
done
for remote in $(git remote); do git remote remove "$remote"; done
printf '%s\n' "$HEAD_SHA" > .git/shallow
git reflog expire --expire=now --all
git gc --prune=now
test "$(git rev-list --all --count)" = 1
git status --porcelain
printf 'CLEAN_REPOSITORY=%s\nBASE=%s\n' "$repo" "$HEAD_SHA"
fi
'''
class IsolatedOpenCode(OpenCode):
def __init__(self,*args,benchmark=None,task_path=None,trial_id=None,**kw):
super().__init__(*args,**kw)
self.benchmark=benchmark
self.task_path=Path(task_path) if task_path else None
self.trial_id=trial_id
self.sid=secrets.token_hex(16)
self.token=secrets.token_hex(32)
self.relay_port=int(os.environ.get('COLLECTION_RELAY_PORT','31631'))
self.base_url=f"http://{os.environ['BENCH_GATEWAY_HOST']}:{self.relay_port}/v1/{self.sid}"
self.repo='/app'
self._budget=14400 if benchmark=='pro' else 10800
(ROOT/'sessions').mkdir(exist_ok=True)
(ROOT/'sessions'/(self.sid+'.json')).write_text(json.dumps({'token':self.token,'expires':time.time()+21600,'trial':trial_id,'benchmark':benchmark,'temperature':float(os.environ.get('COLLECTION_TEMPERATURE','0.7')),'attempt':os.environ.get('COLLECTION_ATTEMPT')}))
self.logs_dir.mkdir(parents=True,exist_ok=True)
(self.logs_dir/'relay-session.json').write_text(json.dumps({'sid':self.sid,'model':MODEL,'trial':trial_id}))
def get_version_command(self):
return '/opt/collection/opencode --version'
async def install(self,environment):
await environment.exec(command='mkdir -p /opt/collection /logs/agent/opencode',user='root')
libc=await environment.exec(command='getconf GNU_LIBC_VERSION 2>/dev/null || true; ldd --version 2>&1 || true; ls /lib/ld-musl-*.so.1 2>/dev/null || true',user='root',timeout_sec=20)
description=(libc.stdout or '')+'\n'+(libc.stderr or '')
musl='musl' in description.lower() and 'glibc ' not in description.lower()
binary=Path(__file__).resolve().parents[1]/'assets'/('opencode-musl' if musl else 'opencode')
await environment.upload_file(binary,'/opt/collection/opencode')
(self.logs_dir/'runtime-compat.json').write_text(json.dumps({'binary':binary.name,'libc_probe':description,'version':'1.19.5'}))
await self.exec_as_root(environment,'chmod 755 /opt/collection/opencode && /opt/collection/opencode --version')
if self.benchmark=='pro':
spec=json.loads((self.task_path/'private_spec.json').read_text())
await self.exec_as_root(environment,'git config --global --add safe.directory /app && git -C /app -c core.hooksPath=/dev/null reset --hard '+shlex.quote(spec['base_commit'])+' && git -C /app clean -ffd && git -C /app ls-files -ci --exclude-standard -z > /opt/collection/tracked-ignored')
safe=[]
for p in spec.get('selected_test_files_to_run') or []:
p=p.removeprefix('/app/')
if p.startswith('/') or '..' in Path(p).parts: raise RuntimeError('Unsafe hidden test path')
safe.append(p)
if safe:
await self.exec_as_root(environment,'cd /app && git --literal-pathspecs rm -rf --ignore-unmatch -- '+' '.join(shlex.quote(p) for p in safe))
await self.exec_as_root(environment,"cd /app && rm -rf .git && git init -q && git config gc.auto 0 && git config maintenance.auto false && git config user.name 'Task Agent' && git config user.email agent@localhost && git -c core.hooksPath=/dev/null add -A && xargs -0 -r git --literal-pathspecs add -f -- < /opt/collection/tracked-ignored && git -c core.hooksPath=/dev/null -c commit.gpgsign=false commit --allow-empty -qm 'Base snapshot'")
# Terminal tasks can intentionally require their supplied Git history
# (for example repository recovery). Keep the native task filesystem;
# hidden verifier/solution material is never installed for the agent.
cleaning=CLEAN if self.benchmark!='tb' else "set -eu; rm -rf /solution /root/.git-credentials /root/.ssh /root/.aws; mkdir -p /logs/artifacts; printf 'NATIVE_TERMINAL_TASK_CONTEXT_PRESERVED\\n'"
cleanup=await self.exec_as_root(environment,cleaning,timeout_sec=600)
(self.logs_dir/'cleanroom-setup.json').write_text(json.dumps({'stdout':cleanup.stdout,'stderr':cleanup.stderr,'code':cleanup.return_code,'timestamp':time.time()}))
if 'CLEAN_REPOSITORY=/testbed' in (cleanup.stdout or ''): self.repo='/testbed'
from harness.settings import opencode_config
config=opencode_config(self.sid,self.token,self.relay_port)
(self.logs_dir/'opencode-config.json').write_text(json.dumps(config))
await environment.upload_file(self.logs_dir/'opencode-config.json','/opt/collection/opencode.json')
async def run(self,instruction,environment,context):
self._instruction=instruction
policy=environment.network_policy.model_dump(mode='json')
assert policy['network_mode']=='allowlist' and policy['allowed_hosts']==[os.environ['BENCH_GATEWAY_HOST']],policy
probe=r'''set -eu
for target in 1.1.1.1:80 169.254.169.254:80 __GATEWAY__:22 __GATEWAY__:65534; do
h=${target%:*};p=${target##*:}
if timeout 2 bash -c 'exec 3<>/dev/tcp/'"$h"'/'"$p" 2>/dev/null; then echo "UNEXPECTED_EGRESS $target";exit 42;else echo "BLOCKED $target";fi
done
'''
probe=probe.replace('__GATEWAY__',os.environ['BENCH_GATEWAY_HOST'])
result=await environment.exec(command='bash -c '+shlex.quote(probe),timeout_sec=20)
(self.logs_dir/'network-probes.json').write_text(json.dumps({'policy':policy,'code':result.return_code,'stdout':result.stdout,'stderr':result.stderr,'time':time.time()}))
if result.return_code: raise RuntimeError('Network isolation probe failed')
args=['/opt/collection/opencode','run','--pure','--format=json','--thinking','--auto','--model','collection/'+MODEL,'--',instruction]
command='set -o pipefail; timeout -k 30 '+str(self._budget)+' '+shlex.join(args)+' 2>&1 </dev/null | tee /logs/agent/opencode.txt'
env={'OPENCODE_CONFIG':'/opt/collection/opencode.json','OPENCODE_DISABLE_MODELS_FETCH':'true','OPENCODE_DISABLE_AUTOUPDATE':'true','OPENCODE_FAKE_VCS':'git','XDG_DATA_HOME':'/logs/agent/opencode/xdg-data','XDG_STATE_HOME':'/logs/agent/opencode/xdg-state','OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER':'true'}
try:
await self.exec_as_agent(environment,command=command,env=env,cwd=self.repo)
finally:
capture="if [ -f /opt/collection/base-sha ]; then cd "+shlex.quote(self.repo)+" && mkdir -p /logs/artifacts && git -c core.hooksPath=/dev/null add -A && git diff --cached --binary $(cat /opt/collection/base-sha) > /logs/artifacts/model.patch && git diff --cached --name-status $(cat /opt/collection/base-sha) > /logs/artifacts/changed-files.txt && git reset -q; fi"
await environment.exec(command=capture,user='root',timeout_sec=300)
if errors:=self._error_messages():
raise NonZeroAgentExitCodeError('; '.join(errors[:3]))