noodcon mondk commited on
Commit
b199558
·
0 Parent(s):

Duplicate from mondk/TerminalBench-DockerLess

Browse files

Co-authored-by: mon-dark <mondk@users.noreply.huggingface.co>

Files changed (42) hide show
  1. .gitattributes +60 -0
  2. README.md +174 -0
  3. TerminalBench-DockerLess.jsonl +4 -0
  4. build_dataset.py +302 -0
  5. predictions/partial.jsonl +4 -0
  6. reports/baseline.json +85 -0
  7. reports/partial.json +66 -0
  8. reports/solution.json +50 -0
  9. run_harness.py +302 -0
  10. tasks/access-log-report/environment/Dockerfile +10 -0
  11. tasks/access-log-report/environment/logs/access.log +40 -0
  12. tasks/access-log-report/instruction.md +61 -0
  13. tasks/access-log-report/solution/solve.sh +85 -0
  14. tasks/access-log-report/tests/test.sh +6 -0
  15. tasks/access-log-report/tests/test_outputs.py +87 -0
  16. tasks/build-repair/environment/Dockerfile +10 -0
  17. tasks/build-repair/environment/build.sh +9 -0
  18. tasks/build-repair/environment/data/input.txt +5 -0
  19. tasks/build-repair/environment/src/gen.py +23 -0
  20. tasks/build-repair/environment/src/lib/__init__.py +0 -0
  21. tasks/build-repair/environment/src/lib/stats.py +7 -0
  22. tasks/build-repair/environment/tests/test_pipeline.py +27 -0
  23. tasks/build-repair/environment/tests/test_stats.py +14 -0
  24. tasks/build-repair/instruction.md +47 -0
  25. tasks/build-repair/solution/solve.sh +33 -0
  26. tasks/build-repair/tests/test.sh +6 -0
  27. tasks/build-repair/tests/test_outputs.py +61 -0
  28. tasks/csv-canon/environment/Dockerfile +10 -0
  29. tasks/csv-canon/environment/data/orders.csv +5 -0
  30. tasks/csv-canon/instruction.md +65 -0
  31. tasks/csv-canon/solution/solve.sh +82 -0
  32. tasks/csv-canon/tests/test.sh +6 -0
  33. tasks/csv-canon/tests/test_outputs.py +112 -0
  34. tasks/git-recovery/environment/Dockerfile +11 -0
  35. tasks/git-recovery/environment/setup.sh +79 -0
  36. tasks/git-recovery/instruction.md +46 -0
  37. tasks/git-recovery/solution/solve.sh +38 -0
  38. tasks/git-recovery/tests/test.sh +6 -0
  39. tasks/git-recovery/tests/test_outputs.py +103 -0
  40. tools/make_controls.py +98 -0
  41. tools/mk_access_log.py +87 -0
  42. tools/validate.py +130 -0
