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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Repair the NL2Bash verifier schema and let the harness run the seed setup."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import copy
|
| 9 |
+
import gzip
|
| 10 |
+
import hashlib
|
| 11 |
+
import io
|
| 12 |
+
import re
|
| 13 |
+
import tarfile
|
| 14 |
+
import tomllib
|
| 15 |
+
|
| 16 |
+
REVISION = '946884702046be1a7dcea2638186ad6b0d2ea103'
|
| 17 |
+
PATCH_VERSIONS = (
|
| 18 |
+
'nl2bash-remove-unsupported-verifier-restart-v1',
|
| 19 |
+
'nl2bash-harness-seed-setup-v1',
|
| 20 |
+
'nl2bash-output-path-v1',
|
| 21 |
+
)
|
| 22 |
+
LABEL = 'static:task-toml-schema.py'
|
| 23 |
+
SETUP_LABEL = 'repair:harness-seed-setup.py'
|
| 24 |
+
OUTPUT_LABEL = 'repair:instruction-output-path.py'
|
| 25 |
+
REASONS = {
|
| 26 |
+
LABEL: ('Removed verifier.restart_environment from task.toml: the pinned Harbor '
|
| 27 |
+
'schema does not recognize this field and the runtime ignores it.'),
|
| 28 |
+
SETUP_LABEL: ('Renamed setup_files/setup_seeds.sh to setup_files/setup.sh and pointed '
|
| 29 |
+
'solve.sh at it (it called the missing /tests/setup_seeds.sh), so the harness '
|
| 30 |
+
'seeds /workspace before every trial; removed the instruction block that '
|
| 31 |
+
'asked the agent to run the script; the fixtures line now says the input '
|
| 32 |
+
'files are already in /workspace, and the claim that the verifier inspects '
|
| 33 |
+
'helper files is removed (it reads only /output/command_capture.txt).'),
|
| 34 |
+
OUTPUT_LABEL: ('The goal named the capture file as $PWD/command_capture.txt. The agent runs from '
|
| 35 |
+
'/workspace, so $PWD expands to /workspace, but the verifier reads only '
|
| 36 |
+
'/output/command_capture.txt (as the requirements say). The goal now names '
|
| 37 |
+
'/output/command_capture.txt; nothing else changes.'),
|
| 38 |
+
}
|
| 39 |
+
# Reviewed 2026-10-17 (stage-4 path warnings): goal sentences that name a capture file other than
|
| 40 |
+
# the one the verifier reads. Exact one-occurrence replacement, per task.
|
| 41 |
+
OUTPUT_PATH_FIXES = {
|
| 42 |
+
'task_267': (b'capturing output in $PWD/command_capture.txt.',
|
| 43 |
+
b'capturing output in /output/command_capture.txt.'),
|
| 44 |
+
}
|
| 45 |
+
SEED_SCRIPT = 'setup_files/setup_seeds.sh'
|
| 46 |
+
HARNESS_SCRIPT = 'setup_files/setup.sh'
|
| 47 |
+
BROKEN_SETUP_CALL = b'bash /tests/setup_seeds.sh'
|
| 48 |
+
HARNESS_SETUP_CALL = b'bash /setup_files/setup.sh'
|
| 49 |
+
INSTRUCTION_SETUP = (b'## Environment Setup (run before starting)\n\n```bash\n'
|
| 50 |
+
b'bash /setup_files/setup_seeds.sh\n```\n\n---\n\n')
|
| 51 |
+
INPUT_LINES = (
|
| 52 |
+
b'- From `/workspace`, assemble any missing fixtures using standard shell utilities '
|
| 53 |
+
b'before running your command.\n',
|
| 54 |
+
b'- The workspace already contains pre-seeded fixtures copied to `/workspace`; '
|
| 55 |
+
b'run the command from that directory.\n',
|
| 56 |
+
)
|
| 57 |
+
INPUT_LINE = (b'- The input files for this task are already in `/workspace`; '
|
| 58 |
+
b'run the command from that directory.\n')
|
| 59 |
+
HELPER_LINE = b'- Do not delete any helper files generated during execution; the verifier inspects them.\n'
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rewrite_instruction(body):
|
| 63 |
+
"""Drop the setup block and the two lines that misdescribe the seeded start state."""
|
| 64 |
+
text = body[len(INSTRUCTION_SETUP):]
|
| 65 |
+
if [text.count(line) for line in INPUT_LINES].count(1) != 1 or \
|
| 66 |
+
sum(text.count(line) for line in INPUT_LINES) != 1 or text.count(HELPER_LINE) != 1:
|
| 67 |
+
raise ValueError('instruction.md lacks the expected fixtures and helper-files lines')
|
| 68 |
+
for line in INPUT_LINES:
|
| 69 |
+
text = text.replace(line, INPUT_LINE)
|
| 70 |
+
return text.replace(HELPER_LINE, b'')
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def clean_config(content):
|
| 74 |
+
"""Remove only the unsupported field; verify every other TOML value survives."""
|
| 75 |
+
text = content.decode('utf-8')
|
| 76 |
+
before = tomllib.loads(text)
|
| 77 |
+
if 'restart_environment' not in before.get('verifier', {}):
|
| 78 |
+
return content
|
| 79 |
+
expected = copy.deepcopy(before)
|
| 80 |
+
del expected['verifier']['restart_environment']
|
| 81 |
+
section = re.compile(r'(?ms)(^\[verifier\][^\n]*\n)(.*?)(?=^\[|\Z)')
|
| 82 |
+
field = re.compile(r'(?m)^[ \t]*(?:restart_environment|"restart_environment"|\'restart_environment\')[ \t]*=[^\n]*(?:\n|$)')
|
| 83 |
+
cleaned = section.sub(lambda m: m[1] + field.sub('', m[2]), text)
|
| 84 |
+
if tomllib.loads(cleaned) != expected:
|
| 85 |
+
raise ValueError('Unsupported task.toml layout for verifier.restart_environment removal')
|
| 86 |
+
return cleaned.encode('utf-8')
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def patch_archive(blob, task_id=None):
|
| 90 |
+
"""Apply narrowly scoped fixes while preserving all other archive payloads."""
|
| 91 |
+
with tarfile.open(fileobj=io.BytesIO(blob), mode='r:*') as source:
|
| 92 |
+
members = source.getmembers()
|
| 93 |
+
configs = [m for m in members if Path(m.name).as_posix() == 'task.toml']
|
| 94 |
+
if len(configs) != 1 or not configs[0].isfile():
|
| 95 |
+
raise ValueError('Expected exactly one regular task.toml in task archive')
|
| 96 |
+
config = configs[0]
|
| 97 |
+
original = source.extractfile(config).read()
|
| 98 |
+
cleaned = clean_config(original)
|
| 99 |
+
edited = {}
|
| 100 |
+
labels = []
|
| 101 |
+
if cleaned != original:
|
| 102 |
+
edited[id(config)] = cleaned
|
| 103 |
+
labels.append(LABEL)
|
| 104 |
+
|
| 105 |
+
by_name = {Path(m.name).as_posix(): m for m in members}
|
| 106 |
+
helper = by_name.get(SEED_SCRIPT)
|
| 107 |
+
solutions = [m for m in members
|
| 108 |
+
if Path(m.name).as_posix().startswith('solution/') and m.isfile()]
|
| 109 |
+
solution_bodies = {id(m): source.extractfile(m).read() for m in solutions}
|
| 110 |
+
instruction = by_name.get('instruction.md')
|
| 111 |
+
instruction_body = source.extractfile(instruction).read() if instruction else b''
|
| 112 |
+
calls = any(BROKEN_SETUP_CALL in body for body in solution_bodies.values())
|
| 113 |
+
renamed = {}
|
| 114 |
+
if helper is not None or calls or b'setup_seeds' in instruction_body:
|
| 115 |
+
# All three parts belong together; anything else needs a human look.
|
| 116 |
+
if helper is None or not helper.isfile() or not calls or HARNESS_SCRIPT in by_name:
|
| 117 |
+
raise ValueError('Unexpected seed setup layout: need setup_files/setup_seeds.sh, '
|
| 118 |
+
'a /tests/setup_seeds.sh call in solve.sh and no setup_files/setup.sh')
|
| 119 |
+
if not instruction_body.startswith(INSTRUCTION_SETUP) or \
|
| 120 |
+
b'setup_seeds' in instruction_body[len(INSTRUCTION_SETUP):]:
|
| 121 |
+
raise ValueError('instruction.md does not start with the expected seed setup block')
|
| 122 |
+
renamed[id(helper)] = HARNESS_SCRIPT
|
| 123 |
+
edited[id(instruction)] = rewrite_instruction(instruction_body)
|
| 124 |
+
for member in solutions:
|
| 125 |
+
body = solution_bodies[id(member)]
|
| 126 |
+
fixed = body.replace(BROKEN_SETUP_CALL, HARNESS_SETUP_CALL)
|
| 127 |
+
if fixed != body:
|
| 128 |
+
edited[id(member)] = fixed
|
| 129 |
+
labels.append(SETUP_LABEL)
|
| 130 |
+
if task_id in OUTPUT_PATH_FIXES:
|
| 131 |
+
old, new = OUTPUT_PATH_FIXES[task_id]
|
| 132 |
+
body = edited.get(id(instruction), instruction_body) if instruction else b''
|
| 133 |
+
if body.count(old) == 1:
|
| 134 |
+
edited[id(instruction)] = body.replace(old, new)
|
| 135 |
+
labels.append(OUTPUT_LABEL)
|
| 136 |
+
elif not (body.count(old) == 0 and body.count(new) == 1):
|
| 137 |
+
raise ValueError(f'{task_id}: expected exactly one {old!r} in instruction.md')
|
| 138 |
+
if not edited:
|
| 139 |
+
return blob, []
|
| 140 |
+
output = io.BytesIO()
|
| 141 |
+
compressed = blob[:2] == b'\x1f\x8b'
|
| 142 |
+
stream = gzip.GzipFile(filename='', fileobj=output, mode='wb', mtime=0) if compressed else output
|
| 143 |
+
with tarfile.open(fileobj=stream, mode='w', format=source.format) as target:
|
| 144 |
+
for member in members:
|
| 145 |
+
info = copy.copy(member)
|
| 146 |
+
info.name = renamed.get(id(member), member.name)
|
| 147 |
+
body = edited.get(id(member), source.extractfile(member).read()) if member.isfile() else None
|
| 148 |
+
if member.isfile() and id(member) in edited:
|
| 149 |
+
info.size = len(body)
|
| 150 |
+
target.addfile(info, io.BytesIO(body) if body is not None else None)
|
| 151 |
+
if compressed:
|
| 152 |
+
stream.close()
|
| 153 |
+
return output.getvalue(), labels
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def patch(source, output):
|
| 157 |
+
import pyarrow as pa
|
| 158 |
+
import pyarrow.parquet as pq
|
| 159 |
+
from data.utils.patch_reporting import write_patch_report
|
| 160 |
+
|
| 161 |
+
source, output = Path(source), Path(output)
|
| 162 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
destination = output / 'tasks.parquet'
|
| 164 |
+
if destination.exists():
|
| 165 |
+
raise ValueError('Use a new patch output directory')
|
| 166 |
+
parquet = pq.ParquetFile(source)
|
| 167 |
+
changed = {}
|
| 168 |
+
with pq.ParquetWriter(destination, parquet.schema_arrow) as writer:
|
| 169 |
+
for batch in parquet.iter_batches(batch_size=32):
|
| 170 |
+
rows = batch.to_pylist()
|
| 171 |
+
for row in rows:
|
| 172 |
+
row['task_binary'], labels = patch_archive(row['task_binary'], row['path'])
|
| 173 |
+
if labels:
|
| 174 |
+
changed[row['path']] = labels
|
| 175 |
+
writer.write_table(pa.Table.from_pylist(rows, schema=parquet.schema_arrow))
|
| 176 |
+
with source.open('rb') as source_stream:
|
| 177 |
+
source_hash = hashlib.file_digest(source_stream, 'sha256').hexdigest()
|
| 178 |
+
return write_patch_report(source, destination, source={
|
| 179 |
+
'dataset': 'open-thoughts/TaskTrove/nl2bash (TOML-normalized input)',
|
| 180 |
+
'url': 'https://huggingface.co/datasets/open-thoughts/TaskTrove',
|
| 181 |
+
'revision': f'sha256:{source_hash}'}, dropped={}, change_labels=changed,
|
| 182 |
+
change_reasons={name: '; '.join(REASONS[label] for label in labels)
|
| 183 |
+
for name, labels in changed.items()},
|
| 184 |
+
patches=PATCH_VERSIONS, patcher=__file__)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def main():
|
| 188 |
+
parser = argparse.ArgumentParser()
|
| 189 |
+
parser.add_argument('--source', type=Path, required=True)
|
| 190 |
+
parser.add_argument('--output', type=Path, required=True)
|
| 191 |
+
args = parser.parse_args()
|
| 192 |
+
report = patch(args.source, args.output)
|
| 193 |
+
print(f"NL2Bash: {sum(t['action'] == 'changed' for t in report['tasks'])} tasks repaired")
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if __name__ == '__main__':
|
| 197 |
+
main()
|