prophet / scripts /build_tasks.py
drkylj's picture
Add predictor spec and prompt; tasks get a Rules section; audit flags end-to-end solving
60f3845 verified
Raw History Blame Contribute Delete
13.6 kB
"""Build Harbor tasks for score-trajectory forecasting from data/normalized.
For a run with nodes 0..n-1 (train submissions then the final submission, in submission order),
task c (c = 0..n-1) cuts the trajectory at the moment node c is submitted:
- the sandbox gets every transcript unit before that moment, the results that were visible to the
agent before that moment, and the payloads of nodes 0..c (node c's payload is the one being judged);
- the agent predicts the scores of nodes c, c+1, ..., c+H-1 (those that exist).
So one trajectory with n nodes gives n tasks.
Usage: python -I scripts/build_tasks.py [--out tasks/fcs2-forecast] [--horizon 3] [--only-task T ...]
"""
import argparse, json, os, re, shutil, hashlib
from collections import defaultdict
NORM = 'data/normalized/'
FR = 'data/hf_raw/metadata/formal-results.json'
TRANSCRIPT_CAP = 3_000_000 # chars; keep the tail (most recent context) if longer
def fmt_dt(ms):
s = max(0, int(ms // 1000))
return f'+{s // 3600:d}h{(s % 3600) // 60:02d}m{s % 60:02d}s'
def true_score(n):
"""Ground-truth score of a node on the 0-100 scale; failed/invalid submissions count as 0."""
if n['mode'] == 'final':
v = n.get('formal_score')
if v is None:
v = n.get('raw_score')
else:
v = n.get('raw_score')
return 0.0 if v is None else float(v)
def render_transcript(units, cut, t0):
"""Units strictly before the cut; a thread's streamed response is kept only if no later
request of that thread happened before the cut (otherwise it is duplicated by that request)."""
pre = [u for u in units if u['t'] < cut]
last_nonresp = {}
for u in pre:
if u['kind'] != 'response':
last_nonresp[u['thread']] = u['t']
out = []
for u in pre:
if u['kind'] == 'response' and last_nonresp.get(u['thread'], -1) >= u['t']:
continue
tag = 'assistant (latest streamed reply)' if u['kind'] == 'response' else u['kind']
out.append(f"\n### [{fmt_dt(u['t'] - t0)}] [{u['thread']}] {tag}\n{u['text']}\n")
s = ''.join(out)
if len(s) > TRANSCRIPT_CAP:
s = f'[... earliest {len(s) - TRANSCRIPT_CAP} chars of the transcript omitted ...]\n' + s[-TRANSCRIPT_CAP:]
return s
INSTRUCTION = """# Forecast the scores of an AI agent's next submissions
You are watching an AI coding agent work on a research-engineering task from the **FrontierCS 2**
benchmark. The agent iterates: it edits code, submits a payload to a *train* verifier (which
returns a score on train workloads), and finally submits one *final* payload that is scored on
**hidden** workloads. Scores are on a 0-100 scale (higher is better); a submission that fails
verification scores 0.
The trajectory has been cut at the moment the agent submitted node **{c}** (0-based submission
index). Everything the agent saw up to that moment is in `/app/context/`:
- `run_info.json` - task, category, paper, the agent (model + harness), elapsed time at the cut.
- `transcript.md` - the agent's conversation up to the cut (model inputs/outputs, tool calls and
tool results, in time order; long items are truncated in the middle).
- `submissions.json` - every earlier submission: when it was made and, if the agent had already
seen it, its score, status and metrics. Results the agent had not yet seen are marked `pending`.
- `submissions/<i>/` - the files of submission `i` (for i <= {c}); `submissions/{c}/` is the
submission that was just made.
- `targets.json` - the submissions you must forecast.
## Rules
- Use only the files in `/app/context/`. No network, no web search, and do not try to find this
run, its dataset, or the paper's results anywhere else.
- Forecast by reading and reasoning. Think as long as you need: compare the submissions, read what
the agent tried and what it observed, and weigh the score history. Small calculations over the
context (diffs, greps, averages, trend fits) are fine.
- Do not solve the task end to end: do not build, install or run the submitted code or the task,
do not re-implement or improve the solution, and do not write benchmarks or simulations to
measure a score.
- Do not modify `/app/context/`.
## Your job
Predict the score of each target submission:
{targets_md}
Write `/app/prediction.json` exactly in this form (numbers on the 0-100 scale):
```json
{{"predictions": [{pred_example}], "rationale": "<a few sentences>"}}
```
You are graded on absolute error per target (reward = mean over targets of max(0, 1 - |error| / 10)).
"""
def build(args):
fr = json.load(open(FR))
tasks_meta = {}
for t in fr['tasks']:
tid = t.get('task_id') or t.get('id')
short = tid.replace('frontier-cs-2.0-', '').replace('-', '_')
tasks_meta[short] = t
runs = {(r['task'], r['model_id']): r for r in fr['runs']}
out_root = args.out
os.makedirs(out_root, exist_ok=True)
index = []
gt_all = {}
for task in sorted(os.listdir(NORM)):
if args.only_task and task not in args.only_task:
continue
for model in sorted(os.listdir(os.path.join(NORM, task))):
d = os.path.join(NORM, task, model)
if not os.path.exists(os.path.join(d, 'nodes.json')):
continue
nodes = json.load(open(os.path.join(d, 'nodes.json')))
meta = json.load(open(os.path.join(d, 'meta.json')))
if not nodes:
continue
units = [json.loads(l) for l in open(os.path.join(d, 'units.jsonl'))]
t0 = min([u['t'] for u in units] + [nodes[0]['t_submit']])
tm = tasks_meta.get(task, {})
run = runs.get((task, model), {})
for c in range(len(nodes)):
cut = nodes[c]['t_submit']
tgt = [nodes[j] for j in range(c, min(len(nodes), c + args.horizon))]
tid = f'{task}__{model}__c{c:03d}'.replace('_', '-').lower()
tdir = os.path.join(out_root, tid)
ctx = os.path.join(tdir, 'environment', 'context')
os.makedirs(ctx, exist_ok=True)
# --- transcript, guarded against any unit that reveals a not-yet-visible result
tr = render_transcript(units, cut, t0)
for n in nodes[c:]:
for m in re.finditer(re.escape(n['id']), tr):
win = tr[m.start():m.start() + 4000]
if re.search(r'raw_score"?\s*[:=]\s*[0-9]', win):
raise RuntimeError(f'leak guard: {tid} shows result of {n["id"]}')
open(os.path.join(ctx, 'transcript.md'), 'w').write(tr)
# --- submissions seen so far
subs = []
for n in nodes[:c + 1]:
seen = n.get('t_result') is not None and n['t_result'] < cut and n['idx'] < c
e = {'index': n['idx'], 'kind': n['mode'], 'submitted_at': fmt_dt(n['t_submit'] - t0)}
if n['idx'] == c:
e['result'] = 'just submitted (this is the first target)'
elif seen:
e.update({'result': 'seen', 'score': n.get('raw_score'), 'status': n.get('status'),
'summary': n.get('summary'), 'metrics': n.get('metrics')})
else:
e['result'] = 'pending (the agent had not seen this result at the cut)'
subs.append(e)
src = os.path.join(d, 'payloads', str(n['idx']))
if os.path.isdir(src):
shutil.copytree(src, os.path.join(ctx, 'submissions', str(n['idx'])), dirs_exist_ok=True)
json.dump(subs, open(os.path.join(ctx, 'submissions.json'), 'w'), indent=1)
info = {'benchmark': 'FrontierCS 2', 'task': task, 'task_display_name': tm.get('display_name') or tm.get('name'),
'category': tm.get('category'), 'paper_title': tm.get('paper_title'),
'agent': meta.get('candidate_name'), 'model_id': model,
'elapsed_at_cut': fmt_dt(cut - t0), 'cut_at_submission_index': c,
'submissions_so_far': c}
json.dump(info, open(os.path.join(ctx, 'run_info.json'), 'w'), indent=1)
targets = [{'index': n['idx'], 'kind': n['mode']} for n in tgt]
json.dump(targets, open(os.path.join(ctx, 'targets.json'), 'w'), indent=1)
# --- environment
if not args.sif: # docker: self-contained; identical layers above COPY are cached across tasks
open(os.path.join(tdir, 'environment', 'Dockerfile'), 'w').write(DOCKERFILE)
# --- instruction
tmd = '\n'.join(f"- submission {n['idx']} ({'final, hidden workloads' if n['mode']=='final' else 'train'})" for n in tgt)
ex = ', '.join(f'{{"index": {n["idx"]}, "score": <number>}}' for n in tgt)
open(os.path.join(tdir, 'instruction.md'), 'w').write(
INSTRUCTION.format(c=c, targets_md=tmd, pred_example=ex))
# --- tests (uploaded only after the agent finishes)
gt = [{'index': n['idx'], 'kind': n['mode'], 'score': true_score(n), 'status': n.get('status')} for n in tgt]
last_seen = [s for s in subs if s.get('result') == 'seen']
base = {'last_seen': (last_seen[-1]['score'] or 0.0) if last_seen else None,
'best_seen': max(((s['score'] or 0.0) for s in last_seen), default=None)}
os.makedirs(os.path.join(tdir, 'tests'), exist_ok=True)
json.dump({'targets': gt, 'baselines': base}, open(os.path.join(tdir, 'tests', 'ground_truth.json'), 'w'), indent=1)
shutil.copy('scripts/harbor_templates/test.sh', os.path.join(tdir, 'tests', 'test.sh'))
shutil.copy('scripts/harbor_templates/grade.py', os.path.join(tdir, 'tests', 'grade.py'))
os.makedirs(os.path.join(tdir, 'solution'), exist_ok=True)
sol = {'predictions': [{'index': g['index'], 'score': g['score']} for g in gt], 'rationale': 'oracle'}
open(os.path.join(tdir, 'solution', 'solve.sh'), 'w').write(
"#!/bin/bash\ncat > /app/prediction.json <<'EOF'\n" + json.dumps(sol) + "\nEOF\n")
os.chmod(os.path.join(tdir, 'solution', 'solve.sh'), 0o755)
envsec = (ENV_SIF.format(sif=args.sif) if args.sif else ENV_DOCKER)
open(os.path.join(tdir, 'task.toml'), 'w').write(TASK_TOML.format(
task=task, model=model, c=c, n=len(nodes), cat=tm.get('category', ''),
timeout=args.agent_timeout) + envsec)
gt_all[tid] = gt
index.append({'task_id': tid, 'fcs_task': task, 'model': model, 'cut': c, 'n_nodes': len(nodes),
'category': tm.get('category'), 'n_targets': len(gt),
'transcript_chars': len(tr), 'family': meta.get('family')})
json.dump(index, open(os.path.join(out_root, '..', os.path.basename(out_root) + '.index.json'), 'w'), indent=0)
json.dump(gt_all, open(os.path.join(out_root, '..', os.path.basename(out_root) + '.ground_truth.json'), 'w'))
print('tasks', len(index))
DOCKERFILE = """FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates ripgrep procps jq less \\
&& rm -rf /var/lib/apt/lists/*
# Claude Code preinstalled at build time, because at run time egress is limited to api.anthropic.com
RUN curl -fsSL https://downloads.claude.ai/claude-code-releases/bootstrap.sh | bash -s -- 2.1.335 \\
&& echo 'export PATH="$HOME/.local/bin:$PATH"' >> /root/.bashrc
ENV PATH=/root/.local/bin:$PATH
# Server-side web tools would bypass the egress allowlist, so they are denied by managed settings
RUN mkdir -p /etc/claude-code \\
&& printf '{"permissions": {"deny": ["WebFetch", "WebSearch"]}}\\n' > /etc/claude-code/managed-settings.json
WORKDIR /app
COPY context/ /app/context/
"""
TASK_TOML = '''schema_version = "1.4"
artifacts = []
[metadata]
benchmark = "frontiercs2-score-forecast"
fcs_task = "{task}"
fcs_model = "{model}"
cut_index = {c}
n_nodes = {n}
category = "{cat}"
[verifier]
timeout_sec = 120.0
environment_mode = "shared"
[agent]
timeout_sec = {timeout}
'''
# Docker: egress limited to the Anthropic API for the whole container lifetime.
ENV_DOCKER = '''
[environment]
network_mode = "allowlist"
allowed_hosts = ["api.anthropic.com"]
build_timeout_sec = 600.0
os = "linux"
cpus = 1
memory_mb = 2048
'''
# Apptainer (HPC, no root): prebuilt .sif; environment/ (the context) is uploaded to /app at start.
# Shared host network, so egress for the agent's Bash is closed by Claude Code's bubblewrap sandbox
# (managed settings baked into the image) and checked by a post-hoc audit.
ENV_SIF = '''
[environment]
docker_image = "{sif}"
network_mode = "public"
os = "linux"
cpus = 1
memory_mb = 2048
'''
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument('--out', default='tasks/fcs2-forecast')
ap.add_argument('--horizon', type=int, default=3)
ap.add_argument('--agent-timeout', type=float, default=1800.0)
ap.add_argument('--only-task', nargs='*')
ap.add_argument('--base-image', default='oraclebench/fcs2-forecast-base:v1')
ap.add_argument('--sif', default=None, help='build Apptainer variant using this .sif path')
build(ap.parse_args())