.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ configs:
6
+ - config_name: tbd
7
+ data_files: TerminalBench-DockerLess.jsonl
8
+ tags:
9
+ - terminal
10
+ - bench
11
+ - dockerless
12
+ ---
13
+ # TerminalBench-DockerLess
14
+
15
+ Terminal-Bench tasks are directories (instruction, environment, solution, tests)
16
+ executed inside a Docker image. This is the same task model with the image
17
+ replaced by a setup script, so a trial needs only `bash`, `git` and `python` —
18
+ no daemon, no network, no build step.
19
+
20
+ Rows carry the classic Terminal-Bench `task.yaml` fields, a rendered
21
+ `task.toml` in the Harbor 1.4 schema, and the whole task directory inline. One
22
+ extra `dockerless` object says how to build the environment without Docker.
23
+
24
+ ```
25
+ TerminalBench-DockerLess.jsonl 4 tasks, 52.5 KiB (~13.4k tokens)
26
+ build_dataset.py flattens tasks/ into rows, then verifies the file
27
+ run_harness.py trial runner: --solution, --baseline, --predictions
28
+ tasks/ the four task directories (source of truth)
29
+ tools/validate.py schema, leakage and non-triviality checks
30
+ tools/make_controls.py builds the partial-credit negative control
31
+ tools/mk_access_log.py regenerates the access.log fixture
32
+ reports/ harness output for solution / baseline / partial
33
+ ```
34
+
35
+ ## Tasks
36
+
37
+ | task_id | difficulty | category | verifier tests | fails before any agent | oracle |
38
+ | --- | --- | --- | --- | --- | --- |
39
+ | `tbdl-access-log-report` | medium | data-processing | 10 | 10 | pass |
40
+ | `tbdl-git-recovery` | hard | software-engineering | 10 | 9 | pass |
41
+ | `tbdl-csv-canon` | hard | data-processing | 8 | 8 | pass |
42
+ | `tbdl-build-repair` | hard | software-engineering | 4 | 4 | pass |
43
+
44
+ Difficulty is kept Terminal-Bench-shaped: each task needs real terminal work
45
+ across several steps and fails if any one part is skipped.
46
+
47
+ - **access-log-report** — a damaged nginx-style log where the user-agent carries
48
+ escaped quotes, so splitting on `"` breaks; produce an exact JSON aggregate,
49
+ a nearest-rank p95, a malformed-line index and a gzip copy, idempotently.
50
+ - **git-recovery** — restore a deleted module from the *right* historical
51
+ revision, resurrect an unreachable commit found via `git fsck`, tag a release
52
+ commit, ignore two untracked artefacts without deleting them, and leave a clean
53
+ tree without rewriting the five original commits.
54
+ - **csv-canon** — write a byte-exact CSV→TSV canonicaliser: BOM, CRLF, RFC 4180
55
+ quoting, embedded newlines, `Decimal` numeric rewriting, byte-order sorting,
56
+ and three distinct exit codes with exact stderr lines.
57
+ - **build-repair** — a build that dies on an unbound shell variable, then on a
58
+ missing output directory, then produces a report missing its last record with a
59
+ truncated mean; all three must be fixed without touching `data/` or `tests/`.
60
+
61
+ ## Row schema
62
+
63
+ | field | notes |
64
+ | --- | --- |
65
+ | `task_id` | `tbdl-<task>` |
66
+ | `instruction` | the full `instruction.md` text |
67
+ | `author_name`, `author_email` | as in `task.yaml` |
68
+ | `difficulty`, `category`, `tags` | `easy` / `medium` / `hard` |
69
+ | `parser_name` | `pytest` |
70
+ | `max_agent_timeout_sec`, `max_test_timeout_sec` | enforced by the harness |
71
+ | `expert_time_estimate_min`, `junior_time_estimate_min` | author estimates |
72
+ | `task_yaml` | the row rendered as a classic Terminal-Bench `task.yaml` |
73
+ | `task_toml` | the row rendered as a Harbor `task.toml` (`schema_version = "1.4"`) |
74
+ | `dockerfile` | the original image spec, kept for fidelity (not executed) |
75
+ | `solution` | `solution/solve.sh`, the oracle |
76
+ | `tests` | `{"test.sh": ..., "test_outputs.py": ...}` |
77
+ | `dockerless.setup` | replaces the Dockerfile: builds the environment |
78
+ | `dockerless.files` | workspace snapshot written before setup runs |
79
+ | `dockerless.test_cmd` | empty = run `tests/test.sh` |
80
+ | `dockerless.baseline_failures` | verifier tests that already fail before any agent acts |
81
+
82
+ ## How the environment is replaced
83
+
84
+ | Terminal-Bench | here |
85
+ | --- | --- |
86
+ | `environment/Dockerfile` + `docker build` | `dockerless.setup` run in a fresh directory |
87
+ | `/workspace` | `$TB_WORK` |
88
+ | `/logs/verifier/reward.txt` | the harness computes reward from the pytest run |
89
+ | `tests/test.sh` | same file, run with `cwd=$TB_WORK` |
90
+
91
+ Each trial gets a throwaway root:
92
+
93
+ ```
94
+ $TB_ROOT/
95
+ workspace/ agent cwd
96
+ home/ HOME
97
+ tmp/ TMPDIR
98
+ bin/ prepended to PATH (contains a python3 shim)
99
+ tests/ verifier, uploaded after the agent finishes
100
+ ```
101
+
102
+ ## Running it
103
+
104
+ ```bash
105
+ python -m pip install pytest # the only dependency
106
+ python build_dataset.py # rebuild + verify (oracle 4/4, baseline 0/4)
107
+ python run_harness.py --solution # oracle, expect 4/4
108
+ python run_harness.py --baseline # no agent, expect 0/4
109
+ python run_harness.py --predictions predictions/partial.jsonl
110
+ ```
111
+
112
+ A prediction is `{"task_id", "agent_script"}`: a shell script run in the
113
+ workspace, which is the Docker-free stand-in for "the agent did its work".
114
+ `resolved` means every verifier test passed (reward `1.0`), the Terminal-Bench
115
+ rule.
116
+
117
+ ## Verified results
118
+
119
+ ```
120
+ $ python run_harness.py --solution
121
+ tbdl-access-log-report 1.0 10/10
122
+ tbdl-git-recovery 1.0 10/10
123
+ tbdl-csv-canon 1.0 8/8
124
+ tbdl-build-repair 1.0 4/4
125
+ resolved 4/4 (100.0%)
126
+
127
+ $ python run_harness.py --baseline -> 0/4
128
+ $ python run_harness.py --predictions predictions/partial.jsonl
129
+ tbdl-access-log-report 0.0 9/10 p95 off by one rank
130
+ tbdl-git-recovery 0.0 5/10 wrong revision, no wip rescue
131
+ tbdl-csv-canon 0.0 5/8 BOM kept, rows unsorted
132
+ tbdl-build-repair 0.0 1/4 shell fixed, Python faults left
133
+ resolved 0/4 (0.0%)
134
+ ```
135
+
136
+ The partial control is the important one: each attempt is a *plausible* half-fix
137
+ and each still scores zero, while the per-test counts show the verifier is
138
+ grading the whole task rather than one easy assertion.
139
+
140
+ `build_dataset.py` refuses to write a row when a task already passes with no
141
+ agent at all, and it re-runs the finished JSONL through the harness in both
142
+ modes, so the file cannot drift from its verification.
143
+
144
+ ## Budget
145
+
146
+ Measured for `max_tokens = 2048`, `context = 240000`:
147
+
148
+ - instruction: 1.3k–2.4k characters (~350–600 tokens) per task
149
+ - whole dataset: 52.5 KiB ≈ 13.4k tokens, so all four rows fit in one context
150
+ - each task is solvable with many short turns: the oracle scripts are 40–90
151
+ lines total, so no single completion needs more than ~1k tokens
152
+
153
+ ## Deliberate deviations
154
+
155
+ - **`setup.sh` instead of a Dockerfile.** The Dockerfile is still shipped in the
156
+ row for fidelity, but the environment is rebuilt by a script so the benchmark
157
+ runs on a laptop with no daemon.
158
+ - **Host toolchain, not a pinned image.** Tasks are written against
159
+ `bash` + `git` + `python` + coreutils only, and the verifier avoids symlinks,
160
+ signals, `/proc` and permission bits so it behaves the same on Linux, macOS and
161
+ Windows/Git Bash.
162
+ - **`agent_script` predictions.** A full Terminal-Bench harness drives a model
163
+ turn by turn; here a prediction is the script that performs the same actions,
164
+ which makes the benchmark reproducible without an inference loop.
165
+ - **Static `reward`.** Multi-step tasks and `multi_step_reward_strategy` are not
166
+ used; every task is single-step with an all-or-nothing reward.
167
+
168
+ ## Platform note
169
+
170
+ On Windows, `bash` on `PATH` is often the WSL launcher. The harness resolves a
171
+ real POSIX shell (Git Bash), proves it works with a probe, and exports it to the
172
+ verifier as `TB_BASH`; verifier code that shells out should use
173
+ `os.environ.get("TB_BASH", "bash")`. A `python3` shim is placed in `$TB_ROOT/bin`
174
+ so scripts with `#!/usr/bin/env python3` run unchanged.
TerminalBench-DockerLess.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"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"]}}
2
+ {"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"]}}
3
+ {"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"]}}
4
+ {"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"]}}
build_dataset.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build TerminalBench-DockerLess.jsonl from tasks/.
2
+
3
+ A Terminal-Bench task is a directory: instruction, environment, solution, tests.
4
+ Docker supplies the environment; here `environment/setup.sh` builds the same
5
+ state in a throwaway directory instead, so a row is self-contained.
6
+
7
+ For every task this script:
8
+ 1. flattens the task directory into a row (instruction, files, tests, solution,
9
+ dockerfile) and renders both a classic `task.yaml` and a Harbor `task.toml`;
10
+ 2. runs the task with no agent at all, to record which verifier tests fail on
11
+ the untouched environment (`dockerless.baseline_failures`);
12
+ 3. writes the JSONL;
13
+ 4. re-runs the whole file through run_harness.py with --solution and
14
+ --baseline, and fails loudly unless the oracle scores 4/4 and the baseline
15
+ scores 0/4.
16
+
17
+ Run with: python build_dataset.py
18
+ """
19
+
20
+ import json
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ from pathlib import Path
26
+
27
+ ROOT = Path(__file__).resolve().parent
28
+ TASKS_DIR = ROOT / "tasks"
29
+ OUT = ROOT / "TerminalBench-DockerLess.jsonl"
30
+ REPORTS = ROOT / "reports"
31
+
32
+ sys.path.insert(0, str(ROOT))
33
+ import run_harness # noqa: E402
34
+
35
+ AUTHOR = {"name": "WorkBuddy Benchmarks", "email": "benchmarks@example.invalid"}
36
+
37
+ TASKS = [
38
+ {
39
+ "dir": "access-log-report",
40
+ "task_id": "tbdl-access-log-report",
41
+ "difficulty": "medium",
42
+ "category": "data-processing",
43
+ "tags": ["log-parsing", "text-processing", "json", "python"],
44
+ "description": "Aggregate a damaged access log into a canonical JSON report, a malformed-line index and a gzip archive.",
45
+ "expert_time_estimate_min": 25,
46
+ "junior_time_estimate_min": 90,
47
+ "max_agent_timeout_sec": 600.0,
48
+ "max_test_timeout_sec": 120.0,
49
+ "requires": ["bash", "python"],
50
+ },
51
+ {
52
+ "dir": "git-recovery",
53
+ "task_id": "tbdl-git-recovery",
54
+ "difficulty": "hard",
55
+ "category": "software-engineering",
56
+ "tags": ["git", "forensics", "history-recovery"],
57
+ "description": "Restore a deleted module from history, resurrect an unreachable commit, tag a release and leave a clean tree.",
58
+ "expert_time_estimate_min": 20,
59
+ "junior_time_estimate_min": 75,
60
+ "max_agent_timeout_sec": 600.0,
61
+ "max_test_timeout_sec": 120.0,
62
+ "requires": ["bash", "git"],
63
+ },
64
+ {
65
+ "dir": "csv-canon",
66
+ "task_id": "tbdl-csv-canon",
67
+ "difficulty": "hard",
68
+ "category": "data-processing",
69
+ "tags": ["csv", "cli", "spec-compliance", "exit-codes"],
70
+ "description": "Write a byte-exact CSV-to-TSV canonicaliser with strict error codes and numeric normalisation.",
71
+ "expert_time_estimate_min": 35,
72
+ "junior_time_estimate_min": 120,
73
+ "max_agent_timeout_sec": 900.0,
74
+ "max_test_timeout_sec": 120.0,
75
+ "requires": ["bash", "python"],
76
+ },
77
+ {
78
+ "dir": "build-repair",
79
+ "task_id": "tbdl-build-repair",
80
+ "difficulty": "hard",
81
+ "category": "software-engineering",
82
+ "tags": ["build", "shell", "debugging"],
83
+ "description": "Repair a shell build with three independent faults so it produces the expected report and passes its own suite.",
84
+ "expert_time_estimate_min": 25,
85
+ "junior_time_estimate_min": 90,
86
+ "max_agent_timeout_sec": 600.0,
87
+ "max_test_timeout_sec": 120.0,
88
+ "requires": ["bash", "python"],
89
+ },
90
+ ]
91
+
92
+
93
+ def read_text(path):
94
+ """Decode without newline translation so CRLF/BOM fixtures survive."""
95
+ return path.read_bytes().decode("utf-8")
96
+
97
+
98
+ def workspace_files(environment_dir):
99
+ files = {}
100
+ for path in sorted(environment_dir.rglob("*")):
101
+ if not path.is_file():
102
+ continue
103
+ rel = path.relative_to(environment_dir).as_posix()
104
+ if rel in ("Dockerfile", "setup.sh"):
105
+ continue
106
+ files[rel] = read_text(path)
107
+ return files
108
+
109
+
110
+ def render_task_yaml(meta, instruction):
111
+ lines = [
112
+ "# Terminal-Bench task definition",
113
+ "instruction: |",
114
+ ]
115
+ for line in instruction.rstrip("\n").split("\n"):
116
+ lines.append(" " + line if line else "")
117
+ lines += [
118
+ "author_name: %s" % AUTHOR["name"],
119
+ "author_email: %s" % AUTHOR["email"],
120
+ "difficulty: %s" % meta["difficulty"],
121
+ "category: %s" % meta["category"],
122
+ "tags:",
123
+ ]
124
+ for tag in meta["tags"]:
125
+ lines.append(" - %s" % tag)
126
+ lines += [
127
+ "parser_name: pytest",
128
+ "max_agent_timeout_sec: %.1f" % meta["max_agent_timeout_sec"],
129
+ "max_test_timeout_sec: %.1f" % meta["max_test_timeout_sec"],
130
+ "expert_time_estimate_min: %d" % meta["expert_time_estimate_min"],
131
+ "junior_time_estimate_min: %d" % meta["junior_time_estimate_min"],
132
+ ]
133
+ return "\n".join(lines) + "\n"
134
+
135
+
136
+ def render_task_toml(meta):
137
+ keywords = ", ".join('"%s"' % tag for tag in meta["tags"])
138
+ return (
139
+ 'schema_version = "1.4"\n'
140
+ 'source = "TerminalBench-DockerLess"\n'
141
+ "\n"
142
+ "[task]\n"
143
+ 'name = "swedl/%s"\n'
144
+ 'authors = [{ name = "%s", email = "%s" }]\n'
145
+ 'description = "%s"\n'
146
+ "keywords = [%s]\n"
147
+ "\n"
148
+ "[metadata]\n"
149
+ 'difficulty = "%s"\n'
150
+ 'category = "%s"\n'
151
+ "tags = [%s]\n"
152
+ "expert_time_estimate_min = %d\n"
153
+ "junior_time_estimate_min = %d\n"
154
+ "\n"
155
+ "[verifier]\n"
156
+ "timeout_sec = %.1f\n"
157
+ "\n"
158
+ "[agent]\n"
159
+ "timeout_sec = %.1f\n"
160
+ "\n"
161
+ "[environment]\n"
162
+ 'network_mode = "no-network"\n'
163
+ 'os = "linux"\n'
164
+ 'workdir = "/workspace"\n'
165
+ % (
166
+ meta["dir"],
167
+ AUTHOR["name"],
168
+ AUTHOR["email"],
169
+ meta["description"],
170
+ keywords,
171
+ meta["difficulty"],
172
+ meta["category"],
173
+ keywords,
174
+ meta["expert_time_estimate_min"],
175
+ meta["junior_time_estimate_min"],
176
+ meta["max_test_timeout_sec"],
177
+ meta["max_agent_timeout_sec"],
178
+ )
179
+ )
180
+
181
+
182
+ def build_row(meta):
183
+ task_dir = TASKS_DIR / meta["dir"]
184
+ environment = task_dir / "environment"
185
+
186
+ instruction = read_text(task_dir / "instruction.md")
187
+ setup_path = environment / "setup.sh"
188
+ setup = read_text(setup_path) if setup_path.is_file() else ""
189
+
190
+ row = {
191
+ "task_id": meta["task_id"],
192
+ "instruction": instruction,
193
+ "author_name": AUTHOR["name"],
194
+ "author_email": AUTHOR["email"],
195
+ "difficulty": meta["difficulty"],
196
+ "category": meta["category"],
197
+ "tags": list(meta["tags"]),
198
+ "parser_name": "pytest",
199
+ "max_agent_timeout_sec": meta["max_agent_timeout_sec"],
200
+ "max_test_timeout_sec": meta["max_test_timeout_sec"],
201
+ "expert_time_estimate_min": meta["expert_time_estimate_min"],
202
+ "junior_time_estimate_min": meta["junior_time_estimate_min"],
203
+ "task_yaml": render_task_yaml(meta, instruction),
204
+ "task_toml": render_task_toml(meta),
205
+ "dockerfile": read_text(environment / "Dockerfile"),
206
+ "solution": read_text(task_dir / "solution" / "solve.sh"),
207
+ "tests": {
208
+ path.name: read_text(path)
209
+ for path in sorted((task_dir / "tests").iterdir())
210
+ if path.is_file()
211
+ },
212
+ "dockerless": {
213
+ "setup": setup,
214
+ "setup_timeout_sec": 120,
215
+ "files": workspace_files(environment),
216
+ "test_cmd": "",
217
+ "workdir": "workspace",
218
+ "requires": list(meta["requires"]),
219
+ "baseline_failures": [],
220
+ },
221
+ }
222
+ return row
223
+
224
+
225
+ def baseline(row):
226
+ root = Path(tempfile.mkdtemp(prefix="tbdl-build-"))
227
+ try:
228
+ result, _ = run_harness.evaluate(row, "", root)
229
+ finally:
230
+ shutil.rmtree(root, ignore_errors=True)
231
+ return result
232
+
233
+
234
+ def main():
235
+ rows = []
236
+ print("%-24s %-7s %-8s %s" % ("task_id", "diff", "files", "baseline"))
237
+ for meta in TASKS:
238
+ row = build_row(meta)
239
+ result = baseline(row)
240
+ row["dockerless"]["baseline_failures"] = result["failing"]
241
+ if result["resolved"]:
242
+ raise RuntimeError(
243
+ "%s passes with no agent at all -- the task is not solvable-proof"
244
+ % row["task_id"]
245
+ )
246
+ if not result["tests_total"]:
247
+ raise RuntimeError("%s: verifier collected no tests" % row["task_id"])
248
+ rows.append(row)
249
+ print(
250
+ "%-24s %-7s %-8d %d/%d failing"
251
+ % (
252
+ row["task_id"],
253
+ row["difficulty"],
254
+ len(row["dockerless"]["files"]),
255
+ result["tests_total"] - result["tests_passed"],
256
+ result["tests_total"],
257
+ )
258
+ )
259
+
260
+ with open(OUT, "w", encoding="utf-8", newline="\n") as handle:
261
+ for row in rows:
262
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
263
+ print("\nwrote %s (%d rows, %.1f KiB)" % (OUT.name, len(rows), OUT.stat().st_size / 1024.0))
264
+
265
+ REPORTS.mkdir(exist_ok=True)
266
+ failures = []
267
+ for mode, expected in (("--solution", len(rows)), ("--baseline", 0)):
268
+ report_path = REPORTS / ("%s.json" % mode.lstrip("-"))
269
+ proc = subprocess.run(
270
+ [
271
+ sys.executable,
272
+ str(ROOT / "run_harness.py"),
273
+ "--dataset",
274
+ str(OUT),
275
+ mode,
276
+ "--out",
277
+ str(report_path),
278
+ ],
279
+ capture_output=True,
280
+ text=True,
281
+ encoding="utf-8",
282
+ )
283
+ tail = (proc.stdout.strip().splitlines() or ["<no output>"])[-1]
284
+ print("%-12s %s" % (mode, tail))
285
+ if proc.returncode != 0:
286
+ failures.append("%s exited %d: %s" % (mode, proc.returncode, proc.stderr[-800:]))
287
+ continue
288
+ resolved = json.loads(report_path.read_text(encoding="utf-8"))["resolved"]
289
+ if resolved != expected:
290
+ failures.append("%s resolved %d, expected %d" % (mode, resolved, expected))
291
+
292
+ if failures:
293
+ print("\nVERIFICATION FAILED")
294
+ for message in failures:
295
+ print(" - %s" % message)
296
+ return 1
297
+ print("\nverification passed: oracle %d/%d, baseline 0/%d" % (len(rows), len(rows), len(rows)))
298
+ return 0
299
+
300
+
301
+ if __name__ == "__main__":
302
+ sys.exit(main())
predictions/partial.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"task_id": "tbdl-access-log-report", "agent_name": "control-partial", "agent_script": "#!/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[int(round(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"}
2
+ {"task_id": "tbdl-git-recovery", "agent_name": "control-partial", "agent_script": "#!/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 ~ / Initial import$/ {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\"\ntrue # gave up on the wip commit\n\n# 3. tag the release commit\ngit tag v1.0 \"$loader_commit\"\n\ngit status --porcelain\n"}
3
+ {"task_id": "tbdl-csv-canon", "agent_name": "control-partial", "agent_script": "#!/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\", 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 pass # rows arrive sorted, surely\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"}
4
+ {"task_id": "tbdl-build-repair", "agent_name": "control-partial", "agent_script": "#!/usr/bin/env bash\nset -euo pipefail\ncd \"$TB_WORK\"\npython - <<'PYEOF'\nfrom pathlib import Path\npath = Path(\"build.sh\")\ntext = path.read_text(encoding=\"utf-8\")\ntext = text.replace('mkdir -p \"$OUTDIR\"', 'mkdir -p \"$OUT\" build')\npath.write_text(text, encoding=\"utf-8\", newline=\"\\n\")\nPYEOF\nbash build.sh || true\n"}
reports/baseline.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "TerminalBench-DockerLess.jsonl",
3
+ "mode": "baseline",
4
+ "tasks": 4,
5
+ "resolved": 0,
6
+ "resolve_rate": 0.0,
7
+ "seconds": 14.25,
8
+ "results": [
9
+ {
10
+ "task_id": "tbdl-access-log-report",
11
+ "reward": 0.0,
12
+ "resolved": false,
13
+ "tests_passed": 0,
14
+ "tests_total": 10,
15
+ "failing": [
16
+ "test_outputs.py::test_bytes_total_treats_dash_as_zero",
17
+ "test_outputs.py::test_gzip_roundtrip_is_byte_identical",
18
+ "test_outputs.py::test_malformed_line_numbers",
19
+ "test_outputs.py::test_p95_uses_nearest_rank",
20
+ "test_outputs.py::test_report_has_exactly_the_documented_keys",
21
+ "test_outputs.py::test_script_regenerates_identical_output",
22
+ "test_outputs.py::test_status_counts",
23
+ "test_outputs.py::test_top_paths_order_and_tiebreak",
24
+ "test_outputs.py::test_total_requests_counts_only_valid_lines",
25
+ "test_outputs.py::test_unique_paths_ignores_query_strings"
26
+ ],
27
+ "note": "ok",
28
+ "seconds": 2.1
29
+ },
30
+ {
31
+ "task_id": "tbdl-git-recovery",
32
+ "reward": 0.0,
33
+ "resolved": false,
34
+ "tests_passed": 1,
35
+ "tests_total": 10,
36
+ "failing": [
37
+ "test_outputs.py::test_app_py_is_committed_not_just_written",
38
+ "test_outputs.py::test_app_py_restored_from_config_loader_commit",
39
+ "test_outputs.py::test_junk_is_ignored_but_still_present",
40
+ "test_outputs.py::test_recovered_branch_points_at_the_wip_commit",
41
+ "test_outputs.py::test_recovered_commit_keeps_the_work_in_progress_plan",
42
+ "test_outputs.py::test_recovered_is_not_an_ancestor_of_main",
43
+ "test_outputs.py::test_restore_commit_message",
44
+ "test_outputs.py::test_tag_v1_points_at_the_config_loader_commit",
45
+ "test_outputs.py::test_worktree_is_clean"
46
+ ],
47
+ "note": "ok",
48
+ "seconds": 5.2
49
+ },
50
+ {
51
+ "task_id": "tbdl-csv-canon",
52
+ "reward": 0.0,
53
+ "resolved": false,
54
+ "tests_passed": 0,
55
+ "tests_total": 8,
56
+ "failing": [
57
+ "test_outputs.py::test_duplicate_column_exits_3",
58
+ "test_outputs.py::test_embedded_newline_survives",
59
+ "test_outputs.py::test_malformed_row_exits_4_with_physical_line",
60
+ "test_outputs.py::test_missing_input_exits_2",
61
+ "test_outputs.py::test_numeric_normalisation",
62
+ "test_outputs.py::test_orders_sample_is_canonicalised",
63
+ "test_outputs.py::test_output_has_no_bom_and_uses_lf",
64
+ "test_outputs.py::test_sorting_is_byte_order_not_numeric"
65
+ ],
66
+ "note": "ok",
67
+ "seconds": 2.74
68
+ },
69
+ {
70
+ "task_id": "tbdl-build-repair",
71
+ "reward": 0.0,
72
+ "resolved": false,
73
+ "tests_passed": 0,
74
+ "tests_total": 4,
75
+ "failing": [
76
+ "test_outputs.py::test_build_exits_zero",
77
+ "test_outputs.py::test_build_log_matches_report",
78
+ "test_outputs.py::test_project_suite_passes",
79
+ "test_outputs.py::test_report_content"
80
+ ],
81
+ "note": "ok",
82
+ "seconds": 4.2
83
+ }
84
+ ]
85
+ }
reports/partial.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "TerminalBench-DockerLess.jsonl",
3
+ "mode": "predictions",
4
+ "tasks": 4,
5
+ "resolved": 0,
6
+ "resolve_rate": 0.0,
7
+ "seconds": 30.47,
8
+ "results": [
9
+ {
10
+ "task_id": "tbdl-access-log-report",
11
+ "reward": 0.0,
12
+ "resolved": false,
13
+ "tests_passed": 9,
14
+ "tests_total": 10,
15
+ "failing": [
16
+ "test_outputs.py::test_p95_uses_nearest_rank"
17
+ ],
18
+ "note": "ok",
19
+ "seconds": 4.46
20
+ },
21
+ {
22
+ "task_id": "tbdl-git-recovery",
23
+ "reward": 0.0,
24
+ "resolved": false,
25
+ "tests_passed": 5,
26
+ "tests_total": 10,
27
+ "failing": [
28
+ "test_outputs.py::test_app_py_restored_from_config_loader_commit",
29
+ "test_outputs.py::test_recovered_branch_points_at_the_wip_commit",
30
+ "test_outputs.py::test_recovered_commit_keeps_the_work_in_progress_plan",
31
+ "test_outputs.py::test_recovered_is_not_an_ancestor_of_main",
32
+ "test_outputs.py::test_tag_v1_points_at_the_config_loader_commit"
33
+ ],
34
+ "note": "ok",
35
+ "seconds": 7.08
36
+ },
37
+ {
38
+ "task_id": "tbdl-csv-canon",
39
+ "reward": 0.0,
40
+ "resolved": false,
41
+ "tests_passed": 5,
42
+ "tests_total": 8,
43
+ "failing": [
44
+ "test_outputs.py::test_embedded_newline_survives",
45
+ "test_outputs.py::test_orders_sample_is_canonicalised",
46
+ "test_outputs.py::test_output_has_no_bom_and_uses_lf"
47
+ ],
48
+ "note": "ok",
49
+ "seconds": 8.41
50
+ },
51
+ {
52
+ "task_id": "tbdl-build-repair",
53
+ "reward": 0.0,
54
+ "resolved": false,
55
+ "tests_passed": 1,
56
+ "tests_total": 4,
57
+ "failing": [
58
+ "test_outputs.py::test_build_exits_zero",
59
+ "test_outputs.py::test_project_suite_passes",
60
+ "test_outputs.py::test_report_content"
61
+ ],
62
+ "note": "ok",
63
+ "seconds": 10.51
64
+ }
65
+ ]
66
+ }
reports/solution.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "TerminalBench-DockerLess.jsonl",
3
+ "mode": "solution",
4
+ "tasks": 4,
5
+ "resolved": 4,
6
+ "resolve_rate": 1.0,
7
+ "seconds": 28.8,
8
+ "results": [
9
+ {
10
+ "task_id": "tbdl-access-log-report",
11
+ "reward": 1.0,
12
+ "resolved": true,
13
+ "tests_passed": 10,
14
+ "tests_total": 10,
15
+ "failing": [],
16
+ "note": "ok",
17
+ "seconds": 4.13
18
+ },
19
+ {
20
+ "task_id": "tbdl-git-recovery",
21
+ "reward": 1.0,
22
+ "resolved": true,
23
+ "tests_passed": 10,
24
+ "tests_total": 10,
25
+ "failing": [],
26
+ "note": "ok",
27
+ "seconds": 6.67
28
+ },
29
+ {
30
+ "task_id": "tbdl-csv-canon",
31
+ "reward": 1.0,
32
+ "resolved": true,
33
+ "tests_passed": 8,
34
+ "tests_total": 8,
35
+ "failing": [],
36
+ "note": "ok",
37
+ "seconds": 8.01
38
+ },
39
+ {
40
+ "task_id": "tbdl-build-repair",
41
+ "reward": 1.0,
42
+ "resolved": true,
43
+ "tests_passed": 4,
44
+ "tests_total": 4,
45
+ "failing": [],
46
+ "note": "ok",
47
+ "seconds": 9.98
48
+ }
49
+ ]
50
+ }
run_harness.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TerminalBench-DockerLess evaluation harness.
2
+
3
+ A Terminal-Bench trial is: build the environment, let the agent work in it, then
4
+ run a verifier that decides success. Docker normally provides the environment;
5
+ here each row carries a `dockerless.setup` script that builds the same state in a
6
+ throwaway directory, so a trial needs only bash, git and python.
7
+
8
+ $TB_ROOT/
9
+ workspace/ <- the agent's cwd (the container's /workspace)
10
+ home/ <- HOME
11
+ tmp/ <- TMPDIR
12
+ bin/ <- prepended to PATH (holds a python3 shim)
13
+ tests/ <- the verifier, uploaded read-only-ish after the agent runs
14
+
15
+ Usage
16
+ -----
17
+ python run_harness.py --solution # oracle, expect 4/4
18
+ python run_harness.py --baseline # do nothing, expect 0/4
19
+ python run_harness.py --predictions preds.jsonl # {"task_id", "agent_script"}
20
+
21
+ A task is resolved when every verifier test passes (reward 1.0), which is the
22
+ Terminal-Bench rule.
23
+ """
24
+
25
+ import argparse
26
+ import json
27
+ import os
28
+ import re
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+ import time
34
+ from pathlib import Path
35
+
36
+ RESULT_RE = re.compile(
37
+ r"^(test_[A-Za-z0-9_]+\.py::[A-Za-z0-9_\[\]\-\.]+)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)"
38
+ )
39
+
40
+ PYTHON_SHIM = '#!/bin/sh\nexec python "$@"\n'
41
+
42
+ _BASH_CACHE = []
43
+
44
+
45
+ def find_bash():
46
+ """Resolve a usable POSIX shell.
47
+
48
+ On Windows ``bash`` on PATH is often the WSL launcher, which may be blocked
49
+ or simply start a different filesystem; prefer Git's own bash and prove the
50
+ candidate works before trusting it.
51
+ """
52
+ if _BASH_CACHE:
53
+ return _BASH_CACHE[0]
54
+
55
+ candidates = []
56
+ override = os.environ.get("TBDL_BASH")
57
+ if override:
58
+ candidates.append(override)
59
+ exepath = os.environ.get("EXEPATH")
60
+ if exepath:
61
+ candidates.append(os.path.join(exepath, "bash.exe"))
62
+ git = shutil.which("git")
63
+ if git:
64
+ git_bin = Path(git).resolve().parent
65
+ candidates.append(str(git_bin.parent / "bin" / "bash.exe"))
66
+ candidates.append(str(git_bin.parent / "usr" / "bin" / "bash.exe"))
67
+ if os.name == "nt":
68
+ candidates.append(r"C:\Program Files\Git\bin\bash.exe")
69
+ candidates.append(r"C:\Program Files\Git\usr\bin\bash.exe")
70
+ candidates.append(shutil.which("bash") or "bash")
71
+
72
+ for candidate in candidates:
73
+ if not candidate or not Path(candidate).exists():
74
+ continue
75
+ try:
76
+ probe = subprocess.run(
77
+ [candidate, "-c", "echo tbdl-ok"],
78
+ capture_output=True,
79
+ text=True,
80
+ timeout=20,
81
+ )
82
+ except (OSError, subprocess.SubprocessError):
83
+ continue
84
+ if probe.returncode == 0 and "tbdl-ok" in probe.stdout:
85
+ _BASH_CACHE.append(candidate)
86
+ return candidate
87
+
88
+ _BASH_CACHE.append("bash")
89
+ return "bash"
90
+
91
+
92
+ def write_files(files, dest):
93
+ for rel, content in files.items():
94
+ path = dest / rel
95
+ path.parent.mkdir(parents=True, exist_ok=True)
96
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
97
+ handle.write(content)
98
+
99
+
100
+ def sandbox_env(root):
101
+ env = os.environ.copy()
102
+ env.update(
103
+ {
104
+ "TB_ROOT": str(root),
105
+ "TB_WORK": str(root / "workspace"),
106
+ "HOME": str(root / "home"),
107
+ "TMPDIR": str(root / "tmp"),
108
+ "TEMP": str(root / "tmp"),
109
+ "TMP": str(root / "tmp"),
110
+ "PATH": str(root / "bin") + os.pathsep + env.get("PATH", ""),
111
+ "PYTHONIOENCODING": "utf-8",
112
+ "PYTHONDONTWRITEBYTECODE": "1",
113
+ "GIT_CONFIG_NOSYSTEM": "1",
114
+ "GIT_AUTHOR_NAME": "tbdl",
115
+ "GIT_AUTHOR_EMAIL": "tbdl@example.invalid",
116
+ "GIT_COMMITTER_NAME": "tbdl",
117
+ "GIT_COMMITTER_EMAIL": "tbdl@example.invalid",
118
+ "GIT_AUTHOR_DATE": "2026-10-30T12:00:00+0000",
119
+ "GIT_COMMITTER_DATE": "2026-10-30T12:00:00+0000",
120
+ "TB_BASH": find_bash(),
121
+ }
122
+ )
123
+ return env
124
+
125
+
126
+ def build_sandbox(row, root):
127
+ for name in ("workspace", "home", "tmp", "bin", "tests"):
128
+ (root / name).mkdir(parents=True, exist_ok=True)
129
+ shim = root / "bin" / "python3"
130
+ shim.write_text(PYTHON_SHIM, encoding="utf-8", newline="\n")
131
+ write_files(row["dockerless"]["files"], root / "workspace")
132
+ write_files(row["tests"], root / "tests")
133
+ env = sandbox_env(root)
134
+
135
+ setup = row["dockerless"].get("setup", "")
136
+ if setup.strip():
137
+ script = root / "setup.sh"
138
+ script.write_text(setup, encoding="utf-8", newline="\n")
139
+ proc = subprocess.run(
140
+ [find_bash(), str(script)],
141
+ cwd=str(root / "workspace"),
142
+ capture_output=True,
143
+ text=True,
144
+ encoding="utf-8",
145
+ env=env,
146
+ timeout=row["dockerless"].get("setup_timeout_sec", 120),
147
+ )
148
+ if proc.returncode != 0:
149
+ raise RuntimeError(
150
+ "setup failed for %s\n%s\n%s" % (row["task_id"], proc.stdout[-3000:], proc.stderr[-3000:])
151
+ )
152
+ return env
153
+
154
+
155
+ def run_script(path, cwd, env, timeout, label):
156
+ try:
157
+ return subprocess.run(
158
+ [find_bash(), str(path)],
159
+ cwd=str(cwd),
160
+ capture_output=True,
161
+ text=True,
162
+ encoding="utf-8",
163
+ env=env,
164
+ timeout=timeout,
165
+ )
166
+ except subprocess.TimeoutExpired:
167
+ return subprocess.CompletedProcess([], 124, "", "%s timed out after %ss" % (label, timeout))
168
+
169
+
170
+ def parse_results(stdout):
171
+ results = {}
172
+ for raw in stdout.splitlines():
173
+ match = RESULT_RE.match(raw.strip())
174
+ if match:
175
+ results[match.group(1)] = match.group(2)
176
+ return results
177
+
178
+
179
+ def evaluate(row, agent_script, root, keep=False):
180
+ env = build_sandbox(row, root)
181
+ work = root / "workspace"
182
+
183
+ note = "ok"
184
+ if agent_script is not None and agent_script.strip():
185
+ agent_path = root / "agent.sh"
186
+ agent_path.write_text(agent_script, encoding="utf-8", newline="\n")
187
+ proc = run_script(
188
+ agent_path, work, env, row.get("max_agent_timeout_sec", 300), "agent"
189
+ )
190
+ if proc.returncode != 0:
191
+ note = "agent script exited %d" % proc.returncode
192
+
193
+ test_cmd = row["dockerless"]["test_cmd"]
194
+ test_script = root / "tests" / "test.sh"
195
+ if test_cmd and test_cmd.strip():
196
+ test_path = root / "run-tests.sh"
197
+ test_path.write_text(test_cmd, encoding="utf-8", newline="\n")
198
+ else:
199
+ test_path = test_script
200
+ proc = run_script(
201
+ test_path, work, env, row.get("max_test_timeout_sec", 120), "verifier"
202
+ )
203
+
204
+ results = parse_results(proc.stdout)
205
+ passed = [name for name, outcome in results.items() if outcome == "PASSED"]
206
+ failed = sorted(name for name, outcome in results.items() if outcome != "PASSED")
207
+ resolved = bool(results) and not failed
208
+ return {
209
+ "task_id": row["task_id"],
210
+ "reward": 1.0 if resolved else 0.0,
211
+ "resolved": resolved,
212
+ "tests_passed": len(passed),
213
+ "tests_total": len(results),
214
+ "failing": failed[:12],
215
+ "note": note if results else "no tests collected",
216
+ "seconds": 0.0,
217
+ }, proc
218
+
219
+
220
+ def load_rows(path):
221
+ return [json.loads(line) for line in open(path, encoding="utf-8") if line.strip()]
222
+
223
+
224
+ def main():
225
+ parser = argparse.ArgumentParser(description=__doc__)
226
+ parser.add_argument("--dataset", default="TerminalBench-DockerLess.jsonl")
227
+ parser.add_argument("--solution", action="store_true", help="run each task's oracle solution")
228
+ parser.add_argument("--baseline", action="store_true", help="run no agent at all")
229
+ parser.add_argument("--predictions", help="JSONL of {task_id, agent_script}")
230
+ parser.add_argument("--only", help="restrict to one task_id")
231
+ parser.add_argument("--out", help="write a JSON report here")
232
+ args = parser.parse_args()
233
+
234
+ rows = load_rows(args.dataset)
235
+ if args.only:
236
+ rows = [row for row in rows if row["task_id"] == args.only]
237
+ if not rows:
238
+ parser.error("unknown task_id: %s" % args.only)
239
+
240
+ predictions = {}
241
+ if args.predictions:
242
+ for line in open(args.predictions, encoding="utf-8"):
243
+ if line.strip():
244
+ record = json.loads(line)
245
+ predictions[record["task_id"]] = record.get("agent_script", "")
246
+
247
+ started = time.time()
248
+ results = []
249
+ print("%-24s %-7s %-8s %s" % ("task_id", "reward", "tests", "note"))
250
+ for row in rows:
251
+ if args.solution:
252
+ agent_script = row.get("solution") or row["dockerless"].get("solution", "")
253
+ elif args.baseline:
254
+ agent_script = ""
255
+ else:
256
+ agent_script = predictions.get(row["task_id"], "")
257
+
258
+ root = Path(tempfile.mkdtemp(prefix="tbdl-%s-" % row["task_id"][:12]))
259
+ begin = time.time()
260
+ try:
261
+ result, proc = evaluate(row, agent_script, root)
262
+ finally:
263
+ shutil.rmtree(root, ignore_errors=True)
264
+ result["seconds"] = round(time.time() - begin, 2)
265
+ results.append(result)
266
+ print(
267
+ "%-24s %-7.1f %d/%-6d %s"
268
+ % (
269
+ result["task_id"],
270
+ result["reward"],
271
+ result["tests_passed"],
272
+ result["tests_total"],
273
+ result["note"],
274
+ )
275
+ )
276
+ if result["failing"] and args.baseline:
277
+ for name in result["failing"]:
278
+ print(" fail %s" % name)
279
+
280
+ solved = sum(1 for result in results if result["resolved"])
281
+ elapsed = time.time() - started
282
+ summary = {
283
+ "dataset": Path(args.dataset).name,
284
+ "mode": "solution" if args.solution else ("baseline" if args.baseline else "predictions"),
285
+ "tasks": len(rows),
286
+ "resolved": solved,
287
+ "resolve_rate": round(solved / len(rows), 4) if rows else 0.0,
288
+ "seconds": round(elapsed, 2),
289
+ "results": results,
290
+ }
291
+ print(
292
+ "\nresolved %d/%d (%.1f%%) in %.1fs"
293
+ % (solved, len(rows), 100.0 * summary["resolve_rate"], elapsed)
294
+ )
295
+ if args.out:
296
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
297
+ Path(args.out).write_text(json.dumps(summary, indent=2), encoding="utf-8")
298
+ print("report -> %s" % args.out)
299
+
300
+
301
+ if __name__ == "__main__":
302
+ main()
tasks/access-log-report/environment/Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim
2
+
3
+ RUN apt-get update && apt-get install -y --no-install-recommends \
4
+ bash coreutils gzip git \
5
+ && rm -rf /var/lib/apt/lists/*
6
+
7
+ WORKDIR /workspace
8
+ COPY logs/ /workspace/logs/
9
+
10
+ CMD ["/bin/bash"]
tasks/access-log-report/environment/logs/access.log ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 10.0.0.1 - - [10/Oct/2026:13:00:00 +0000] "GET /index.html HTTP/1.1" 200 200 "-" "curl/8.5.0" 3
2
+ 10.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
3
+ 10.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
4
+ 10.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
5
+ 10.0.0.5 - - [10/Oct/2026:13:02:08 +0000] "GET /index.html HTTP/1.1" 200 252 "-" "curl/8.5.0" 110
6
+ 10.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
7
+ 10.0.0.9 - - [10/Oct/2026:13:02:11 +0000] "GET /index.html HTTP/1.1" 200 512 "-" "curl/8.0"
8
+ 10.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
9
+ 10.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
10
+ 10.0.0.9 - - [10/Oct/2026:13:04:16 +0000] "GET /index.html HTTP/1.1" 200 304 "-" "curl/8.5.0" 74
11
+ 10.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
12
+ 10.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
13
+ 10.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
14
+ 10.0.0.4 - - [10/Oct/2026:13:06:24 +0000] "GET /api/users HTTP/1.1" 200 356 "-" "curl/8.5.0" 44
15
+ 10.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
16
+ 10.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
17
+ 10.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
18
+ 10.0.0.8 - - [10/Oct/2026:13:08:32 +0000] "GET /api/users HTTP/1.1" 200 408 "-" "curl/8.5.0" 14
19
+ 10.0.0.3 - - [10/Oct/2026:13:05:44 +0000] "POST /api/users HTTP/1.1" abc 300 "-" "curl/8.0" 44
20
+ 10.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
21
+ 10.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
22
+ 10.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
23
+ 10.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
24
+ 10.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
25
+ 10.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
26
+ 10.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
27
+ 10.0.0.7 - - [10/Oct/2026:13:12:48 +0000] "GET /static/app.js HTTP/1.1" 200 512 "-" "curl/8.5.0" 90
28
+ 10.0.0.4 - - [10/Oct/2026:13:09:02 +0000] "GET /health HTTP/1.1" 200 0
29
+ 10.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
30
+ 10.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
31
+ 10.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
32
+ 10.0.0.2 - - [10/Oct/2026:13:14:56 +0000] "GET /static/app.js HTTP/1.1" 304 564 "-" "curl/8.5.0" 58
33
+ 10.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
34
+ 10.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
35
+ 10.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
36
+ 10.0.0.6 - - [10/Oct/2026:13:16:04 +0000] "GET /health HTTP/1.1" 404 616 "-" "curl/8.5.0" 28
37
+ # rotated by logrotate at 2026-10-10T14:00:00Z
38
+ 10.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
39
+ 10.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
40
+ 10.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
tasks/access-log-report/instruction.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Access log report
2
+
3
+ `logs/access.log` is a web server access log in a combined-ish format:
4
+
5
+ ```
6
+ <ip> - - [<timestamp>] "<METHOD> <path> HTTP/1.1" <status> <bytes> "<referer>" "<user-agent>" <duration_ms>
7
+ ```
8
+
9
+ Some lines are damaged. The user-agent field may contain escaped double quotes
10
+ (`\"`), so the line cannot be parsed by splitting on `"` -- quoted fields have to
11
+ be scanned properly. `bytes` is `-` when the server did not record a size.
12
+
13
+ Write **`tools/report.sh`** in the workspace root. Running
14
+
15
+ ```
16
+ bash tools/report.sh
17
+ ```
18
+
19
+ from the workspace root must read `logs/access.log` and (re)generate the
20
+ following under `out/`, exit 0, and print nothing that matters. It must be
21
+ idempotent: deleting `out/` and running it again must produce byte-identical
22
+ files.
23
+
24
+ ## `out/report.json`
25
+
26
+ A JSON object with exactly these keys:
27
+
28
+ | key | type | meaning |
29
+ | --- | --- | --- |
30
+ | `total_requests` | int | number of **valid** lines |
31
+ | `unique_paths` | int | number of distinct normalised paths |
32
+ | `status_counts` | object | `{"<status>": <count>}`, keys are strings; only statuses that occur |
33
+ | `top_paths` | array | up to 3 objects `{"path": str, "count": int}`, highest count first, ties broken by path ascending |
34
+ | `bytes_total` | int | sum of `bytes` over valid lines, `-` counts as 0 |
35
+ | `p95_ms` | int | 95th percentile of `duration_ms`, nearest-rank method |
36
+
37
+ `p95_ms` is the nearest-rank percentile: sort the durations ascending, take
38
+ element number `ceil(0.95 * n)` counting from 1. With `n = 36` that is the 35th
39
+ smallest duration. If there are no valid lines, `p95_ms` is `0`.
40
+
41
+ Paths are normalised by dropping everything from the first `?` onwards, so
42
+ `/api/users?id=42` counts as `/api/users`.
43
+
44
+ ## `out/malformed.txt`
45
+
46
+ The 1-based line numbers of the lines that do not match the grammar above, one
47
+ per line, ascending. A line is malformed if any of these hold: it is not the
48
+ nine-part shape above, `status` is not exactly three digits, `bytes` is neither
49
+ `-` nor digits, or the trailing `duration_ms` is missing or not digits.
50
+ Malformed lines are excluded from every aggregate.
51
+
52
+ ## `out/access.log.gz`
53
+
54
+ A gzip stream whose decompressed content is byte-for-byte identical to
55
+ `logs/access.log`.
56
+
57
+ ## Notes
58
+
59
+ - Only `logs/access.log` is input; do not edit it.
60
+ - `python` is on `PATH` (`python3` is also available). Standard library only --
61
+ there is no network access.
tasks/access-log-report/solution/solve.sh ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle solution: a regex-based parser that survives escaped quotes in the
3
+ # user-agent field, plus deterministic JSON/gzip output.
4
+ set -euo pipefail
5
+ cd "$TB_WORK"
6
+ mkdir -p tools
7
+
8
+ cat > tools/report.py <<'PYEOF'
9
+ import gzip
10
+ import json
11
+ import math
12
+ import re
13
+ from collections import Counter
14
+ from pathlib import Path
15
+
16
+ LINE = re.compile(
17
+ r'^(?P<ip>\S+) - - \[(?P<ts>[^\]]+)\] '
18
+ r'"(?P<method>[A-Z]+) (?P<path>\S+) HTTP/1\.1" '
19
+ r'(?P<status>\d{3}) (?P<size>\d+|-) '
20
+ r'"(?P<ref>(?:[^"\\]|\\.)*)" "(?P<ua>(?:[^"\\]|\\.)*)" '
21
+ r'(?P<ms>\d+)$'
22
+ )
23
+
24
+
25
+ def main():
26
+ root = Path(__file__).resolve().parent.parent
27
+ log = root / "logs" / "access.log"
28
+ raw = log.read_bytes()
29
+ lines = raw.decode("utf-8").split("\n")
30
+ if lines and lines[-1] == "":
31
+ lines.pop()
32
+
33
+ paths, statuses, durations, bad = [], [], [], []
34
+ total_bytes = 0
35
+ for number, line in enumerate(lines, 1):
36
+ match = LINE.match(line)
37
+ if match is None:
38
+ bad.append(number)
39
+ continue
40
+ paths.append(match.group("path").split("?")[0])
41
+ statuses.append(match.group("status"))
42
+ size = match.group("size")
43
+ total_bytes += 0 if size == "-" else int(size)
44
+ durations.append(int(match.group("ms")))
45
+
46
+ durations.sort()
47
+ count = len(durations)
48
+ p95 = durations[math.ceil(0.95 * count) - 1] if count else 0
49
+
50
+ path_counts = Counter(paths)
51
+ top = sorted(path_counts.items(), key=lambda item: (-item[1], item[0]))[:3]
52
+
53
+ report = {
54
+ "total_requests": count,
55
+ "unique_paths": len(path_counts),
56
+ "status_counts": dict(sorted(Counter(statuses).items())),
57
+ "top_paths": [{"path": path, "count": hits} for path, hits in top],
58
+ "bytes_total": total_bytes,
59
+ "p95_ms": p95,
60
+ }
61
+
62
+ out = root / "out"
63
+ out.mkdir(parents=True, exist_ok=True)
64
+ with open(out / "report.json", "w", encoding="utf-8", newline="\n") as handle:
65
+ handle.write(json.dumps(report, indent=2, sort_keys=True) + "\n")
66
+ with open(out / "malformed.txt", "w", encoding="utf-8", newline="\n") as handle:
67
+ handle.write("".join("%d\n" % number for number in bad))
68
+ with open(out / "access.log.gz", "wb") as handle:
69
+ with gzip.GzipFile(fileobj=handle, mode="wb", mtime=0) as gz:
70
+ gz.write(raw)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
75
+ PYEOF
76
+
77
+ cat > tools/report.sh <<'SHEOF'
78
+ #!/usr/bin/env bash
79
+ set -euo pipefail
80
+ here="$(cd "$(dirname "$0")/.." && pwd)"
81
+ exec python "$here/tools/report.py"
82
+ SHEOF
83
+
84
+ chmod +x tools/report.sh
85
+ bash tools/report.sh
tasks/access-log-report/tests/test.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the
3
+ # reward signal (0 = solved).
4
+ set -uo pipefail
5
+ cd "$TB_ROOT/tests"
6
+ python -m pytest -v --tb=short -p no:cacheprovider test_outputs.py
tasks/access-log-report/tests/test_outputs.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import json
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ WORK = Path(os.environ["TB_WORK"])
11
+ BASH = os.environ.get("TB_BASH", "bash")
12
+
13
+
14
+ def load_report():
15
+ path = WORK / "out" / "report.json"
16
+ assert path.is_file(), "out/report.json was not created"
17
+ return json.loads(path.read_text(encoding="utf-8"))
18
+
19
+
20
+ def test_report_has_exactly_the_documented_keys():
21
+ report = load_report()
22
+ assert sorted(report) == [
23
+ "bytes_total",
24
+ "p95_ms",
25
+ "status_counts",
26
+ "top_paths",
27
+ "total_requests",
28
+ "unique_paths",
29
+ ]
30
+
31
+
32
+ def test_total_requests_counts_only_valid_lines():
33
+ assert load_report()["total_requests"] == 36
34
+
35
+
36
+ def test_unique_paths_ignores_query_strings():
37
+ assert load_report()["unique_paths"] == 5
38
+
39
+
40
+ def test_status_counts():
41
+ assert load_report()["status_counts"] == {"200": 28, "304": 4, "404": 3, "500": 1}
42
+
43
+
44
+ def test_top_paths_order_and_tiebreak():
45
+ assert load_report()["top_paths"] == [
46
+ {"path": "/api/users", "count": 12},
47
+ {"path": "/index.html", "count": 12},
48
+ {"path": "/static/app.js", "count": 6},
49
+ ]
50
+
51
+
52
+ def test_bytes_total_treats_dash_as_zero():
53
+ assert load_report()["bytes_total"] == 14535
54
+
55
+
56
+ def test_p95_uses_nearest_rank():
57
+ assert load_report()["p95_ms"] == 162
58
+
59
+
60
+ def test_malformed_line_numbers():
61
+ path = WORK / "out" / "malformed.txt"
62
+ assert path.is_file(), "out/malformed.txt was not created"
63
+ numbers = [int(line) for line in path.read_text(encoding="utf-8").split()]
64
+ assert numbers == [7, 19, 28, 37]
65
+
66
+
67
+ def test_gzip_roundtrip_is_byte_identical():
68
+ original = (WORK / "logs" / "access.log").read_bytes()
69
+ archive = WORK / "out" / "access.log.gz"
70
+ assert archive.is_file(), "out/access.log.gz was not created"
71
+ assert gzip.decompress(archive.read_bytes()) == original
72
+
73
+
74
+ def test_script_regenerates_identical_output():
75
+ out = WORK / "out"
76
+ before = (out / "report.json").read_bytes()
77
+ before_bad = (out / "malformed.txt").read_bytes()
78
+ shutil.rmtree(out)
79
+ proc = subprocess.run(
80
+ [BASH, "tools/report.sh"],
81
+ cwd=str(WORK),
82
+ capture_output=True,
83
+ text=True,
84
+ )
85
+ assert proc.returncode == 0, "tools/report.sh failed:\n%s\n%s" % (proc.stdout, proc.stderr)
86
+ assert (out / "report.json").read_bytes() == before
87
+ assert (out / "malformed.txt").read_bytes() == before_bad
tasks/build-repair/environment/Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim
2
+
3
+ RUN apt-get update && apt-get install -y --no-install-recommends \
4
+ bash coreutils \
5
+ && rm -rf /var/lib/apt/lists/*
6
+
7
+ WORKDIR /workspace
8
+ COPY . /workspace/
9
+
10
+ CMD ["/bin/bash"]
tasks/build-repair/environment/build.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ OUT=dist
5
+ mkdir -p "$OUTDIR"
6
+
7
+ python src/gen.py data/input.txt | tee build/gen.log > "$OUT/report.txt"
8
+
9
+ python -m pytest tests -q
tasks/build-repair/environment/data/input.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ alpha,10
2
+ beta,20
3
+ gamma,31
4
+ delta,40
5
+ epsilon,55
tasks/build-repair/environment/src/gen.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the per-record report on stdout."""
2
+
3
+ import sys
4
+
5
+ from lib.stats import mean
6
+
7
+
8
+ def main(path):
9
+ with open(path, "r", encoding="utf-8") as handle:
10
+ lines = [line.strip() for line in handle if line.strip()]
11
+
12
+ records = []
13
+ for line in lines[:-1]:
14
+ name, _, score = line.partition(",")
15
+ records.append((name, int(score)))
16
+
17
+ for name, score in records:
18
+ print("%s=%d" % (name, score))
19
+ print("mean=%.2f" % mean([score for _, score in records]))
20
+
21
+
22
+ if __name__ == "__main__":
23
+ main(sys.argv[1])
tasks/build-repair/environment/src/lib/__init__.py ADDED
File without changes
tasks/build-repair/environment/src/lib/stats.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Tiny stats helpers used by the report generator."""
2
+
3
+
4
+ def mean(values):
5
+ """Arithmetic mean of a non-empty sequence."""
6
+ total = sum(values)
7
+ return total // len(values)
tasks/build-repair/environment/tests/test_pipeline.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ ROOT = Path(__file__).resolve().parent.parent
6
+
7
+
8
+ def run_gen():
9
+ return subprocess.run(
10
+ [sys.executable, "src/gen.py", "data/input.txt"],
11
+ cwd=str(ROOT),
12
+ capture_output=True,
13
+ text=True,
14
+ )
15
+
16
+
17
+ def test_every_record_is_reported_in_input_order():
18
+ proc = run_gen()
19
+ assert proc.returncode == 0, proc.stderr
20
+ assert proc.stdout.strip().splitlines() == [
21
+ "alpha=10",
22
+ "beta=20",
23
+ "gamma=31",
24
+ "delta=40",
25
+ "epsilon=55",
26
+ "mean=31.20",
27
+ ]
tasks/build-repair/environment/tests/test_stats.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
5
+
6
+ from lib.stats import mean
7
+
8
+
9
+ def test_mean_of_even_count_is_fractional():
10
+ assert abs(mean([1, 2]) - 1.5) < 1e-9
11
+
12
+
13
+ def test_mean_keeps_the_fractional_part():
14
+ assert abs(mean([10, 20, 31]) - 61 / 3) < 1e-9
tasks/build-repair/instruction.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Make the report build work again
2
+
3
+ `build.sh` is supposed to regenerate `dist/report.txt` and then run the project's
4
+ own test suite. Right now it does neither:
5
+
6
+ ```
7
+ $ bash build.sh
8
+ build.sh: line 5: OUTDIR: unbound variable
9
+ ```
10
+
11
+ Nothing in the repository is sacred except the inputs and the tests. Fix the
12
+ build so that `bash build.sh`, run from the workspace root, exits `0` and
13
+ produces:
14
+
15
+ - `dist/report.txt`
16
+ - `build/gen.log`
17
+
18
+ Both files must contain the same text: one `name=score` line per record from
19
+ `data/input.txt`, in input order, followed by a single `mean=<value>` line where
20
+ the value is the arithmetic mean of the scores printed with exactly two decimal
21
+ places.
22
+
23
+ For the shipped `data/input.txt` the expected content is:
24
+
25
+ ```
26
+ alpha=10
27
+ beta=20
28
+ gamma=31
29
+ delta=40
30
+ epsilon=55
31
+ mean=31.20
32
+ ```
33
+
34
+ ## Constraints
35
+
36
+ - `data/input.txt` must not change.
37
+ - The tests in `tests/` must not change; they must pass as written. They are run
38
+ by `build.sh` itself, so a build that "succeeds" while skipping them is not a
39
+ fix.
40
+ - `dist/` and `build/` are build outputs; they may be recreated freely.
41
+ - Only the Python standard library is available, and there is no network.
42
+
43
+ ## Notes
44
+
45
+ - `bash build.sh` must be safe to run repeatedly.
46
+ - Do not silence failures with `|| true`; the build has to fail loudly when a
47
+ step really fails.
tasks/build-repair/solution/solve.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle solution: three independent repairs -- the shell variable typo and the
3
+ # missing output directory, the dropped final record, and the truncated mean.
4
+ set -euo pipefail
5
+ cd "$TB_WORK"
6
+
7
+ cat > build.sh <<'SHEOF'
8
+ #!/usr/bin/env bash
9
+ set -euo pipefail
10
+
11
+ OUT=dist
12
+ mkdir -p "$OUT" build
13
+
14
+ python src/gen.py data/input.txt | tee build/gen.log > "$OUT/report.txt"
15
+
16
+ python -m pytest tests -q
17
+ SHEOF
18
+
19
+ python - <<'PYEOF'
20
+ from pathlib import Path
21
+
22
+ gen = Path("src/gen.py")
23
+ text = gen.read_text(encoding="utf-8")
24
+ text = text.replace("for line in lines[:-1]:", "for line in lines:")
25
+ gen.write_text(text, encoding="utf-8", newline="\n")
26
+
27
+ stats = Path("src/lib/stats.py")
28
+ text = stats.read_text(encoding="utf-8")
29
+ text = text.replace("return total // len(values)", "return total / len(values)")
30
+ stats.write_text(text, encoding="utf-8", newline="\n")
31
+ PYEOF
32
+
33
+ bash build.sh
tasks/build-repair/tests/test.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the
3
+ # reward signal (0 = solved).
4
+ set -uo pipefail
5
+ cd "$TB_ROOT/tests"
6
+ python -m pytest -v --tb=short -p no:cacheprovider test_outputs.py
tasks/build-repair/tests/test_outputs.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ WORK = Path(os.environ["TB_WORK"])
8
+ BASH = os.environ.get("TB_BASH", "bash")
9
+
10
+ EXPECTED_REPORT = (
11
+ "alpha=10\n"
12
+ "beta=20\n"
13
+ "gamma=31\n"
14
+ "delta=40\n"
15
+ "epsilon=55\n"
16
+ "mean=31.20\n"
17
+ )
18
+
19
+
20
+ @pytest.fixture(scope="module")
21
+ def build():
22
+ for path in (WORK / "dist", WORK / "build"):
23
+ if path.exists():
24
+ for child in path.rglob("*"):
25
+ if child.is_file():
26
+ child.unlink()
27
+ return subprocess.run(
28
+ [BASH, "build.sh"],
29
+ cwd=str(WORK),
30
+ capture_output=True,
31
+ text=True,
32
+ encoding="utf-8",
33
+ )
34
+
35
+
36
+ def test_build_exits_zero(build):
37
+ assert build.returncode == 0, "build.sh failed:\n%s\n%s" % (build.stdout, build.stderr)
38
+
39
+
40
+ def test_report_content(build):
41
+ path = WORK / "dist" / "report.txt"
42
+ assert path.is_file(), "dist/report.txt was not produced"
43
+ assert path.read_text(encoding="utf-8") == EXPECTED_REPORT
44
+
45
+
46
+ def test_build_log_matches_report(build):
47
+ log = WORK / "build" / "gen.log"
48
+ report = WORK / "dist" / "report.txt"
49
+ assert log.is_file(), "build/gen.log was not produced"
50
+ assert log.read_text(encoding="utf-8") == report.read_text(encoding="utf-8")
51
+
52
+
53
+ def test_project_suite_passes(build):
54
+ proc = subprocess.run(
55
+ ["python", "-m", "pytest", "tests", "-q", "-p", "no:cacheprovider"],
56
+ cwd=str(WORK),
57
+ capture_output=True,
58
+ text=True,
59
+ encoding="utf-8",
60
+ )
61
+ assert proc.returncode == 0, "project tests failed:\n%s\n%s" % (proc.stdout, proc.stderr)
tasks/csv-canon/environment/Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim
2
+
3
+ RUN apt-get update && apt-get install -y --no-install-recommends \
4
+ bash coreutils \
5
+ && rm -rf /var/lib/apt/lists/*
6
+
7
+ WORKDIR /workspace
8
+ COPY data/ /workspace/data/
9
+
10
+ CMD ["/bin/bash"]
tasks/csv-canon/environment/data/orders.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ id,sku,qty,price
2
+ 3,SKU-9,2,1.50
3
+ 1,SKU-2,10,2
4
+ 2,SKU-1,5,1e3
5
+ 1,SKU-1,5,0.75
tasks/csv-canon/instruction.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `canon` — canonicalise a CSV export
2
+
3
+ Downstream tools need one boring, byte-stable TSV. Write an executable script at
4
+ `bin/canon` (shebang, `chmod +x`) that is invoked as:
5
+
6
+ ```
7
+ ./bin/canon <input.csv> <output.tsv>
8
+ ```
9
+
10
+ ## Input
11
+
12
+ UTF-8 CSV, possibly with a byte-order mark, possibly CRLF, RFC 4180 quoting:
13
+ fields may be quoted, may contain commas, doubled quotes (`""`) and embedded
14
+ newlines. The first record is the header.
15
+
16
+ ## Output
17
+
18
+ UTF-8 **without** a BOM, `\n` line endings, tab-separated, one line per record,
19
+ header first. Fields are written verbatim — never re-quoted, never trimmed —
20
+ except for the numeric normalisation below. Column order is preserved.
21
+
22
+ ## Numeric normalisation
23
+
24
+ A field is numeric when the whole field matches
25
+ `^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$`. Numeric fields are rewritten in
26
+ plain decimal notation with no exponent, no leading `+`, no leading zeros, and
27
+ no trailing zeros after the decimal point:
28
+
29
+ | input | output |
30
+ | --- | --- |
31
+ | `1.50` | `1.5` |
32
+ | `1.0` | `1` |
33
+ | `1e3` | `1000` |
34
+ | `2.5e-3` | `0.0025` |
35
+ | `+5` | `5` |
36
+ | `007` | `7` |
37
+ | `-0` | `0` |
38
+
39
+ Every other field is copied unchanged.
40
+
41
+ ## Ordering
42
+
43
+ Sort the data records by field 0, then by field 1, comparing the **normalised
44
+ strings** in byte order (so `"10"` sorts before `"9"`). The sort must be stable.
45
+
46
+ ## Errors
47
+
48
+ On any error, print exactly one line to stderr, exit with the given code, and do
49
+ **not** create the output file:
50
+
51
+ | condition | stderr line | exit |
52
+ | --- | --- | --- |
53
+ | input path does not exist | `no such file: <input path as given>` | `2` |
54
+ | two header names collide case-insensitively after trimming | `duplicate column: <name as written in the later header field>` | `3` |
55
+ | a record's field count differs from the header's | `malformed row: line <n>` | `4` |
56
+
57
+ `<n>` is the 1-based physical line number where the offending record starts
58
+ (so a record whose first line is the third line of the file reports `3`).
59
+
60
+ On success exit `0` and print nothing to stderr.
61
+
62
+ ## Notes
63
+
64
+ - `python` and `python3` are both on `PATH`; standard library only, no network.
65
+ - `data/orders.csv` is a sample with a BOM and CRLF endings.
tasks/csv-canon/solution/solve.sh ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle solution: csv module for RFC4180, Decimal for exact numeric rewriting.
3
+ set -euo pipefail
4
+ cd "$TB_WORK"
5
+ mkdir -p bin
6
+
7
+ cat > bin/canon <<'PYEOF'
8
+ #!/usr/bin/env python3
9
+ import csv
10
+ import re
11
+ import sys
12
+ from decimal import Decimal, InvalidOperation
13
+ from pathlib import Path
14
+
15
+ NUMERIC = re.compile(r"^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$")
16
+
17
+
18
+ def normalize(cell):
19
+ if not NUMERIC.match(cell):
20
+ return cell
21
+ try:
22
+ value = Decimal(cell)
23
+ except InvalidOperation:
24
+ return cell
25
+ if value == 0:
26
+ return "0"
27
+ return format(value.normalize(), "f")
28
+
29
+
30
+ def main(argv):
31
+ if len(argv) != 3:
32
+ sys.stderr.write("usage: canon <input.csv> <output.tsv>\n")
33
+ return 1
34
+ source = Path(argv[1])
35
+ target = Path(argv[2])
36
+ if not source.is_file():
37
+ sys.stderr.write("no such file: %s\n" % argv[1])
38
+ return 2
39
+
40
+ with open(source, "r", encoding="utf-8-sig", newline="") as handle:
41
+ reader = csv.reader(handle)
42
+ header = next(reader, None)
43
+ if header is None:
44
+ header = []
45
+ header = [name.strip() for name in header]
46
+
47
+ seen = set()
48
+ for name in header:
49
+ key = name.casefold()
50
+ if key in seen:
51
+ sys.stderr.write("duplicate column: %s\n" % name)
52
+ return 3
53
+ seen.add(key)
54
+
55
+ rows = []
56
+ previous_line = reader.line_num
57
+ for record in reader:
58
+ start = previous_line + 1
59
+ previous_line = reader.line_num
60
+ if not record:
61
+ continue
62
+ if len(record) != len(header):
63
+ sys.stderr.write("malformed row: line %d\n" % start)
64
+ return 4
65
+ rows.append([normalize(cell) for cell in record])
66
+
67
+ rows.sort(key=lambda row: (row[0], row[1] if len(row) > 1 else ""))
68
+
69
+ target.parent.mkdir(parents=True, exist_ok=True)
70
+ with open(target, "w", encoding="utf-8", newline="") as handle:
71
+ handle.write("\t".join(header) + "\n")
72
+ for row in rows:
73
+ handle.write("\t".join(row) + "\n")
74
+ return 0
75
+
76
+
77
+ if __name__ == "__main__":
78
+ sys.exit(main(sys.argv))
79
+ PYEOF
80
+
81
+ chmod +x bin/canon
82
+ ./bin/canon data/orders.csv out/orders.tsv
tasks/csv-canon/tests/test.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the
3
+ # reward signal (0 = solved).
4
+ set -uo pipefail
5
+ cd "$TB_ROOT/tests"
6
+ python -m pytest -v --tb=short -p no:cacheprovider test_outputs.py
tasks/csv-canon/tests/test_outputs.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from pathlib import Path
4
+
5
+ WORK = Path(os.environ["TB_WORK"])
6
+ BASH = os.environ.get("TB_BASH", "bash")
7
+ CANON = "./bin/canon"
8
+
9
+
10
+ def run_canon(source, target):
11
+ return subprocess.run(
12
+ [BASH, "-c", 'exec ./bin/canon "$@"', "canon", str(source), str(target)],
13
+ cwd=str(WORK),
14
+ capture_output=True,
15
+ text=True,
16
+ encoding="utf-8",
17
+ )
18
+
19
+
20
+ def case_dir():
21
+ path = Path(os.environ["TB_ROOT"]) / "tmp" / "cases"
22
+ path.mkdir(parents=True, exist_ok=True)
23
+ return path
24
+
25
+
26
+ def write_case(name, body, newline=""):
27
+ path = case_dir() / name
28
+ with open(path, "w", encoding="utf-8", newline=newline) as handle:
29
+ handle.write(body)
30
+ return path
31
+
32
+
33
+ def test_missing_input_exits_2():
34
+ target = case_dir() / "missing.tsv"
35
+ if target.exists():
36
+ target.unlink()
37
+ proc = run_canon("does-not-exist.csv", target)
38
+ assert proc.returncode == 2, proc.stderr
39
+ assert proc.stderr.strip() == "no such file: does-not-exist.csv"
40
+ assert not target.exists(), "output must not be created on error"
41
+
42
+
43
+ def test_duplicate_column_exits_3():
44
+ source = write_case("dup.csv", "id,ID\n1,2\n")
45
+ target = case_dir() / "dup.tsv"
46
+ if target.exists():
47
+ target.unlink()
48
+ proc = run_canon(source, target)
49
+ assert proc.returncode == 3, proc.stderr
50
+ assert proc.stderr.strip() == "duplicate column: ID"
51
+ assert not target.exists()
52
+
53
+
54
+ def test_malformed_row_exits_4_with_physical_line():
55
+ source = write_case("bad.csv", "id,sku\n1,a\n2,b,c\n")
56
+ target = case_dir() / "bad.tsv"
57
+ if target.exists():
58
+ target.unlink()
59
+ proc = run_canon(source, target)
60
+ assert proc.returncode == 4, proc.stderr
61
+ assert proc.stderr.strip() == "malformed row: line 3"
62
+ assert not target.exists()
63
+
64
+
65
+ def test_orders_sample_is_canonicalised():
66
+ target = case_dir() / "orders.tsv"
67
+ proc = run_canon("data/orders.csv", target)
68
+ assert proc.returncode == 0, proc.stderr
69
+ expected = (
70
+ "id\tsku\tqty\tprice\n"
71
+ "1\tSKU-1\t5\t0.75\n"
72
+ "1\tSKU-2\t10\t2\n"
73
+ "2\tSKU-1\t5\t1000\n"
74
+ "3\tSKU-9\t2\t1.5\n"
75
+ )
76
+ assert target.read_bytes() == expected.encode("utf-8")
77
+
78
+
79
+ def test_output_has_no_bom_and_uses_lf():
80
+ target = case_dir() / "orders.tsv"
81
+ run_canon("data/orders.csv", target)
82
+ raw = target.read_bytes()
83
+ assert not raw.startswith(b"\xef\xbb\xbf")
84
+ assert b"\r" not in raw
85
+
86
+
87
+ def test_embedded_newline_survives():
88
+ source = write_case("multi.csv", 'id,note\n2,"line one\nline two"\n1,plain\n')
89
+ target = case_dir() / "multi.tsv"
90
+ proc = run_canon(source, target)
91
+ assert proc.returncode == 0, proc.stderr
92
+ expected = "id\tnote\n1\tplain\n2\tline one\nline two\n"
93
+ assert target.read_bytes() == expected.encode("utf-8")
94
+
95
+
96
+ def test_numeric_normalisation():
97
+ source = write_case(
98
+ "nums.csv", "id,v\n1,+5\n2,007\n3,-0\n4,1.0\n5,2.5e-3\n6,abc\n"
99
+ )
100
+ target = case_dir() / "nums.tsv"
101
+ proc = run_canon(source, target)
102
+ assert proc.returncode == 0, proc.stderr
103
+ expected = "id\tv\n1\t5\n2\t7\n3\t0\n4\t1\n5\t0.0025\n6\tabc\n"
104
+ assert target.read_bytes() == expected.encode("utf-8")
105
+
106
+
107
+ def test_sorting_is_byte_order_not_numeric():
108
+ source = write_case("ids.csv", "id,x\n10,a\n9,b\n")
109
+ target = case_dir() / "ids.tsv"
110
+ proc = run_canon(source, target)
111
+ assert proc.returncode == 0, proc.stderr
112
+ assert target.read_bytes() == b"id\tx\n10\ta\n9\tb\n"
tasks/git-recovery/environment/Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13-slim
2
+
3
+ RUN apt-get update && apt-get install -y --no-install-recommends \
4
+ bash coreutils git \
5
+ && rm -rf /var/lib/apt/lists/*
6
+
7
+ WORKDIR /workspace
8
+ COPY setup.sh /tmp/setup.sh
9
+ RUN bash /tmp/setup.sh
10
+
11
+ CMD ["/bin/bash"]
tasks/git-recovery/environment/setup.sh ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Builds the broken repository state. This is the Dockerfile's analogue: it
3
+ # constructs the environment the agent wakes up in, deterministically.
4
+ set -euo pipefail
5
+ cd "$TB_WORK"
6
+
7
+ git init -q -b main
8
+ git config user.name "Release Bot"
9
+ git config user.email "release@example.invalid"
10
+ git config commit.gpgsign false
11
+ git config core.autocrlf false
12
+
13
+ mkdir -p src
14
+ cat > src/app.py <<'EOF'
15
+ VERSION = 1
16
+
17
+
18
+ def main():
19
+ return "v1"
20
+ EOF
21
+ git add -A
22
+ git commit -qm "Initial import"
23
+
24
+ mkdir -p notes
25
+ cat > notes/plan.md <<'EOF'
26
+ # Plan
27
+
28
+ - step one: wire up the loader
29
+ EOF
30
+ git add -A
31
+ git commit -qm "Add plan notes"
32
+
33
+ cat > src/app.py <<'EOF'
34
+ VERSION = 2
35
+
36
+ DEFAULTS = {"retries": 3, "timeout": 30}
37
+
38
+
39
+ def main():
40
+ return "v2"
41
+
42
+
43
+ def load(path):
44
+ with open(path, "r", encoding="utf-8") as handle:
45
+ return handle.read()
46
+ EOF
47
+ git add -A
48
+ git commit -qm "Add config loader"
49
+
50
+ git rm -q src/app.py
51
+ git commit -qm "Drop legacy module"
52
+
53
+ mkdir -p docs
54
+ cat > docs/build.md <<'EOF'
55
+ # Build
56
+
57
+ Run `make build`.
58
+ EOF
59
+ git add -A
60
+ git commit -qm "Document build"
61
+
62
+ # An abandoned experiment: a commit on a branch that is then deleted, leaving
63
+ # the commit unreachable from every ref.
64
+ git checkout -q -b wip HEAD~2
65
+ cat > notes/plan.md <<'EOF'
66
+ # Plan
67
+
68
+ - step one: wire up the loader
69
+ - step two: add retry budget (work in progress)
70
+ EOF
71
+ git add -A
72
+ git commit -qm "wip: plan"
73
+ git checkout -q main
74
+ git branch -qD wip
75
+
76
+ # Untracked junk that must end up ignored, not deleted.
77
+ printf 'starting\n' > debug.log
78
+ mkdir -p build
79
+ printf 'object file\n' > build/tmp.o
tasks/git-recovery/instruction.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Recover a broken release repository
2
+
3
+ The git repository in the workspace was left in a mess after a bad afternoon.
4
+ `main` currently has five commits, but the module `src/app.py` was deleted by the
5
+ `Drop legacy module` commit and nobody kept a copy. An experiment that was never
6
+ merged lives on as an unreachable commit whose message is `wip: plan`.
7
+
8
+ Fix the repository. When you are done it must satisfy all of the following.
9
+
10
+ ## 1. Restore the module
11
+
12
+ `src/app.py` must exist again with **exactly** the content it had in the commit
13
+ titled `Add config loader` (not the older `Initial import` version), and it must
14
+ be committed on `main` in a commit whose message is exactly:
15
+
16
+ ```
17
+ restore app.py
18
+ ```
19
+
20
+ ## 2. Rescue the abandoned experiment
21
+
22
+ Create a branch named `recovered` that points at the unreachable commit whose
23
+ message is `wip: plan`. That commit must **not** become an ancestor of `main`,
24
+ and it must still carry the work-in-progress version of `notes/plan.md`.
25
+
26
+ ## 3. Tag the release
27
+
28
+ Create an annotated-or-lightweight tag `v1.0` pointing at the commit titled
29
+ `Add config loader`.
30
+
31
+ ## 4. Ignore the junk, don't delete it
32
+
33
+ The workspace has two untracked artefacts, `debug.log` and `build/tmp.o`. Add a
34
+ `.gitignore` so that both are ignored, commit it, and leave the files on disk.
35
+
36
+ ## 5. Clean tree
37
+
38
+ `git status --porcelain` must print nothing.
39
+
40
+ ## Constraints
41
+
42
+ - Do not rewrite or discard the five existing commits on `main`; all five
43
+ original commit subjects must still be present in `git log main`. In
44
+ particular do not `reset` `main` backwards.
45
+ - Do not delete `debug.log` or `build/tmp.o`.
46
+ - No network access; everything you need is already in `.git`.
tasks/git-recovery/solution/solve.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle solution: find the lost commit through fsck, recover the file from the
3
+ # right historical revision, tag, ignore and commit.
4
+ set -euo pipefail
5
+ cd "$TB_WORK"
6
+
7
+ git config user.name "Release Bot"
8
+ git config user.email "release@example.invalid"
9
+
10
+ # 1. restore src/app.py from "Add config loader"
11
+ loader_commit="$(git log --format='%H %s' main | awk '$0 ~ / Add config loader$/ {print $1}' | head -1)"
12
+ test -n "$loader_commit"
13
+ mkdir -p src
14
+ git show "$loader_commit:src/app.py" > src/app.py
15
+
16
+ # 4. ignore the junk
17
+ cat > .gitignore <<'EOF'
18
+ *.log
19
+ build/
20
+ EOF
21
+
22
+ git add -A
23
+ git commit -qm "restore app.py"
24
+
25
+ # 2. rescue the unreachable commit
26
+ wip_commit="$(git fsck --unreachable --no-reflogs 2>/dev/null | awk '$2 == "commit" {print $3}' | while read -r sha; do
27
+ if [ "$(git log -1 --format=%s "$sha" 2>/dev/null)" = "wip: plan" ]; then
28
+ echo "$sha"
29
+ break
30
+ fi
31
+ done)"
32
+ test -n "$wip_commit"
33
+ git branch recovered "$wip_commit"
34
+
35
+ # 3. tag the release commit
36
+ git tag v1.0 "$loader_commit"
37
+
38
+ git status --porcelain
tasks/git-recovery/tests/test.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Verifier entrypoint. Runs the pytest suite and lets its exit code stand as the
3
+ # reward signal (0 = solved).
4
+ set -uo pipefail
5
+ cd "$TB_ROOT/tests"
6
+ python -m pytest -v --tb=short -p no:cacheprovider test_outputs.py
tasks/git-recovery/tests/test_outputs.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from pathlib import Path
4
+
5
+ WORK = Path(os.environ["TB_WORK"])
6
+
7
+ EXPECTED_APP = '''VERSION = 2
8
+
9
+ DEFAULTS = {"retries": 3, "timeout": 30}
10
+
11
+
12
+ def main():
13
+ return "v2"
14
+
15
+
16
+ def load(path):
17
+ with open(path, "r", encoding="utf-8") as handle:
18
+ return handle.read()
19
+ '''
20
+
21
+ ORIGINAL_SUBJECTS = [
22
+ "Initial import",
23
+ "Add plan notes",
24
+ "Add config loader",
25
+ "Drop legacy module",
26
+ "Document build",
27
+ ]
28
+
29
+
30
+ def git(*args):
31
+ return subprocess.run(
32
+ ["git"] + list(args),
33
+ cwd=str(WORK),
34
+ capture_output=True,
35
+ text=True,
36
+ encoding="utf-8",
37
+ )
38
+
39
+
40
+ def subjects():
41
+ result = git("log", "--format=%s", "main")
42
+ assert result.returncode == 0, result.stderr
43
+ return [line for line in result.stdout.splitlines() if line]
44
+
45
+
46
+ def test_app_py_restored_from_config_loader_commit():
47
+ path = WORK / "src" / "app.py"
48
+ assert path.is_file(), "src/app.py was not restored"
49
+ assert path.read_text(encoding="utf-8") == EXPECTED_APP
50
+
51
+
52
+ def test_restore_commit_message():
53
+ assert "restore app.py" in subjects()
54
+
55
+
56
+ def test_app_py_is_committed_not_just_written():
57
+ result = git("ls-files", "--error-unmatch", "src/app.py")
58
+ assert result.returncode == 0, "src/app.py is not tracked"
59
+
60
+
61
+ def test_recovered_branch_points_at_the_wip_commit():
62
+ ref = git("rev-parse", "--verify", "refs/heads/recovered")
63
+ assert ref.returncode == 0, "branch 'recovered' does not exist"
64
+ message = git("log", "-1", "--format=%s", "recovered")
65
+ assert message.stdout.strip() == "wip: plan"
66
+
67
+
68
+ def test_recovered_is_not_an_ancestor_of_main():
69
+ ref = git("rev-parse", "--verify", "refs/heads/recovered")
70
+ assert ref.returncode == 0, "branch 'recovered' does not exist"
71
+ result = git("merge-base", "--is-ancestor", "recovered", "main")
72
+ assert result.returncode == 1, "the rescued commit must stay off main"
73
+
74
+
75
+ def test_recovered_commit_keeps_the_work_in_progress_plan():
76
+ blob = git("show", "recovered:notes/plan.md")
77
+ assert blob.returncode == 0, "recovered commit has no notes/plan.md"
78
+ assert "step two" in blob.stdout
79
+
80
+
81
+ def test_tag_v1_points_at_the_config_loader_commit():
82
+ tag = git("rev-list", "-n", "1", "v1.0")
83
+ assert tag.returncode == 0, "tag v1.0 does not exist"
84
+ subject = git("log", "-1", "--format=%s", tag.stdout.strip())
85
+ assert subject.stdout.strip() == "Add config loader"
86
+
87
+
88
+ def test_junk_is_ignored_but_still_present():
89
+ for rel in ("debug.log", "build/tmp.o"):
90
+ assert (WORK / rel).is_file(), "%s was deleted" % rel
91
+ result = git("check-ignore", "-q", rel)
92
+ assert result.returncode == 0, "%s is not ignored" % rel
93
+
94
+
95
+ def test_worktree_is_clean():
96
+ status = git("status", "--porcelain")
97
+ assert status.stdout.strip() == "", "dirty tree:\n%s" % status.stdout
98
+
99
+
100
+ def test_original_history_is_preserved():
101
+ current = subjects()
102
+ for subject in ORIGINAL_SUBJECTS:
103
+ assert subject in current, "commit %r disappeared from main" % subject
tools/make_controls.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate a negative control: a plausible but incomplete attempt per task.
2
+
3
+ Every task must score 0.0. This is the check that the verifier is measuring the
4
+ whole task rather than one easy assertion.
5
+
6
+ The controls are produced by mutating the oracle: the interesting failure mode
7
+ for an agent is not "did nothing" but "fixed the obvious half".
8
+
9
+ Run with: python tools/make_controls.py
10
+ """
11
+
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ ROOT = Path(__file__).resolve().parent.parent
17
+ DATASET = ROOT / "TerminalBench-DockerLess.jsonl"
18
+ OUTDIR = ROOT / "predictions"
19
+
20
+
21
+ def mutate(text, old, new, label):
22
+ if old not in text:
23
+ raise SystemExit("control %s: anchor not found" % label)
24
+ return text.replace(old, new)
25
+
26
+
27
+ def build_controls(rows):
28
+ by_id = {row["task_id"]: row for row in rows}
29
+ controls = {}
30
+
31
+ # 1. access-log: nearest-rank replaced by a 0-based index -> p95 is off by one
32
+ # rank, everything else is right.
33
+ solution = by_id["tbdl-access-log-report"]["solution"]
34
+ controls["tbdl-access-log-report"] = mutate(
35
+ solution,
36
+ "p95 = durations[math.ceil(0.95 * count) - 1] if count else 0",
37
+ "p95 = durations[int(round(0.95 * count)) - 1] if count else 0",
38
+ "access-log",
39
+ )
40
+
41
+ # 2. git-recovery: recovers the *wrong* historical revision and never
42
+ # rescues the unreachable commit.
43
+ solution = by_id["tbdl-git-recovery"]["solution"]
44
+ solution = mutate(solution, "/ Add config loader$/", "/ Initial import$/", "git-recovery")
45
+ solution = mutate(
46
+ solution, 'git branch recovered "$wip_commit"', "true # gave up on the wip commit", "git-recovery-2"
47
+ )
48
+ controls["tbdl-git-recovery"] = solution
49
+
50
+ # 3. csv-canon: forgets the BOM and forgets to sort.
51
+ solution = by_id["tbdl-csv-canon"]["solution"]
52
+ solution = mutate(solution, 'encoding="utf-8-sig"', 'encoding="utf-8"', "csv-canon")
53
+ solution = mutate(
54
+ solution,
55
+ 'rows.sort(key=lambda row: (row[0], row[1] if len(row) > 1 else ""))',
56
+ "pass # rows arrive sorted, surely",
57
+ "csv-canon-2",
58
+ )
59
+ controls["tbdl-csv-canon"] = solution
60
+
61
+ # 4. build-repair: fixes the shell bugs only, leaving both Python faults.
62
+ controls["tbdl-build-repair"] = """#!/usr/bin/env bash
63
+ set -euo pipefail
64
+ cd "$TB_WORK"
65
+ python - <<'PYEOF'
66
+ from pathlib import Path
67
+ path = Path("build.sh")
68
+ text = path.read_text(encoding="utf-8")
69
+ text = text.replace('mkdir -p "$OUTDIR"', 'mkdir -p "$OUT" build')
70
+ path.write_text(text, encoding="utf-8", newline="\\n")
71
+ PYEOF
72
+ bash build.sh || true
73
+ """
74
+ return controls
75
+
76
+
77
+ def main():
78
+ OUTDIR.mkdir(exist_ok=True)
79
+ rows = [json.loads(line) for line in open(DATASET, encoding="utf-8") if line.strip()]
80
+ controls = build_controls(rows)
81
+ target = OUTDIR / "partial.jsonl"
82
+ with open(target, "w", encoding="utf-8", newline="\n") as handle:
83
+ for row in rows:
84
+ handle.write(
85
+ json.dumps(
86
+ {
87
+ "task_id": row["task_id"],
88
+ "agent_name": "control-partial",
89
+ "agent_script": controls[row["task_id"]],
90
+ }
91
+ )
92
+ + "\n"
93
+ )
94
+ print("wrote %s for %d tasks" % (target, len(rows)))
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
tools/mk_access_log.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the access.log fixture for the access-log-report task.
2
+
3
+ Deterministic: same bytes every run. The fixture is deliberately awkward --
4
+ one user-agent carries escaped quotes, two byte counts are "-", four lines are
5
+ malformed in four different ways, and four request paths carry query strings.
6
+
7
+ Run with: python tools/mk_access_log.py
8
+ """
9
+
10
+ from pathlib import Path
11
+
12
+ OUT = (
13
+ Path(__file__).resolve().parent.parent
14
+ / "tasks"
15
+ / "access-log-report"
16
+ / "environment"
17
+ / "logs"
18
+ / "access.log"
19
+ )
20
+
21
+ MS = [
22
+ 3, 7, 11, 12, 14, 18, 21, 25, 28, 31, 35, 40, 44, 47, 52, 55, 58, 61,
23
+ 66, 70, 74, 78, 82, 85, 90, 95, 99, 104, 110, 118, 126, 133, 141, 150,
24
+ 162, 175,
25
+ ]
26
+
27
+ PATHS = (
28
+ ["/index.html"] * 12
29
+ + ["/api/users"] * 8
30
+ + ["/api/users?id=42"] * 4
31
+ + ["/static/app.js"] * 6
32
+ + ["/health"] * 3
33
+ + ["/api/orders"] * 3
34
+ )
35
+
36
+ STATUS = [200] * 28 + [304] * 4 + [404] * 3 + [500]
37
+
38
+ MALFORMED = {
39
+ 7: '10.0.0.9 - - [10/Oct/2026:13:02:11 +0000] "GET /index.html HTTP/1.1" 200 512 "-" "curl/8.0"',
40
+ 19: '10.0.0.3 - - [10/Oct/2026:13:05:44 +0000] "POST /api/users HTTP/1.1" abc 300 "-" "curl/8.0" 44',
41
+ 28: '10.0.0.4 - - [10/Oct/2026:13:09:02 +0000] "GET /health HTTP/1.1" 200 0',
42
+ 37: "# rotated by logrotate at 2026-10-10T14:00:00Z",
43
+ }
44
+
45
+ UA_WEIRD = 'Mozilla/5.0 (\\"compatible\\"; bot) Gecko/20100101'
46
+
47
+
48
+ def build():
49
+ valid = []
50
+ for index in range(36):
51
+ path = PATHS[index]
52
+ method = "GET"
53
+ if path == "/api/users" and index % 5 == 0:
54
+ method = "POST"
55
+ status = STATUS[index]
56
+ if index in (9, 26):
57
+ size = "-"
58
+ else:
59
+ size = str(200 + index * 13)
60
+ ms = MS[(index * 7) % 36]
61
+ referer = "-" if index % 4 == 0 else "https://example.com/"
62
+ ua = UA_WEIRD if index in (5, 17) else "curl/8.5.0"
63
+ line = (
64
+ '10.0.0.%d - - [10/Oct/2026:13:%02d:%02d +0000] "%s %s HTTP/1.1" %d %s "%s" "%s" %d'
65
+ % (index % 9 + 1, index // 2, (index * 17) % 60, method, path, status, size, referer, ua, ms)
66
+ )
67
+ valid.append(line)
68
+ return valid
69
+
70
+
71
+ def main():
72
+ lines = build()
73
+ out = []
74
+ source = iter(lines)
75
+ for position in range(1, 41):
76
+ if position in MALFORMED:
77
+ out.append(MALFORMED[position])
78
+ else:
79
+ out.append(next(source))
80
+ OUT.parent.mkdir(parents=True, exist_ok=True)
81
+ with open(OUT, "w", encoding="utf-8", newline="\n") as handle:
82
+ handle.write("\n".join(out) + "\n")
83
+ print("wrote %s (%d lines, %d valid)" % (OUT, len(out), len(lines)))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
tools/validate.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structural validation for TerminalBench-DockerLess.jsonl.
2
+
3
+ Checks that every row carries the classic Terminal-Bench task.yaml fields and the
4
+ Harbor task.toml rendering, that the embedded task directory is complete, that
5
+ the verifier and instruction do not leak each other, and that every task is
6
+ non-trivial (something must fail before any agent acts).
7
+
8
+ Run with: python tools/validate.py
9
+ """
10
+
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ ROOT = Path(__file__).resolve().parent.parent
16
+ DATASET = ROOT / "TerminalBench-DockerLess.jsonl"
17
+
18
+ TB_FIELDS = [
19
+ "task_id",
20
+ "instruction",
21
+ "author_name",
22
+ "author_email",
23
+ "difficulty",
24
+ "category",
25
+ "tags",
26
+ "parser_name",
27
+ "max_agent_timeout_sec",
28
+ "max_test_timeout_sec",
29
+ "expert_time_estimate_min",
30
+ "junior_time_estimate_min",
31
+ "task_yaml",
32
+ "task_toml",
33
+ "dockerfile",
34
+ "solution",
35
+ "tests",
36
+ "dockerless",
37
+ ]
38
+
39
+ REQUIRED_FILES = ["instruction.md", "environment/Dockerfile", "solution/solve.sh", "tests/test.sh"]
40
+
41
+ MAX_INSTRUCTION_CHARS = 4000
42
+ MIN_AGENT_TIMEOUT = 60
43
+ MIN_TEST_TIMEOUT = 30
44
+
45
+ failures = []
46
+
47
+
48
+ def check(condition, message):
49
+ if not condition:
50
+ failures.append(message)
51
+
52
+
53
+ def main():
54
+ rows = [json.loads(line) for line in open(DATASET, encoding="utf-8") if line.strip()]
55
+ check(len(rows) == 4, "expected 4 rows, found %d" % len(rows))
56
+
57
+ seen = set()
58
+ for row in rows:
59
+ tid = row.get("task_id", "<missing>")
60
+ for field in TB_FIELDS:
61
+ check(field in row, "%s: missing field %s" % (tid, field))
62
+ check(tid not in seen, "%s: duplicate task_id" % tid)
63
+ seen.add(tid)
64
+
65
+ instruction = row["instruction"]
66
+ check(len(instruction.strip()) > 200, "%s: instruction too short" % tid)
67
+ check(len(instruction) <= MAX_INSTRUCTION_CHARS, "%s: instruction too long" % tid)
68
+ check("::" not in instruction, "%s: instruction leaks a test node id" % tid)
69
+ check("test_outputs" not in instruction, "%s: instruction names the verifier file" % tid)
70
+
71
+ check(row["parser_name"] == "pytest", "%s: parser_name must be pytest" % tid)
72
+ check(row["difficulty"] in ("easy", "medium", "hard"), "%s: bad difficulty" % tid)
73
+ check(row["max_agent_timeout_sec"] >= MIN_AGENT_TIMEOUT, "%s: agent timeout too small" % tid)
74
+ check(row["max_test_timeout_sec"] >= MIN_TEST_TIMEOUT, "%s: test timeout too small" % tid)
75
+
76
+ yaml = row["task_yaml"]
77
+ for needle in ("instruction: |", "parser_name: pytest", "difficulty: ", "max_agent_timeout_sec:"):
78
+ check(needle in yaml, "%s: task_yaml missing %r" % (tid, needle))
79
+ toml = row["task_toml"]
80
+ for needle in ('schema_version = "1.4"', "[verifier]", "[agent]", "[environment]"):
81
+ check(needle in toml, "%s: task_toml missing %r" % (tid, needle))
82
+
83
+ tests = row["tests"]
84
+ check("test.sh" in tests, "%s: tests/test.sh missing" % tid)
85
+ check("test_outputs.py" in tests, "%s: tests/test_outputs.py missing" % tid)
86
+ check(row["solution"].strip() != "", "%s: empty solution" % tid)
87
+ check("FROM " in row["dockerfile"], "%s: dockerfile does not look like a Dockerfile" % tid)
88
+
89
+ dockerless = row["dockerless"]
90
+ files = dockerless["files"]
91
+ for rel in files:
92
+ check(not rel.startswith("/"), "%s: absolute path in snapshot: %s" % (tid, rel))
93
+ check(".." not in Path(rel).parts, "%s: escaping path in snapshot: %s" % (tid, rel))
94
+ check("Dockerfile" not in files, "%s: snapshot contains the Dockerfile" % tid)
95
+ check("setup.sh" not in files, "%s: snapshot contains setup.sh" % tid)
96
+
97
+ check(
98
+ bool(dockerless["baseline_failures"]),
99
+ "%s: nothing fails before the agent acts" % tid,
100
+ )
101
+ check(
102
+ bool(dockerless.get("setup", "").strip()) or bool(files),
103
+ "%s: task has neither setup script nor files" % tid,
104
+ )
105
+
106
+ print(
107
+ "%-24s %-6s files=%-2d tests=%-2d baseline_fail=%-2d instr=%d chars"
108
+ % (
109
+ tid,
110
+ row["difficulty"],
111
+ len(files),
112
+ len(tests) - 1,
113
+ len(dockerless["baseline_failures"]),
114
+ len(instruction),
115
+ )
116
+ )
117
+
118
+ total_chars = DATASET.stat().st_size
119
+ print("\n%d tasks, %.1f KiB (~%d tokens)" % (len(rows), total_chars / 1024.0, total_chars // 4))
120
+ if failures:
121
+ print("\nFAILED %d checks:" % len(failures))
122
+ for message in failures:
123
+ print(" - %s" % message)
124
+ return 1
125
+ print("all checks passed")
126
+ return 0
127
+
128
+
129
+ if __name__ == "__main__":
130
+ sys.exit(main())