File size: 53,771 Bytes
b199558
 
 
 
1
2
3
4
5
{"task_id": "tbdl-access-log-report", "instruction": "# Access log report\n\n`logs/access.log` is a web server access log in a combined-ish format:\n\n```\n<ip> - - [<timestamp>] \"<METHOD> <path> HTTP/1.1\" <status> <bytes> \"<referer>\" \"<user-agent>\" <duration_ms>\n```\n\nSome lines are damaged. The user-agent field may contain escaped double quotes\n(`\\\"`), so the line cannot be parsed by splitting on `\"` -- quoted fields have to\nbe scanned properly. `bytes` is `-` when the server did not record a size.\n\nWrite **`tools/report.sh`** in the workspace root. Running\n\n```\nbash tools/report.sh\n```\n\nfrom the workspace root must read `logs/access.log` and (re)generate the\nfollowing under `out/`, exit 0, and print nothing that matters. It must be\nidempotent: deleting `out/` and running it again must produce byte-identical\nfiles.\n\n## `out/report.json`\n\nA JSON object with exactly these keys:\n\n| key | type | meaning |\n| --- | --- | --- |\n| `total_requests` | int | number of **valid** lines |\n| `unique_paths` | int | number of distinct normalised paths |\n| `status_counts` | object | `{\"<status>\": <count>}`, keys are strings; only statuses that occur |\n| `top_paths` | array | up to 3 objects `{\"path\": str, \"count\": int}`, highest count first, ties broken by path ascending |\n| `bytes_total` | int | sum of `bytes` over valid lines, `-` counts as 0 |\n| `p95_ms` | int | 95th percentile of `duration_ms`, nearest-rank method |\n\n`p95_ms` is the nearest-rank percentile: sort the durations ascending, take\nelement number `ceil(0.95 * n)` counting from 1. With `n = 36` that is the 35th\nsmallest duration. If there are no valid lines, `p95_ms` is `0`.\n\nPaths are normalised by dropping everything from the first `?` onwards, so\n`/api/users?id=42` counts as `/api/users`.\n\n## `out/malformed.txt`\n\nThe 1-based line numbers of the lines that do not match the grammar above, one\nper line, ascending. A line is malformed if any of these hold: it is not the\nnine-part shape above, `status` is not exactly three digits, `bytes` is neither\n`-` nor digits, or the trailing `duration_ms` is missing or not digits.\nMalformed lines are excluded from every aggregate.\n\n## `out/access.log.gz`\n\nA gzip stream whose decompressed content is byte-for-byte identical to\n`logs/access.log`.\n\n## Notes\n\n- Only `logs/access.log` is input; do not edit it.\n- `python` is on `PATH` (`python3` is also available). Standard library only --\n  there is no network access.\n", "author_name": "WorkBuddy Benchmarks", "author_email": "benchmarks@example.invalid", "difficulty": "medium", "category": "data-processing", "tags": ["log-parsing", "text-processing", "json", "python"], "parser_name": "pytest", "max_agent_timeout_sec": 600.0, "max_test_timeout_sec": 120.0, "expert_time_estimate_min": 25, "junior_time_estimate_min": 90, "task_yaml": "# Terminal-Bench task definition\ninstruction: |\n  # Access log report\n\n  `logs/access.log` is a web server access log in a combined-ish format:\n\n  ```\n  <ip> - - [<timestamp>] \"<METHOD> <path> HTTP/1.1\" <status> <bytes> \"<referer>\" \"<user-agent>\" <duration_ms>\n  ```\n\n  Some lines are damaged. The user-agent field may contain escaped double quotes\n  (`\\\"`), so the line cannot be parsed by splitting on `\"` -- quoted fields have to\n  be scanned properly. `bytes` is `-` when the server did not record a size.\n\n  Write **`tools/report.sh`** in the workspace root. Running\n\n  ```\n  bash tools/report.sh\n  ```\n\n  from the workspace root must read `logs/access.log` and (re)generate the\n  following under `out/`, exit 0, and print nothing that matters. It must be\n  idempotent: deleting `out/` and running it again must produce byte-identical\n  files.\n\n  ## `out/report.json`\n\n  A JSON object with exactly these keys:\n\n  | key | type | meaning |\n  | --- | --- | --- |\n  | `total_requests` | int | number of **valid** lines |\n  | `unique_paths` | int | number of distinct normalised paths |\n  | `status_counts` | object | `{\"<status>\": <count>}`, keys are strings; only statuses that occur |\n  | `top_paths` | array | up to 3 objects `{\"path\": str, \"count\": int}`, highest count first, ties broken by path ascending |\n  | `bytes_total` | int | sum of `bytes` over valid lines, `-` counts as 0 |\n  | `p95_ms` | int | 95th percentile of `duration_ms`, nearest-rank method |\n\n  `p95_ms` is the nearest-rank percentile: sort the durations ascending, take\n  element number `ceil(0.95 * n)` counting from 1. With `n = 36` that is the 35th\n  smallest duration. If there are no valid lines, `p95_ms` is `0`.\n\n  Paths are normalised by dropping everything from the first `?` onwards, so\n  `/api/users?id=42` counts as `/api/users`.\n\n  ## `out/malformed.txt`\n\n  The 1-based line numbers of the lines that do not match the grammar above, one\n  per line, ascending. A line is malformed if any of these hold: it is not the\n  nine-part shape above, `status` is not exactly three digits, `bytes` is neither\n  `-` nor digits, or the trailing `duration_ms` is missing or not digits.\n  Malformed lines are excluded from every aggregate.\n\n  ## `out/access.log.gz`\n\n  A gzip stream whose decompressed content is byte-for-byte identical to\n  `logs/access.log`.\n\n  ## Notes\n\n  - Only `logs/access.log` is input; do not edit it.\n  - `python` is on `PATH` (`python3` is also available). Standard library only --\n    there is no network access.\nauthor_name: WorkBuddy Benchmarks\nauthor_email: benchmarks@example.invalid\ndifficulty: medium\ncategory: data-processing\ntags:\n  - log-parsing\n  - text-processing\n  - json\n  - python\nparser_name: pytest\nmax_agent_timeout_sec: 600.0\nmax_test_timeout_sec: 120.0\nexpert_time_estimate_min: 25\njunior_time_estimate_min: 90\n", "task_toml": "schema_version = \"1.4\"\nsource = \"TerminalBench-DockerLess\"\n\n[task]\nname = \"swedl/access-log-report\"\nauthors = [{ name = \"WorkBuddy Benchmarks\", email = \"benchmarks@example.invalid\" }]\ndescription = \"Aggregate a damaged access log into a canonical JSON report, a malformed-line index and a gzip archive.\"\nkeywords = [\"log-parsing\", \"text-processing\", \"json\", \"python\"]\n\n[metadata]\ndifficulty = \"medium\"\ncategory = \"data-processing\"\ntags = [\"log-parsing\", \"text-processing\", \"json\", \"python\"]\nexpert_time_estimate_min = 25\njunior_time_estimate_min = 90\n\n[verifier]\ntimeout_sec = 120.0\n\n[agent]\ntimeout_sec = 600.0\n\n[environment]\nnetwork_mode = \"no-network\"\nos = \"linux\"\nworkdir = \"/workspace\"\n", "dockerfile": "FROM python:3.13-slim\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n        bash coreutils gzip git \\\n    && rm -rf /var/lib/apt/lists/*\n\nWORKDIR /workspace\nCOPY logs/ /workspace/logs/\n\nCMD [\"/bin/bash\"]\n", "solution": "#!/usr/bin/env bash\n# Oracle solution: a regex-based parser that survives escaped quotes in the\n# user-agent field, plus deterministic JSON/gzip output.\nset -euo pipefail\ncd \"$TB_WORK\"\nmkdir -p tools\n\ncat > tools/report.py <<'PYEOF'\nimport gzip\nimport json\nimport math\nimport re\nfrom collections import Counter\nfrom pathlib import Path\n\nLINE = re.compile(\n    r'^(?P<ip>\\S+) - - \\[(?P<ts>[^\\]]+)\\] '\n    r'\"(?P<method>[A-Z]+) (?P<path>\\S+) HTTP/1\\.1\" '\n    r'(?P<status>\\d{3}) (?P<size>\\d+|-) '\n    r'\"(?P<ref>(?:[^\"\\\\]|\\\\.)*)\" \"(?P<ua>(?:[^\"\\\\]|\\\\.)*)\" '\n    r'(?P<ms>\\d+)$'\n)\n\n\ndef main():\n    root = Path(__file__).resolve().parent.parent\n    log = root / \"logs\" / \"access.log\"\n    raw = log.read_bytes()\n    lines = raw.decode(\"utf-8\").split(\"\\n\")\n    if lines and lines[-1] == \"\":\n        lines.pop()\n\n    paths, statuses, durations, bad = [], [], [], []\n    total_bytes = 0\n    for number, line in enumerate(lines, 1):\n        match = LINE.match(line)\n        if match is None:\n            bad.append(number)\n            continue\n        paths.append(match.group(\"path\").split(\"?\")[0])\n        statuses.append(match.group(\"status\"))\n        size = match.group(\"size\")\n        total_bytes += 0 if size == \"-\" else int(size)\n        durations.append(int(match.group(\"ms\")))\n\n    durations.sort()\n    count = len(durations)\n    p95 = durations[math.ceil(0.95 * count) - 1] if count else 0\n\n    path_counts = Counter(paths)\n    top = sorted(path_counts.items(), key=lambda item: (-item[1], item[0]))[:3]\n\n    report = {\n        \"total_requests\": count,\n        \"unique_paths\": len(path_counts),\n        \"status_counts\": dict(sorted(Counter(statuses).items())),\n        \"top_paths\": [{\"path\": path, \"count\": hits} for path, hits in top],\n        \"bytes_total\": total_bytes,\n        \"p95_ms\": p95,\n    }\n\n    out = root / \"out\"\n    out.mkdir(parents=True, exist_ok=True)\n    with open(out / \"report.json\", \"w\", encoding=\"utf-8\", newline=\"\\n\") as handle:\n        handle.write(json.dumps(report, indent=2, sort_keys=True) + \"\\n\")\n    with open(out / \"malformed.txt\", \"w\", encoding=\"utf-8\", newline=\"\\n\") as handle:\n        handle.write(\"\".join(\"%d\\n\" % number for number in bad))\n    with open(out / \"access.log.gz\", \"wb\") as handle:\n        with gzip.GzipFile(fileobj=handle, mode=\"wb\", mtime=0) as gz:\n            gz.write(raw)\n\n\nif __name__ == \"__main__\":\n    main()\nPYEOF\n\ncat > tools/report.sh <<'SHEOF'\n#!/usr/bin/env bash\nset -euo pipefail\nhere=\"$(cd \"$(dirname \"$0\")/..\" && pwd)\"\nexec python \"$here/tools/report.py\"\nSHEOF\n\nchmod +x tools/report.sh\nbash tools/report.sh\n", "tests": {"test.sh": "#!/usr/bin/env bash\n# Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the\n# reward signal (0 = solved).\nset -uo pipefail\ncd \"$TB_ROOT/tests\"\npython -m pytest -v --tb=short -p no:cacheprovider test_outputs.py\n", "test_outputs.py": "import gzip\nimport json\nimport os\nimport shutil\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\n\nWORK = Path(os.environ[\"TB_WORK\"])\nBASH = os.environ.get(\"TB_BASH\", \"bash\")\n\n\ndef load_report():\n    path = WORK / \"out\" / \"report.json\"\n    assert path.is_file(), \"out/report.json was not created\"\n    return json.loads(path.read_text(encoding=\"utf-8\"))\n\n\ndef test_report_has_exactly_the_documented_keys():\n    report = load_report()\n    assert sorted(report) == [\n        \"bytes_total\",\n        \"p95_ms\",\n        \"status_counts\",\n        \"top_paths\",\n        \"total_requests\",\n        \"unique_paths\",\n    ]\n\n\ndef test_total_requests_counts_only_valid_lines():\n    assert load_report()[\"total_requests\"] == 36\n\n\ndef test_unique_paths_ignores_query_strings():\n    assert load_report()[\"unique_paths\"] == 5\n\n\ndef test_status_counts():\n    assert load_report()[\"status_counts\"] == {\"200\": 28, \"304\": 4, \"404\": 3, \"500\": 1}\n\n\ndef test_top_paths_order_and_tiebreak():\n    assert load_report()[\"top_paths\"] == [\n        {\"path\": \"/api/users\", \"count\": 12},\n        {\"path\": \"/index.html\", \"count\": 12},\n        {\"path\": \"/static/app.js\", \"count\": 6},\n    ]\n\n\ndef test_bytes_total_treats_dash_as_zero():\n    assert load_report()[\"bytes_total\"] == 14535\n\n\ndef test_p95_uses_nearest_rank():\n    assert load_report()[\"p95_ms\"] == 162\n\n\ndef test_malformed_line_numbers():\n    path = WORK / \"out\" / \"malformed.txt\"\n    assert path.is_file(), \"out/malformed.txt was not created\"\n    numbers = [int(line) for line in path.read_text(encoding=\"utf-8\").split()]\n    assert numbers == [7, 19, 28, 37]\n\n\ndef test_gzip_roundtrip_is_byte_identical():\n    original = (WORK / \"logs\" / \"access.log\").read_bytes()\n    archive = WORK / \"out\" / \"access.log.gz\"\n    assert archive.is_file(), \"out/access.log.gz was not created\"\n    assert gzip.decompress(archive.read_bytes()) == original\n\n\ndef test_script_regenerates_identical_output():\n    out = WORK / \"out\"\n    before = (out / \"report.json\").read_bytes()\n    before_bad = (out / \"malformed.txt\").read_bytes()\n    shutil.rmtree(out)\n    proc = subprocess.run(\n        [BASH, \"tools/report.sh\"],\n        cwd=str(WORK),\n        capture_output=True,\n        text=True,\n    )\n    assert proc.returncode == 0, \"tools/report.sh failed:\\n%s\\n%s\" % (proc.stdout, proc.stderr)\n    assert (out / \"report.json\").read_bytes() == before\n    assert (out / \"malformed.txt\").read_bytes() == before_bad\n"}, "dockerless": {"setup": "", "setup_timeout_sec": 120, "files": {"logs/access.log": "10.0.0.1 - - [10/Oct/2026:13:00:00 +0000] \"GET /index.html HTTP/1.1\" 200 200 \"-\" \"curl/8.5.0\" 3\n10.0.0.2 - - [10/Oct/2026:13:00:17 +0000] \"GET /index.html HTTP/1.1\" 200 213 \"https://example.com/\" \"curl/8.5.0\" 25\n10.0.0.3 - - [10/Oct/2026:13:01:34 +0000] \"GET /index.html HTTP/1.1\" 200 226 \"https://example.com/\" \"curl/8.5.0\" 52\n10.0.0.4 - - [10/Oct/2026:13:01:51 +0000] \"GET /index.html HTTP/1.1\" 200 239 \"https://example.com/\" \"curl/8.5.0\" 78\n10.0.0.5 - - [10/Oct/2026:13:02:08 +0000] \"GET /index.html HTTP/1.1\" 200 252 \"-\" \"curl/8.5.0\" 110\n10.0.0.6 - - [10/Oct/2026:13:02:25 +0000] \"GET /index.html HTTP/1.1\" 200 265 \"https://example.com/\" \"Mozilla/5.0 (\\\"compatible\\\"; bot) Gecko/20100101\" 175\n10.0.0.9 - - [10/Oct/2026:13:02:11 +0000] \"GET /index.html HTTP/1.1\" 200 512 \"-\" \"curl/8.0\"\n10.0.0.7 - - [10/Oct/2026:13:03:42 +0000] \"GET /index.html HTTP/1.1\" 200 278 \"https://example.com/\" \"curl/8.5.0\" 21\n10.0.0.8 - - [10/Oct/2026:13:03:59 +0000] \"GET /index.html HTTP/1.1\" 200 291 \"https://example.com/\" \"curl/8.5.0\" 47\n10.0.0.9 - - [10/Oct/2026:13:04:16 +0000] \"GET /index.html HTTP/1.1\" 200 304 \"-\" \"curl/8.5.0\" 74\n10.0.0.1 - - [10/Oct/2026:13:04:33 +0000] \"GET /index.html HTTP/1.1\" 200 - \"https://example.com/\" \"curl/8.5.0\" 104\n10.0.0.2 - - [10/Oct/2026:13:05:50 +0000] \"GET /index.html HTTP/1.1\" 200 330 \"https://example.com/\" \"curl/8.5.0\" 162\n10.0.0.3 - - [10/Oct/2026:13:05:07 +0000] \"GET /index.html HTTP/1.1\" 200 343 \"https://example.com/\" \"curl/8.5.0\" 18\n10.0.0.4 - - [10/Oct/2026:13:06:24 +0000] \"GET /api/users HTTP/1.1\" 200 356 \"-\" \"curl/8.5.0\" 44\n10.0.0.5 - - [10/Oct/2026:13:06:41 +0000] \"GET /api/users HTTP/1.1\" 200 369 \"https://example.com/\" \"curl/8.5.0\" 70\n10.0.0.6 - - [10/Oct/2026:13:07:58 +0000] \"GET /api/users HTTP/1.1\" 200 382 \"https://example.com/\" \"curl/8.5.0\" 99\n10.0.0.7 - - [10/Oct/2026:13:07:15 +0000] \"POST /api/users HTTP/1.1\" 200 395 \"https://example.com/\" \"curl/8.5.0\" 150\n10.0.0.8 - - [10/Oct/2026:13:08:32 +0000] \"GET /api/users HTTP/1.1\" 200 408 \"-\" \"curl/8.5.0\" 14\n10.0.0.3 - - [10/Oct/2026:13:05:44 +0000] \"POST /api/users HTTP/1.1\" abc 300 \"-\" \"curl/8.0\" 44\n10.0.0.9 - - [10/Oct/2026:13:08:49 +0000] \"GET /api/users HTTP/1.1\" 200 421 \"https://example.com/\" \"Mozilla/5.0 (\\\"compatible\\\"; bot) Gecko/20100101\" 40\n10.0.0.1 - - [10/Oct/2026:13:09:06 +0000] \"GET /api/users HTTP/1.1\" 200 434 \"https://example.com/\" \"curl/8.5.0\" 66\n10.0.0.2 - - [10/Oct/2026:13:09:23 +0000] \"GET /api/users HTTP/1.1\" 200 447 \"https://example.com/\" \"curl/8.5.0\" 95\n10.0.0.3 - - [10/Oct/2026:13:10:40 +0000] \"GET /api/users?id=42 HTTP/1.1\" 200 460 \"-\" \"curl/8.5.0\" 141\n10.0.0.4 - - [10/Oct/2026:13:10:57 +0000] \"GET /api/users?id=42 HTTP/1.1\" 200 473 \"https://example.com/\" \"curl/8.5.0\" 12\n10.0.0.5 - - [10/Oct/2026:13:11:14 +0000] \"GET /api/users?id=42 HTTP/1.1\" 200 486 \"https://example.com/\" \"curl/8.5.0\" 35\n10.0.0.6 - - [10/Oct/2026:13:11:31 +0000] \"GET /api/users?id=42 HTTP/1.1\" 200 499 \"https://example.com/\" \"curl/8.5.0\" 61\n10.0.0.7 - - [10/Oct/2026:13:12:48 +0000] \"GET /static/app.js HTTP/1.1\" 200 512 \"-\" \"curl/8.5.0\" 90\n10.0.0.4 - - [10/Oct/2026:13:09:02 +0000] \"GET /health HTTP/1.1\" 200 0\n10.0.0.8 - - [10/Oct/2026:13:12:05 +0000] \"GET /static/app.js HTTP/1.1\" 200 525 \"https://example.com/\" \"curl/8.5.0\" 133\n10.0.0.9 - - [10/Oct/2026:13:13:22 +0000] \"GET /static/app.js HTTP/1.1\" 200 - \"https://example.com/\" \"curl/8.5.0\" 11\n10.0.0.1 - - [10/Oct/2026:13:13:39 +0000] \"GET /static/app.js HTTP/1.1\" 200 551 \"https://example.com/\" \"curl/8.5.0\" 31\n10.0.0.2 - - [10/Oct/2026:13:14:56 +0000] \"GET /static/app.js HTTP/1.1\" 304 564 \"-\" \"curl/8.5.0\" 58\n10.0.0.3 - - [10/Oct/2026:13:14:13 +0000] \"GET /static/app.js HTTP/1.1\" 304 577 \"https://example.com/\" \"curl/8.5.0\" 85\n10.0.0.4 - - [10/Oct/2026:13:15:30 +0000] \"GET /health HTTP/1.1\" 304 590 \"https://example.com/\" \"curl/8.5.0\" 126\n10.0.0.5 - - [10/Oct/2026:13:15:47 +0000] \"GET /health HTTP/1.1\" 304 603 \"https://example.com/\" \"curl/8.5.0\" 7\n10.0.0.6 - - [10/Oct/2026:13:16:04 +0000] \"GET /health HTTP/1.1\" 404 616 \"-\" \"curl/8.5.0\" 28\n# rotated by logrotate at 2026-10-10T14:00:00Z\n10.0.0.7 - - [10/Oct/2026:13:16:21 +0000] \"GET /api/orders HTTP/1.1\" 404 629 \"https://example.com/\" \"curl/8.5.0\" 55\n10.0.0.8 - - [10/Oct/2026:13:17:38 +0000] \"GET /api/orders HTTP/1.1\" 404 642 \"https://example.com/\" \"curl/8.5.0\" 82\n10.0.0.9 - - [10/Oct/2026:13:17:55 +0000] \"GET /api/orders HTTP/1.1\" 500 655 \"https://example.com/\" \"curl/8.5.0\" 118\n"}, "test_cmd": "", "workdir": "workspace", "requires": ["bash", "python"], "baseline_failures": ["test_outputs.py::test_bytes_total_treats_dash_as_zero", "test_outputs.py::test_gzip_roundtrip_is_byte_identical", "test_outputs.py::test_malformed_line_numbers", "test_outputs.py::test_p95_uses_nearest_rank", "test_outputs.py::test_report_has_exactly_the_documented_keys", "test_outputs.py::test_script_regenerates_identical_output", "test_outputs.py::test_status_counts", "test_outputs.py::test_top_paths_order_and_tiebreak", "test_outputs.py::test_total_requests_counts_only_valid_lines", "test_outputs.py::test_unique_paths_ignores_query_strings"]}}
{"task_id": "tbdl-git-recovery", "instruction": "# Recover a broken release repository\n\nThe git repository in the workspace was left in a mess after a bad afternoon.\n`main` currently has five commits, but the module `src/app.py` was deleted by the\n`Drop legacy module` commit and nobody kept a copy. An experiment that was never\nmerged lives on as an unreachable commit whose message is `wip: plan`.\n\nFix the repository. When you are done it must satisfy all of the following.\n\n## 1. Restore the module\n\n`src/app.py` must exist again with **exactly** the content it had in the commit\ntitled `Add config loader` (not the older `Initial import` version), and it must\nbe committed on `main` in a commit whose message is exactly:\n\n```\nrestore app.py\n```\n\n## 2. Rescue the abandoned experiment\n\nCreate a branch named `recovered` that points at the unreachable commit whose\nmessage is `wip: plan`. That commit must **not** become an ancestor of `main`,\nand it must still carry the work-in-progress version of `notes/plan.md`.\n\n## 3. Tag the release\n\nCreate an annotated-or-lightweight tag `v1.0` pointing at the commit titled\n`Add config loader`.\n\n## 4. Ignore the junk, don't delete it\n\nThe workspace has two untracked artefacts, `debug.log` and `build/tmp.o`. Add a\n`.gitignore` so that both are ignored, commit it, and leave the files on disk.\n\n## 5. Clean tree\n\n`git status --porcelain` must print nothing.\n\n## Constraints\n\n- Do not rewrite or discard the five existing commits on `main`; all five\n  original commit subjects must still be present in `git log main`. In\n  particular do not `reset` `main` backwards.\n- Do not delete `debug.log` or `build/tmp.o`.\n- No network access; everything you need is already in `.git`.\n", "author_name": "WorkBuddy Benchmarks", "author_email": "benchmarks@example.invalid", "difficulty": "hard", "category": "software-engineering", "tags": ["git", "forensics", "history-recovery"], "parser_name": "pytest", "max_agent_timeout_sec": 600.0, "max_test_timeout_sec": 120.0, "expert_time_estimate_min": 20, "junior_time_estimate_min": 75, "task_yaml": "# Terminal-Bench task definition\ninstruction: |\n  # Recover a broken release repository\n\n  The git repository in the workspace was left in a mess after a bad afternoon.\n  `main` currently has five commits, but the module `src/app.py` was deleted by the\n  `Drop legacy module` commit and nobody kept a copy. An experiment that was never\n  merged lives on as an unreachable commit whose message is `wip: plan`.\n\n  Fix the repository. When you are done it must satisfy all of the following.\n\n  ## 1. Restore the module\n\n  `src/app.py` must exist again with **exactly** the content it had in the commit\n  titled `Add config loader` (not the older `Initial import` version), and it must\n  be committed on `main` in a commit whose message is exactly:\n\n  ```\n  restore app.py\n  ```\n\n  ## 2. Rescue the abandoned experiment\n\n  Create a branch named `recovered` that points at the unreachable commit whose\n  message is `wip: plan`. That commit must **not** become an ancestor of `main`,\n  and it must still carry the work-in-progress version of `notes/plan.md`.\n\n  ## 3. Tag the release\n\n  Create an annotated-or-lightweight tag `v1.0` pointing at the commit titled\n  `Add config loader`.\n\n  ## 4. Ignore the junk, don't delete it\n\n  The workspace has two untracked artefacts, `debug.log` and `build/tmp.o`. Add a\n  `.gitignore` so that both are ignored, commit it, and leave the files on disk.\n\n  ## 5. Clean tree\n\n  `git status --porcelain` must print nothing.\n\n  ## Constraints\n\n  - Do not rewrite or discard the five existing commits on `main`; all five\n    original commit subjects must still be present in `git log main`. In\n    particular do not `reset` `main` backwards.\n  - Do not delete `debug.log` or `build/tmp.o`.\n  - No network access; everything you need is already in `.git`.\nauthor_name: WorkBuddy Benchmarks\nauthor_email: benchmarks@example.invalid\ndifficulty: hard\ncategory: software-engineering\ntags:\n  - git\n  - forensics\n  - history-recovery\nparser_name: pytest\nmax_agent_timeout_sec: 600.0\nmax_test_timeout_sec: 120.0\nexpert_time_estimate_min: 20\njunior_time_estimate_min: 75\n", "task_toml": "schema_version = \"1.4\"\nsource = \"TerminalBench-DockerLess\"\n\n[task]\nname = \"swedl/git-recovery\"\nauthors = [{ name = \"WorkBuddy Benchmarks\", email = \"benchmarks@example.invalid\" }]\ndescription = \"Restore a deleted module from history, resurrect an unreachable commit, tag a release and leave a clean tree.\"\nkeywords = [\"git\", \"forensics\", \"history-recovery\"]\n\n[metadata]\ndifficulty = \"hard\"\ncategory = \"software-engineering\"\ntags = [\"git\", \"forensics\", \"history-recovery\"]\nexpert_time_estimate_min = 20\njunior_time_estimate_min = 75\n\n[verifier]\ntimeout_sec = 120.0\n\n[agent]\ntimeout_sec = 600.0\n\n[environment]\nnetwork_mode = \"no-network\"\nos = \"linux\"\nworkdir = \"/workspace\"\n", "dockerfile": "FROM python:3.13-slim\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n        bash coreutils git \\\n    && rm -rf /var/lib/apt/lists/*\n\nWORKDIR /workspace\nCOPY setup.sh /tmp/setup.sh\nRUN bash /tmp/setup.sh\n\nCMD [\"/bin/bash\"]\n", "solution": "#!/usr/bin/env bash\n# Oracle solution: find the lost commit through fsck, recover the file from the\n# right historical revision, tag, ignore and commit.\nset -euo pipefail\ncd \"$TB_WORK\"\n\ngit config user.name \"Release Bot\"\ngit config user.email \"release@example.invalid\"\n\n# 1. restore src/app.py from \"Add config loader\"\nloader_commit=\"$(git log --format='%H %s' main | awk '$0 ~ / Add config loader$/ {print $1}' | head -1)\"\ntest -n \"$loader_commit\"\nmkdir -p src\ngit show \"$loader_commit:src/app.py\" > src/app.py\n\n# 4. ignore the junk\ncat > .gitignore <<'EOF'\n*.log\nbuild/\nEOF\n\ngit add -A\ngit commit -qm \"restore app.py\"\n\n# 2. rescue the unreachable commit\nwip_commit=\"$(git fsck --unreachable --no-reflogs 2>/dev/null | awk '$2 == \"commit\" {print $3}' | while read -r sha; do\n    if [ \"$(git log -1 --format=%s \"$sha\" 2>/dev/null)\" = \"wip: plan\" ]; then\n        echo \"$sha\"\n        break\n    fi\ndone)\"\ntest -n \"$wip_commit\"\ngit branch recovered \"$wip_commit\"\n\n# 3. tag the release commit\ngit tag v1.0 \"$loader_commit\"\n\ngit status --porcelain\n", "tests": {"test.sh": "#!/usr/bin/env bash\n# Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the\n# reward signal (0 = solved).\nset -uo pipefail\ncd \"$TB_ROOT/tests\"\npython -m pytest -v --tb=short -p no:cacheprovider test_outputs.py\n", "test_outputs.py": "import os\nimport subprocess\nfrom pathlib import Path\n\nWORK = Path(os.environ[\"TB_WORK\"])\n\nEXPECTED_APP = '''VERSION = 2\n\nDEFAULTS = {\"retries\": 3, \"timeout\": 30}\n\n\ndef main():\n    return \"v2\"\n\n\ndef load(path):\n    with open(path, \"r\", encoding=\"utf-8\") as handle:\n        return handle.read()\n'''\n\nORIGINAL_SUBJECTS = [\n    \"Initial import\",\n    \"Add plan notes\",\n    \"Add config loader\",\n    \"Drop legacy module\",\n    \"Document build\",\n]\n\n\ndef git(*args):\n    return subprocess.run(\n        [\"git\"] + list(args),\n        cwd=str(WORK),\n        capture_output=True,\n        text=True,\n        encoding=\"utf-8\",\n    )\n\n\ndef subjects():\n    result = git(\"log\", \"--format=%s\", \"main\")\n    assert result.returncode == 0, result.stderr\n    return [line for line in result.stdout.splitlines() if line]\n\n\ndef test_app_py_restored_from_config_loader_commit():\n    path = WORK / \"src\" / \"app.py\"\n    assert path.is_file(), \"src/app.py was not restored\"\n    assert path.read_text(encoding=\"utf-8\") == EXPECTED_APP\n\n\ndef test_restore_commit_message():\n    assert \"restore app.py\" in subjects()\n\n\ndef test_app_py_is_committed_not_just_written():\n    result = git(\"ls-files\", \"--error-unmatch\", \"src/app.py\")\n    assert result.returncode == 0, \"src/app.py is not tracked\"\n\n\ndef test_recovered_branch_points_at_the_wip_commit():\n    ref = git(\"rev-parse\", \"--verify\", \"refs/heads/recovered\")\n    assert ref.returncode == 0, \"branch 'recovered' does not exist\"\n    message = git(\"log\", \"-1\", \"--format=%s\", \"recovered\")\n    assert message.stdout.strip() == \"wip: plan\"\n\n\ndef test_recovered_is_not_an_ancestor_of_main():\n    ref = git(\"rev-parse\", \"--verify\", \"refs/heads/recovered\")\n    assert ref.returncode == 0, \"branch 'recovered' does not exist\"\n    result = git(\"merge-base\", \"--is-ancestor\", \"recovered\", \"main\")\n    assert result.returncode == 1, \"the rescued commit must stay off main\"\n\n\ndef test_recovered_commit_keeps_the_work_in_progress_plan():\n    blob = git(\"show\", \"recovered:notes/plan.md\")\n    assert blob.returncode == 0, \"recovered commit has no notes/plan.md\"\n    assert \"step two\" in blob.stdout\n\n\ndef test_tag_v1_points_at_the_config_loader_commit():\n    tag = git(\"rev-list\", \"-n\", \"1\", \"v1.0\")\n    assert tag.returncode == 0, \"tag v1.0 does not exist\"\n    subject = git(\"log\", \"-1\", \"--format=%s\", tag.stdout.strip())\n    assert subject.stdout.strip() == \"Add config loader\"\n\n\ndef test_junk_is_ignored_but_still_present():\n    for rel in (\"debug.log\", \"build/tmp.o\"):\n        assert (WORK / rel).is_file(), \"%s was deleted\" % rel\n        result = git(\"check-ignore\", \"-q\", rel)\n        assert result.returncode == 0, \"%s is not ignored\" % rel\n\n\ndef test_worktree_is_clean():\n    status = git(\"status\", \"--porcelain\")\n    assert status.stdout.strip() == \"\", \"dirty tree:\\n%s\" % status.stdout\n\n\ndef test_original_history_is_preserved():\n    current = subjects()\n    for subject in ORIGINAL_SUBJECTS:\n        assert subject in current, \"commit %r disappeared from main\" % subject\n"}, "dockerless": {"setup": "#!/usr/bin/env bash\n# Builds the broken repository state. This is the Dockerfile's analogue: it\n# constructs the environment the agent wakes up in, deterministically.\nset -euo pipefail\ncd \"$TB_WORK\"\n\ngit init -q -b main\ngit config user.name \"Release Bot\"\ngit config user.email \"release@example.invalid\"\ngit config commit.gpgsign false\ngit config core.autocrlf false\n\nmkdir -p src\ncat > src/app.py <<'EOF'\nVERSION = 1\n\n\ndef main():\n    return \"v1\"\nEOF\ngit add -A\ngit commit -qm \"Initial import\"\n\nmkdir -p notes\ncat > notes/plan.md <<'EOF'\n# Plan\n\n- step one: wire up the loader\nEOF\ngit add -A\ngit commit -qm \"Add plan notes\"\n\ncat > src/app.py <<'EOF'\nVERSION = 2\n\nDEFAULTS = {\"retries\": 3, \"timeout\": 30}\n\n\ndef main():\n    return \"v2\"\n\n\ndef load(path):\n    with open(path, \"r\", encoding=\"utf-8\") as handle:\n        return handle.read()\nEOF\ngit add -A\ngit commit -qm \"Add config loader\"\n\ngit rm -q src/app.py\ngit commit -qm \"Drop legacy module\"\n\nmkdir -p docs\ncat > docs/build.md <<'EOF'\n# Build\n\nRun `make build`.\nEOF\ngit add -A\ngit commit -qm \"Document build\"\n\n# An abandoned experiment: a commit on a branch that is then deleted, leaving\n# the commit unreachable from every ref.\ngit checkout -q -b wip HEAD~2\ncat > notes/plan.md <<'EOF'\n# Plan\n\n- step one: wire up the loader\n- step two: add retry budget (work in progress)\nEOF\ngit add -A\ngit commit -qm \"wip: plan\"\ngit checkout -q main\ngit branch -qD wip\n\n# Untracked junk that must end up ignored, not deleted.\nprintf 'starting\\n' > debug.log\nmkdir -p build\nprintf 'object file\\n' > build/tmp.o\n", "setup_timeout_sec": 120, "files": {}, "test_cmd": "", "workdir": "workspace", "requires": ["bash", "git"], "baseline_failures": ["test_outputs.py::test_app_py_is_committed_not_just_written", "test_outputs.py::test_app_py_restored_from_config_loader_commit", "test_outputs.py::test_junk_is_ignored_but_still_present", "test_outputs.py::test_recovered_branch_points_at_the_wip_commit", "test_outputs.py::test_recovered_commit_keeps_the_work_in_progress_plan", "test_outputs.py::test_recovered_is_not_an_ancestor_of_main", "test_outputs.py::test_restore_commit_message", "test_outputs.py::test_tag_v1_points_at_the_config_loader_commit", "test_outputs.py::test_worktree_is_clean"]}}
{"task_id": "tbdl-csv-canon", "instruction": "# `canon` — canonicalise a CSV export\n\nDownstream tools need one boring, byte-stable TSV. Write an executable script at\n`bin/canon` (shebang, `chmod +x`) that is invoked as:\n\n```\n./bin/canon <input.csv> <output.tsv>\n```\n\n## Input\n\nUTF-8 CSV, possibly with a byte-order mark, possibly CRLF, RFC 4180 quoting:\nfields may be quoted, may contain commas, doubled quotes (`\"\"`) and embedded\nnewlines. The first record is the header.\n\n## Output\n\nUTF-8 **without** a BOM, `\\n` line endings, tab-separated, one line per record,\nheader first. Fields are written verbatim — never re-quoted, never trimmed —\nexcept for the numeric normalisation below. Column order is preserved.\n\n## Numeric normalisation\n\nA field is numeric when the whole field matches\n`^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$`. Numeric fields are rewritten in\nplain decimal notation with no exponent, no leading `+`, no leading zeros, and\nno trailing zeros after the decimal point:\n\n| input | output |\n| --- | --- |\n| `1.50` | `1.5` |\n| `1.0` | `1` |\n| `1e3` | `1000` |\n| `2.5e-3` | `0.0025` |\n| `+5` | `5` |\n| `007` | `7` |\n| `-0` | `0` |\n\nEvery other field is copied unchanged.\n\n## Ordering\n\nSort the data records by field 0, then by field 1, comparing the **normalised\nstrings** in byte order (so `\"10\"` sorts before `\"9\"`). The sort must be stable.\n\n## Errors\n\nOn any error, print exactly one line to stderr, exit with the given code, and do\n**not** create the output file:\n\n| condition | stderr line | exit |\n| --- | --- | --- |\n| input path does not exist | `no such file: <input path as given>` | `2` |\n| two header names collide case-insensitively after trimming | `duplicate column: <name as written in the later header field>` | `3` |\n| a record's field count differs from the header's | `malformed row: line <n>` | `4` |\n\n`<n>` is the 1-based physical line number where the offending record starts\n(so a record whose first line is the third line of the file reports `3`).\n\nOn success exit `0` and print nothing to stderr.\n\n## Notes\n\n- `python` and `python3` are both on `PATH`; standard library only, no network.\n- `data/orders.csv` is a sample with a BOM and CRLF endings.\n", "author_name": "WorkBuddy Benchmarks", "author_email": "benchmarks@example.invalid", "difficulty": "hard", "category": "data-processing", "tags": ["csv", "cli", "spec-compliance", "exit-codes"], "parser_name": "pytest", "max_agent_timeout_sec": 900.0, "max_test_timeout_sec": 120.0, "expert_time_estimate_min": 35, "junior_time_estimate_min": 120, "task_yaml": "# Terminal-Bench task definition\ninstruction: |\n  # `canon` — canonicalise a CSV export\n\n  Downstream tools need one boring, byte-stable TSV. Write an executable script at\n  `bin/canon` (shebang, `chmod +x`) that is invoked as:\n\n  ```\n  ./bin/canon <input.csv> <output.tsv>\n  ```\n\n  ## Input\n\n  UTF-8 CSV, possibly with a byte-order mark, possibly CRLF, RFC 4180 quoting:\n  fields may be quoted, may contain commas, doubled quotes (`\"\"`) and embedded\n  newlines. The first record is the header.\n\n  ## Output\n\n  UTF-8 **without** a BOM, `\\n` line endings, tab-separated, one line per record,\n  header first. Fields are written verbatim — never re-quoted, never trimmed —\n  except for the numeric normalisation below. Column order is preserved.\n\n  ## Numeric normalisation\n\n  A field is numeric when the whole field matches\n  `^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$`. Numeric fields are rewritten in\n  plain decimal notation with no exponent, no leading `+`, no leading zeros, and\n  no trailing zeros after the decimal point:\n\n  | input | output |\n  | --- | --- |\n  | `1.50` | `1.5` |\n  | `1.0` | `1` |\n  | `1e3` | `1000` |\n  | `2.5e-3` | `0.0025` |\n  | `+5` | `5` |\n  | `007` | `7` |\n  | `-0` | `0` |\n\n  Every other field is copied unchanged.\n\n  ## Ordering\n\n  Sort the data records by field 0, then by field 1, comparing the **normalised\n  strings** in byte order (so `\"10\"` sorts before `\"9\"`). The sort must be stable.\n\n  ## Errors\n\n  On any error, print exactly one line to stderr, exit with the given code, and do\n  **not** create the output file:\n\n  | condition | stderr line | exit |\n  | --- | --- | --- |\n  | input path does not exist | `no such file: <input path as given>` | `2` |\n  | two header names collide case-insensitively after trimming | `duplicate column: <name as written in the later header field>` | `3` |\n  | a record's field count differs from the header's | `malformed row: line <n>` | `4` |\n\n  `<n>` is the 1-based physical line number where the offending record starts\n  (so a record whose first line is the third line of the file reports `3`).\n\n  On success exit `0` and print nothing to stderr.\n\n  ## Notes\n\n  - `python` and `python3` are both on `PATH`; standard library only, no network.\n  - `data/orders.csv` is a sample with a BOM and CRLF endings.\nauthor_name: WorkBuddy Benchmarks\nauthor_email: benchmarks@example.invalid\ndifficulty: hard\ncategory: data-processing\ntags:\n  - csv\n  - cli\n  - spec-compliance\n  - exit-codes\nparser_name: pytest\nmax_agent_timeout_sec: 900.0\nmax_test_timeout_sec: 120.0\nexpert_time_estimate_min: 35\njunior_time_estimate_min: 120\n", "task_toml": "schema_version = \"1.4\"\nsource = \"TerminalBench-DockerLess\"\n\n[task]\nname = \"swedl/csv-canon\"\nauthors = [{ name = \"WorkBuddy Benchmarks\", email = \"benchmarks@example.invalid\" }]\ndescription = \"Write a byte-exact CSV-to-TSV canonicaliser with strict error codes and numeric normalisation.\"\nkeywords = [\"csv\", \"cli\", \"spec-compliance\", \"exit-codes\"]\n\n[metadata]\ndifficulty = \"hard\"\ncategory = \"data-processing\"\ntags = [\"csv\", \"cli\", \"spec-compliance\", \"exit-codes\"]\nexpert_time_estimate_min = 35\njunior_time_estimate_min = 120\n\n[verifier]\ntimeout_sec = 120.0\n\n[agent]\ntimeout_sec = 900.0\n\n[environment]\nnetwork_mode = \"no-network\"\nos = \"linux\"\nworkdir = \"/workspace\"\n", "dockerfile": "FROM python:3.13-slim\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n        bash coreutils \\\n    && rm -rf /var/lib/apt/lists/*\n\nWORKDIR /workspace\nCOPY data/ /workspace/data/\n\nCMD [\"/bin/bash\"]\n", "solution": "#!/usr/bin/env bash\n# Oracle solution: csv module for RFC4180, Decimal for exact numeric rewriting.\nset -euo pipefail\ncd \"$TB_WORK\"\nmkdir -p bin\n\ncat > bin/canon <<'PYEOF'\n#!/usr/bin/env python3\nimport csv\nimport re\nimport sys\nfrom decimal import Decimal, InvalidOperation\nfrom pathlib import Path\n\nNUMERIC = re.compile(r\"^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$\")\n\n\ndef normalize(cell):\n    if not NUMERIC.match(cell):\n        return cell\n    try:\n        value = Decimal(cell)\n    except InvalidOperation:\n        return cell\n    if value == 0:\n        return \"0\"\n    return format(value.normalize(), \"f\")\n\n\ndef main(argv):\n    if len(argv) != 3:\n        sys.stderr.write(\"usage: canon <input.csv> <output.tsv>\\n\")\n        return 1\n    source = Path(argv[1])\n    target = Path(argv[2])\n    if not source.is_file():\n        sys.stderr.write(\"no such file: %s\\n\" % argv[1])\n        return 2\n\n    with open(source, \"r\", encoding=\"utf-8-sig\", newline=\"\") as handle:\n        reader = csv.reader(handle)\n        header = next(reader, None)\n        if header is None:\n            header = []\n        header = [name.strip() for name in header]\n\n        seen = set()\n        for name in header:\n            key = name.casefold()\n            if key in seen:\n                sys.stderr.write(\"duplicate column: %s\\n\" % name)\n                return 3\n            seen.add(key)\n\n        rows = []\n        previous_line = reader.line_num\n        for record in reader:\n            start = previous_line + 1\n            previous_line = reader.line_num\n            if not record:\n                continue\n            if len(record) != len(header):\n                sys.stderr.write(\"malformed row: line %d\\n\" % start)\n                return 4\n            rows.append([normalize(cell) for cell in record])\n\n    rows.sort(key=lambda row: (row[0], row[1] if len(row) > 1 else \"\"))\n\n    target.parent.mkdir(parents=True, exist_ok=True)\n    with open(target, \"w\", encoding=\"utf-8\", newline=\"\") as handle:\n        handle.write(\"\\t\".join(header) + \"\\n\")\n        for row in rows:\n            handle.write(\"\\t\".join(row) + \"\\n\")\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main(sys.argv))\nPYEOF\n\nchmod +x bin/canon\n./bin/canon data/orders.csv out/orders.tsv\n", "tests": {"test.sh": "#!/usr/bin/env bash\n# Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the\n# reward signal (0 = solved).\nset -uo pipefail\ncd \"$TB_ROOT/tests\"\npython -m pytest -v --tb=short -p no:cacheprovider test_outputs.py\n", "test_outputs.py": "import os\nimport subprocess\nfrom pathlib import Path\n\nWORK = Path(os.environ[\"TB_WORK\"])\nBASH = os.environ.get(\"TB_BASH\", \"bash\")\nCANON = \"./bin/canon\"\n\n\ndef run_canon(source, target):\n    return subprocess.run(\n        [BASH, \"-c\", 'exec ./bin/canon \"$@\"', \"canon\", str(source), str(target)],\n        cwd=str(WORK),\n        capture_output=True,\n        text=True,\n        encoding=\"utf-8\",\n    )\n\n\ndef case_dir():\n    path = Path(os.environ[\"TB_ROOT\"]) / \"tmp\" / \"cases\"\n    path.mkdir(parents=True, exist_ok=True)\n    return path\n\n\ndef write_case(name, body, newline=\"\"):\n    path = case_dir() / name\n    with open(path, \"w\", encoding=\"utf-8\", newline=newline) as handle:\n        handle.write(body)\n    return path\n\n\ndef test_missing_input_exits_2():\n    target = case_dir() / \"missing.tsv\"\n    if target.exists():\n        target.unlink()\n    proc = run_canon(\"does-not-exist.csv\", target)\n    assert proc.returncode == 2, proc.stderr\n    assert proc.stderr.strip() == \"no such file: does-not-exist.csv\"\n    assert not target.exists(), \"output must not be created on error\"\n\n\ndef test_duplicate_column_exits_3():\n    source = write_case(\"dup.csv\", \"id,ID\\n1,2\\n\")\n    target = case_dir() / \"dup.tsv\"\n    if target.exists():\n        target.unlink()\n    proc = run_canon(source, target)\n    assert proc.returncode == 3, proc.stderr\n    assert proc.stderr.strip() == \"duplicate column: ID\"\n    assert not target.exists()\n\n\ndef test_malformed_row_exits_4_with_physical_line():\n    source = write_case(\"bad.csv\", \"id,sku\\n1,a\\n2,b,c\\n\")\n    target = case_dir() / \"bad.tsv\"\n    if target.exists():\n        target.unlink()\n    proc = run_canon(source, target)\n    assert proc.returncode == 4, proc.stderr\n    assert proc.stderr.strip() == \"malformed row: line 3\"\n    assert not target.exists()\n\n\ndef test_orders_sample_is_canonicalised():\n    target = case_dir() / \"orders.tsv\"\n    proc = run_canon(\"data/orders.csv\", target)\n    assert proc.returncode == 0, proc.stderr\n    expected = (\n        \"id\\tsku\\tqty\\tprice\\n\"\n        \"1\\tSKU-1\\t5\\t0.75\\n\"\n        \"1\\tSKU-2\\t10\\t2\\n\"\n        \"2\\tSKU-1\\t5\\t1000\\n\"\n        \"3\\tSKU-9\\t2\\t1.5\\n\"\n    )\n    assert target.read_bytes() == expected.encode(\"utf-8\")\n\n\ndef test_output_has_no_bom_and_uses_lf():\n    target = case_dir() / \"orders.tsv\"\n    run_canon(\"data/orders.csv\", target)\n    raw = target.read_bytes()\n    assert not raw.startswith(b\"\\xef\\xbb\\xbf\")\n    assert b\"\\r\" not in raw\n\n\ndef test_embedded_newline_survives():\n    source = write_case(\"multi.csv\", 'id,note\\n2,\"line one\\nline two\"\\n1,plain\\n')\n    target = case_dir() / \"multi.tsv\"\n    proc = run_canon(source, target)\n    assert proc.returncode == 0, proc.stderr\n    expected = \"id\\tnote\\n1\\tplain\\n2\\tline one\\nline two\\n\"\n    assert target.read_bytes() == expected.encode(\"utf-8\")\n\n\ndef test_numeric_normalisation():\n    source = write_case(\n        \"nums.csv\", \"id,v\\n1,+5\\n2,007\\n3,-0\\n4,1.0\\n5,2.5e-3\\n6,abc\\n\"\n    )\n    target = case_dir() / \"nums.tsv\"\n    proc = run_canon(source, target)\n    assert proc.returncode == 0, proc.stderr\n    expected = \"id\\tv\\n1\\t5\\n2\\t7\\n3\\t0\\n4\\t1\\n5\\t0.0025\\n6\\tabc\\n\"\n    assert target.read_bytes() == expected.encode(\"utf-8\")\n\n\ndef test_sorting_is_byte_order_not_numeric():\n    source = write_case(\"ids.csv\", \"id,x\\n10,a\\n9,b\\n\")\n    target = case_dir() / \"ids.tsv\"\n    proc = run_canon(source, target)\n    assert proc.returncode == 0, proc.stderr\n    assert target.read_bytes() == b\"id\\tx\\n10\\ta\\n9\\tb\\n\"\n"}, "dockerless": {"setup": "", "setup_timeout_sec": 120, "files": {"data/orders.csv": "id,sku,qty,price\r\n3,SKU-9,2,1.50\r\n1,SKU-2,10,2\r\n2,SKU-1,5,1e3\r\n1,SKU-1,5,0.75\r\n"}, "test_cmd": "", "workdir": "workspace", "requires": ["bash", "python"], "baseline_failures": ["test_outputs.py::test_duplicate_column_exits_3", "test_outputs.py::test_embedded_newline_survives", "test_outputs.py::test_malformed_row_exits_4_with_physical_line", "test_outputs.py::test_missing_input_exits_2", "test_outputs.py::test_numeric_normalisation", "test_outputs.py::test_orders_sample_is_canonicalised", "test_outputs.py::test_output_has_no_bom_and_uses_lf", "test_outputs.py::test_sorting_is_byte_order_not_numeric"]}}
{"task_id": "tbdl-build-repair", "instruction": "# Make the report build work again\n\n`build.sh` is supposed to regenerate `dist/report.txt` and then run the project's\nown test suite. Right now it does neither:\n\n```\n$ bash build.sh\nbuild.sh: line 5: OUTDIR: unbound variable\n```\n\nNothing in the repository is sacred except the inputs and the tests. Fix the\nbuild so that `bash build.sh`, run from the workspace root, exits `0` and\nproduces:\n\n- `dist/report.txt`\n- `build/gen.log`\n\nBoth files must contain the same text: one `name=score` line per record from\n`data/input.txt`, in input order, followed by a single `mean=<value>` line where\nthe value is the arithmetic mean of the scores printed with exactly two decimal\nplaces.\n\nFor the shipped `data/input.txt` the expected content is:\n\n```\nalpha=10\nbeta=20\ngamma=31\ndelta=40\nepsilon=55\nmean=31.20\n```\n\n## Constraints\n\n- `data/input.txt` must not change.\n- The tests in `tests/` must not change; they must pass as written. They are run\n  by `build.sh` itself, so a build that \"succeeds\" while skipping them is not a\n  fix.\n- `dist/` and `build/` are build outputs; they may be recreated freely.\n- Only the Python standard library is available, and there is no network.\n\n## Notes\n\n- `bash build.sh` must be safe to run repeatedly.\n- Do not silence failures with `|| true`; the build has to fail loudly when a\n  step really fails.\n", "author_name": "WorkBuddy Benchmarks", "author_email": "benchmarks@example.invalid", "difficulty": "hard", "category": "software-engineering", "tags": ["build", "shell", "debugging"], "parser_name": "pytest", "max_agent_timeout_sec": 600.0, "max_test_timeout_sec": 120.0, "expert_time_estimate_min": 25, "junior_time_estimate_min": 90, "task_yaml": "# Terminal-Bench task definition\ninstruction: |\n  # Make the report build work again\n\n  `build.sh` is supposed to regenerate `dist/report.txt` and then run the project's\n  own test suite. Right now it does neither:\n\n  ```\n  $ bash build.sh\n  build.sh: line 5: OUTDIR: unbound variable\n  ```\n\n  Nothing in the repository is sacred except the inputs and the tests. Fix the\n  build so that `bash build.sh`, run from the workspace root, exits `0` and\n  produces:\n\n  - `dist/report.txt`\n  - `build/gen.log`\n\n  Both files must contain the same text: one `name=score` line per record from\n  `data/input.txt`, in input order, followed by a single `mean=<value>` line where\n  the value is the arithmetic mean of the scores printed with exactly two decimal\n  places.\n\n  For the shipped `data/input.txt` the expected content is:\n\n  ```\n  alpha=10\n  beta=20\n  gamma=31\n  delta=40\n  epsilon=55\n  mean=31.20\n  ```\n\n  ## Constraints\n\n  - `data/input.txt` must not change.\n  - The tests in `tests/` must not change; they must pass as written. They are run\n    by `build.sh` itself, so a build that \"succeeds\" while skipping them is not a\n    fix.\n  - `dist/` and `build/` are build outputs; they may be recreated freely.\n  - Only the Python standard library is available, and there is no network.\n\n  ## Notes\n\n  - `bash build.sh` must be safe to run repeatedly.\n  - Do not silence failures with `|| true`; the build has to fail loudly when a\n    step really fails.\nauthor_name: WorkBuddy Benchmarks\nauthor_email: benchmarks@example.invalid\ndifficulty: hard\ncategory: software-engineering\ntags:\n  - build\n  - shell\n  - debugging\nparser_name: pytest\nmax_agent_timeout_sec: 600.0\nmax_test_timeout_sec: 120.0\nexpert_time_estimate_min: 25\njunior_time_estimate_min: 90\n", "task_toml": "schema_version = \"1.4\"\nsource = \"TerminalBench-DockerLess\"\n\n[task]\nname = \"swedl/build-repair\"\nauthors = [{ name = \"WorkBuddy Benchmarks\", email = \"benchmarks@example.invalid\" }]\ndescription = \"Repair a shell build with three independent faults so it produces the expected report and passes its own suite.\"\nkeywords = [\"build\", \"shell\", \"debugging\"]\n\n[metadata]\ndifficulty = \"hard\"\ncategory = \"software-engineering\"\ntags = [\"build\", \"shell\", \"debugging\"]\nexpert_time_estimate_min = 25\njunior_time_estimate_min = 90\n\n[verifier]\ntimeout_sec = 120.0\n\n[agent]\ntimeout_sec = 600.0\n\n[environment]\nnetwork_mode = \"no-network\"\nos = \"linux\"\nworkdir = \"/workspace\"\n", "dockerfile": "FROM python:3.13-slim\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n        bash coreutils \\\n    && rm -rf /var/lib/apt/lists/*\n\nWORKDIR /workspace\nCOPY . /workspace/\n\nCMD [\"/bin/bash\"]\n", "solution": "#!/usr/bin/env bash\n# Oracle solution: three independent repairs -- the shell variable typo and the\n# missing output directory, the dropped final record, and the truncated mean.\nset -euo pipefail\ncd \"$TB_WORK\"\n\ncat > build.sh <<'SHEOF'\n#!/usr/bin/env bash\nset -euo pipefail\n\nOUT=dist\nmkdir -p \"$OUT\" build\n\npython src/gen.py data/input.txt | tee build/gen.log > \"$OUT/report.txt\"\n\npython -m pytest tests -q\nSHEOF\n\npython - <<'PYEOF'\nfrom pathlib import Path\n\ngen = Path(\"src/gen.py\")\ntext = gen.read_text(encoding=\"utf-8\")\ntext = text.replace(\"for line in lines[:-1]:\", \"for line in lines:\")\ngen.write_text(text, encoding=\"utf-8\", newline=\"\\n\")\n\nstats = Path(\"src/lib/stats.py\")\ntext = stats.read_text(encoding=\"utf-8\")\ntext = text.replace(\"return total // len(values)\", \"return total / len(values)\")\nstats.write_text(text, encoding=\"utf-8\", newline=\"\\n\")\nPYEOF\n\nbash build.sh\n", "tests": {"test.sh": "#!/usr/bin/env bash\n# Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the\n# reward signal (0 = solved).\nset -uo pipefail\ncd \"$TB_ROOT/tests\"\npython -m pytest -v --tb=short -p no:cacheprovider test_outputs.py\n", "test_outputs.py": "import os\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\n\nWORK = Path(os.environ[\"TB_WORK\"])\nBASH = os.environ.get(\"TB_BASH\", \"bash\")\n\nEXPECTED_REPORT = (\n    \"alpha=10\\n\"\n    \"beta=20\\n\"\n    \"gamma=31\\n\"\n    \"delta=40\\n\"\n    \"epsilon=55\\n\"\n    \"mean=31.20\\n\"\n)\n\n\n@pytest.fixture(scope=\"module\")\ndef build():\n    for path in (WORK / \"dist\", WORK / \"build\"):\n        if path.exists():\n            for child in path.rglob(\"*\"):\n                if child.is_file():\n                    child.unlink()\n    return subprocess.run(\n        [BASH, \"build.sh\"],\n        cwd=str(WORK),\n        capture_output=True,\n        text=True,\n        encoding=\"utf-8\",\n    )\n\n\ndef test_build_exits_zero(build):\n    assert build.returncode == 0, \"build.sh failed:\\n%s\\n%s\" % (build.stdout, build.stderr)\n\n\ndef test_report_content(build):\n    path = WORK / \"dist\" / \"report.txt\"\n    assert path.is_file(), \"dist/report.txt was not produced\"\n    assert path.read_text(encoding=\"utf-8\") == EXPECTED_REPORT\n\n\ndef test_build_log_matches_report(build):\n    log = WORK / \"build\" / \"gen.log\"\n    report = WORK / \"dist\" / \"report.txt\"\n    assert log.is_file(), \"build/gen.log was not produced\"\n    assert log.read_text(encoding=\"utf-8\") == report.read_text(encoding=\"utf-8\")\n\n\ndef test_project_suite_passes(build):\n    proc = subprocess.run(\n        [\"python\", \"-m\", \"pytest\", \"tests\", \"-q\", \"-p\", \"no:cacheprovider\"],\n        cwd=str(WORK),\n        capture_output=True,\n        text=True,\n        encoding=\"utf-8\",\n    )\n    assert proc.returncode == 0, \"project tests failed:\\n%s\\n%s\" % (proc.stdout, proc.stderr)\n"}, "dockerless": {"setup": "", "setup_timeout_sec": 120, "files": {"build.sh": "#!/usr/bin/env bash\nset -euo pipefail\n\nOUT=dist\nmkdir -p \"$OUTDIR\"\n\npython src/gen.py data/input.txt | tee build/gen.log > \"$OUT/report.txt\"\n\npython -m pytest tests -q\n", "data/input.txt": "alpha,10\nbeta,20\ngamma,31\ndelta,40\nepsilon,55\n", "src/gen.py": "\"\"\"Generate the per-record report on stdout.\"\"\"\n\nimport sys\n\nfrom lib.stats import mean\n\n\ndef main(path):\n    with open(path, \"r\", encoding=\"utf-8\") as handle:\n        lines = [line.strip() for line in handle if line.strip()]\n\n    records = []\n    for line in lines[:-1]:\n        name, _, score = line.partition(\",\")\n        records.append((name, int(score)))\n\n    for name, score in records:\n        print(\"%s=%d\" % (name, score))\n    print(\"mean=%.2f\" % mean([score for _, score in records]))\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1])\n", "src/lib/__init__.py": "", "src/lib/stats.py": "\"\"\"Tiny stats helpers used by the report generator.\"\"\"\n\n\ndef mean(values):\n    \"\"\"Arithmetic mean of a non-empty sequence.\"\"\"\n    total = sum(values)\n    return total // len(values)\n", "tests/test_pipeline.py": "import subprocess\nimport sys\nfrom pathlib import Path\n\nROOT = Path(__file__).resolve().parent.parent\n\n\ndef run_gen():\n    return subprocess.run(\n        [sys.executable, \"src/gen.py\", \"data/input.txt\"],\n        cwd=str(ROOT),\n        capture_output=True,\n        text=True,\n    )\n\n\ndef test_every_record_is_reported_in_input_order():\n    proc = run_gen()\n    assert proc.returncode == 0, proc.stderr\n    assert proc.stdout.strip().splitlines() == [\n        \"alpha=10\",\n        \"beta=20\",\n        \"gamma=31\",\n        \"delta=40\",\n        \"epsilon=55\",\n        \"mean=31.20\",\n    ]\n", "tests/test_stats.py": "import sys\nfrom pathlib import Path\n\nsys.path.insert(0, str(Path(__file__).resolve().parent.parent / \"src\"))\n\nfrom lib.stats import mean\n\n\ndef test_mean_of_even_count_is_fractional():\n    assert abs(mean([1, 2]) - 1.5) < 1e-9\n\n\ndef test_mean_keeps_the_fractional_part():\n    assert abs(mean([10, 20, 31]) - 61 / 3) < 1e-9\n"}, "test_cmd": "", "workdir": "workspace", "requires": ["bash", "python"], "baseline_failures": ["test_outputs.py::test_build_exits_zero", "test_outputs.py::test_build_log_matches_report", "test_outputs.py::test_project_suite_passes", "test_outputs.py::test_report_content"]}}