rca-umb commited on
Commit
e042d72
·
verified ·
1 Parent(s): 3cddd02

Five Desks Code: tasks, calibration and source

Browse files
README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pretty_name: Five Desks Code (OpenEnv environment)
4
+ tags:
5
+ - openenv
6
+ - reinforcement-learning
7
+ - rl-environment
8
+ - tool-use
9
+ - agents
10
+ - software-engineering
11
+ configs:
12
+ - config_name: default
13
+ data_files:
14
+ - split: train
15
+ path: tasks.jsonl
16
+ ---
17
+
18
+ # Five Desks Code: agentic coding on real libraries from every domain
19
+
20
+ Five Desks Code is an [OpenEnv](https://github.com/meta-pytorch/OpenEnv) environment for the
21
+ [OpenEnv Arena](https://openenvarena-arena.hf.space/). Every task is real agentic software work: explore an
22
+ unfamiliar repository, reproduce a problem, read code, run things, change code, check that nothing else broke, and
23
+ submit. The repositories are pinned releases of open-source Python libraries from the arena's eight domains, so the
24
+ coding happens inside finance, science, scheduling, subtitles, signing, pipe-flow and media code, and the media
25
+ tasks use real production tools (ffmpeg, ImageMagick, Pillow).
26
+
27
+ Why coding: RL on software tasks has been reported to carry over to other reasoning tasks (for example SWE-RL), and on this arena's own
28
+ leaderboard the software-repair runs that had a learning signal averaged 4.0/40 against about 3.0 for all runs,
29
+ including two of the three best single runs (a gap inside the 1 to 4 that runs with no learning at all have scored,
30
+ so it is a hunch, not evidence). Three runs of our own narrower diligence tasks (Five Desks v1-v3) learned
31
+ their tasks and scored 2, 2 and 1 out of 40.
32
+
33
+ - **Image:** `ghcr.io/rca-umb/five-desks` (code tag, linux/amd64, public); the arena pins the digest.
34
+ - **Source:** [`source/`](./source): environment, tests, the catalog builder and the calibration code.
35
+
36
+ ## Tasks
37
+
38
+ **Bug fixing (`bugfix-<domain>-l1|l2`).** Each instance takes one library and one bug from a build-time catalog of
39
+ 525: a single token changed inside a function (a comparison, an operator, a constant, `and`/`or`, a `not`) that
40
+ 1 to 8 of the library's own tests catch. The catalog builder plants every candidate change in a container, runs the
41
+ library's test suite, keeps the changes the tests catch, and then checks each one inside the final image (the
42
+ untouched repository must fail, the original code must pass, at both levels). Level 1 is a failing CI run: the issue
43
+ shows the failing test's output and the suite is in the repository. Level 2 is a user report: the issue shows only
44
+ the failing check, and the tests that cover it are removed, so the policy has to reproduce, locate and verify on its
45
+ own.
46
+
47
+ **Media production (`media-production-l1|l2`).** Each instance generates its own media and a client spec plus
48
+ production notes that add one requirement the spec does not mention: a trimmed, scaled clip (with or without a mono
49
+ audio track), square thumbnails from photos rotated by EXIF (skipping placeholders), a contact sheet ordered by
50
+ capture time, or a loudness-normalised FLAC delivery (with or without the leading silence).
51
+
52
+ Tools (names and argument names are drawn per episode, e.g. `read_file`/`cat`/`open_file`, so the policy has to read
53
+ the tool list): list files, read a file with line numbers, search with a regular expression, replace an exact
54
+ snippet, write a file, run a shell command (60 s), run pytest (100 s), submit. One generic action for everything:
55
+ `{"tool": "<name>", "args": {...}}`.
56
+
57
+ ## Reward and grading
58
+
59
+ All or nothing. A bug fix scores 1 only if every catching test passes and no other test in those files fails that
60
+ passes on the original library. Grading copies only the library's own source files from the workspace into a clean
61
+ copy of the original project and runs the original tests there, so edits to tests, configuration or `conftest.py`
62
+ change nothing, and a package containing symlinks scores 0. Media deliverables are measured, not trusted: stream
63
+ properties with ffprobe, the first frame against the right moment of the source, thumbnail and tile content against
64
+ references computed from a private copy of the inputs, and the peak level and start of the audio.
65
+
66
+ The policy's commands run as the unprivileged `nobody` user with CPU, memory, file-size and process limits; the
67
+ server, the bug catalog and the original sources are root-only. `source/codedesk/tests` checks: oracle 1 and
68
+ untouched 0 for every task id, test-file edits and conftest tricks score 0, symlinks out score 0, the catching tests
69
+ are absent at level 2, the policy cannot read the server, and a set of hostile tool calls (path escapes, a fork bomb,
70
+ endless output, killing the server) cannot escape or crash an episode.
71
+
72
+ ## Calibration (Qwen3.8-27B, thinking off, arena reply parsing)
73
+
74
+ HF Inference Providers (DeepInfra), temperature 1.0, arena-style system prompt with the action schema, budgets as
75
+ submitted, replies parsed by their first JSON object (which matched the arena's training rewards on our earlier
76
+ tasks). The trained tasks, one per domain plus media production:
77
+
78
+ | task id | domain | code | what the policy gets | solved by the untrained model |
79
+ |---|---|---|---|---|
80
+ | bugfix-office-l1 | office | croniter, isodate, humanize | failing CI test given | 0.56 (16) |
81
+ | bugfix-finance-l1 | finance | numpy-financial | failing CI test given | 0.50 (16) |
82
+ | bugfix-science-l1 | natural science | uncertainties | failing CI test given | 0.31 (16) |
83
+ | bugfix-industrial-l2 | industrial | fluids (pumps, valves, pipe flow, fittings) | user report only; catching tests removed | 0.38 (16) |
84
+ | bugfix-media-l2 | media | srt, webvtt-py, python-slugify | user report only; catching tests removed | 0.56 (16) |
85
+ | bugfix-security-l2 | cybersecurity | PyJWT, itsdangerous | user report only; catching tests removed | 0.50 (16) |
86
+ | bugfix-software-l2 | software engineering | toolz, tabulate, inflection | user report only; catching tests removed | 0.69 (16) |
87
+ | bugfix-math-l1 | math | more-itertools | failing CI test given | 0.50 (16) |
88
+ | media-production-l2 | media | ffmpeg, ImageMagick, Pillow | clip, thumbnails, contact sheet or audio delivery from spec.md + notes.md | 0.44 (16) |
89
+
90
+ All picked tasks have mixed outcomes, so GRPO groups carry signal. About a third of the losses are replies that are
91
+ not one valid action (arguments outside `args`, invalid JSON escapes in long code strings, prose with no action):
92
+ keeping tool calls well-formed while carrying code is part of what these tasks train. Episodes are long (about 13
93
+ tool calls), so a 4-hour run takes fewer optimizer steps than with short tasks.
94
+
95
+ ## Libraries
96
+
97
+ Pinned sources as published on PyPI, shipped with their licenses: croniter 6.2.4 (MIT), isodate 0.7.2 (BSD),
98
+ humanize 4.16.0 (MIT), numpy-financial 1.0.0 (BSD-3-Clause), uncertainties 3.2.3 (BSD-3-Clause), fluids 1.3.1 (MIT),
99
+ srt 3.5.3 (MIT), webvtt-py 0.5.1 (MIT), python-slugify 9.1.3 (MIT), PyJWT 2.15.1 (MIT), itsdangerous 2.2.0
100
+ (BSD-3-Clause), toolz 1.2.0 (BSD-3-Clause), tabulate 0.10.0 (MIT), inflection 0.5.1 (MIT), more-itertools 11.1.0 (MIT).
101
+ The bug catalog (which line was changed) is the answer key and is not published here; `source/codedesk/build`
102
+ rebuilds it from these versions.
calibration/r1_episodes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
calibration/r1_summary.json ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3.8-27B:deepinfra",
3
+ "lenient": true,
4
+ "episodes": 144,
5
+ "seconds": 1070,
6
+ "usage": {
7
+ "prompt_tokens": 13852782,
8
+ "completion_tokens": 233631,
9
+ "calls": 2124,
10
+ "empty_content": 115
11
+ },
12
+ "tasks": {
13
+ "bugfix-office-l1": {
14
+ "n": 8,
15
+ "mean": 0.5,
16
+ "solved": 4,
17
+ "rewards": [
18
+ 0.0,
19
+ 1.0,
20
+ 0.0,
21
+ 1.0,
22
+ 0.0,
23
+ 1.0,
24
+ 0.0,
25
+ 1.0
26
+ ],
27
+ "ends": {
28
+ "schema_invalid": 1,
29
+ "submitted": 4,
30
+ "empty": 1,
31
+ "no_json": 2
32
+ },
33
+ "turns": 13,
34
+ "rescued_replies": 23
35
+ },
36
+ "bugfix-office-l2": {
37
+ "n": 8,
38
+ "mean": 0.625,
39
+ "solved": 5,
40
+ "rewards": [
41
+ 0.0,
42
+ 1.0,
43
+ 0.0,
44
+ 0.0,
45
+ 1.0,
46
+ 1.0,
47
+ 1.0,
48
+ 1.0
49
+ ],
50
+ "ends": {
51
+ "no_json": 1,
52
+ "submitted": 6,
53
+ "budget": 1
54
+ },
55
+ "turns": 22.2,
56
+ "rescued_replies": 69
57
+ },
58
+ "bugfix-finance-l1": {
59
+ "n": 8,
60
+ "mean": 0.375,
61
+ "solved": 3,
62
+ "rewards": [
63
+ 1.0,
64
+ 0.0,
65
+ 0.0,
66
+ 1.0,
67
+ 0.0,
68
+ 1.0,
69
+ 0.0,
70
+ 0.0
71
+ ],
72
+ "ends": {
73
+ "submitted": 3,
74
+ "schema_invalid": 2,
75
+ "truncated": 1,
76
+ "no_json": 2
77
+ },
78
+ "turns": 7.9,
79
+ "rescued_replies": 18
80
+ },
81
+ "bugfix-finance-l2": {
82
+ "n": 8,
83
+ "mean": 0.125,
84
+ "solved": 1,
85
+ "rewards": [
86
+ 0.0,
87
+ 0.0,
88
+ 1.0,
89
+ 0.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 0.0
94
+ ],
95
+ "ends": {
96
+ "submitted": 3,
97
+ "out_of_steps": 1,
98
+ "no_json": 1,
99
+ "schema_invalid": 2,
100
+ "truncated": 1
101
+ },
102
+ "turns": 17.1,
103
+ "rescued_replies": 82
104
+ },
105
+ "bugfix-science-l1": {
106
+ "n": 8,
107
+ "mean": 0.25,
108
+ "solved": 2,
109
+ "rewards": [
110
+ 0.0,
111
+ 0.0,
112
+ 0.0,
113
+ 0.0,
114
+ 1.0,
115
+ 0.0,
116
+ 1.0,
117
+ 0.0
118
+ ],
119
+ "ends": {
120
+ "schema_invalid": 4,
121
+ "no_json": 1,
122
+ "budget": 1,
123
+ "submitted": 1,
124
+ "truncated": 1
125
+ },
126
+ "turns": 8.9,
127
+ "rescued_replies": 37
128
+ },
129
+ "bugfix-science-l2": {
130
+ "n": 8,
131
+ "mean": 0.25,
132
+ "solved": 2,
133
+ "rewards": [
134
+ 1.0,
135
+ 1.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0
142
+ ],
143
+ "ends": {
144
+ "submitted": 5,
145
+ "no_json": 1,
146
+ "out_of_steps": 1,
147
+ "schema_invalid": 1
148
+ },
149
+ "turns": 22.2,
150
+ "rescued_replies": 85
151
+ },
152
+ "bugfix-industrial-l1": {
153
+ "n": 8,
154
+ "mean": 0.875,
155
+ "solved": 7,
156
+ "rewards": [
157
+ 1.0,
158
+ 1.0,
159
+ 1.0,
160
+ 0.0,
161
+ 1.0,
162
+ 1.0,
163
+ 1.0,
164
+ 1.0
165
+ ],
166
+ "ends": {
167
+ "submitted": 7,
168
+ "no_json": 1
169
+ },
170
+ "turns": 13.6,
171
+ "rescued_replies": 59
172
+ },
173
+ "bugfix-industrial-l2": {
174
+ "n": 8,
175
+ "mean": 0.375,
176
+ "solved": 3,
177
+ "rewards": [
178
+ 0.0,
179
+ 1.0,
180
+ 0.0,
181
+ 0.0,
182
+ 1.0,
183
+ 0.0,
184
+ 1.0,
185
+ 0.0
186
+ ],
187
+ "ends": {
188
+ "schema_invalid": 2,
189
+ "submitted": 3,
190
+ "no_json": 2,
191
+ "out_of_steps": 1
192
+ },
193
+ "turns": 17.2,
194
+ "rescued_replies": 21
195
+ },
196
+ "bugfix-media-l1": {
197
+ "n": 8,
198
+ "mean": 0.375,
199
+ "solved": 3,
200
+ "rewards": [
201
+ 0.0,
202
+ 1.0,
203
+ 0.0,
204
+ 0.0,
205
+ 0.0,
206
+ 1.0,
207
+ 0.0,
208
+ 1.0
209
+ ],
210
+ "ends": {
211
+ "no_json": 2,
212
+ "submitted": 3,
213
+ "empty": 1,
214
+ "schema_invalid": 1,
215
+ "truncated": 1
216
+ },
217
+ "turns": 12.1,
218
+ "rescued_replies": 30
219
+ },
220
+ "bugfix-media-l2": {
221
+ "n": 8,
222
+ "mean": 0.375,
223
+ "solved": 3,
224
+ "rewards": [
225
+ 0.0,
226
+ 0.0,
227
+ 1.0,
228
+ 1.0,
229
+ 0.0,
230
+ 1.0,
231
+ 0.0,
232
+ 0.0
233
+ ],
234
+ "ends": {
235
+ "schema_invalid": 3,
236
+ "submitted": 4,
237
+ "budget": 1
238
+ },
239
+ "turns": 13.2,
240
+ "rescued_replies": 54
241
+ },
242
+ "bugfix-security-l1": {
243
+ "n": 8,
244
+ "mean": 0.75,
245
+ "solved": 6,
246
+ "rewards": [
247
+ 1.0,
248
+ 0.0,
249
+ 0.0,
250
+ 1.0,
251
+ 1.0,
252
+ 1.0,
253
+ 1.0,
254
+ 1.0
255
+ ],
256
+ "ends": {
257
+ "submitted": 6,
258
+ "no_json": 1,
259
+ "schema_invalid": 1
260
+ },
261
+ "turns": 10.6,
262
+ "rescued_replies": 27
263
+ },
264
+ "bugfix-security-l2": {
265
+ "n": 8,
266
+ "mean": 0.5,
267
+ "solved": 4,
268
+ "rewards": [
269
+ 1.0,
270
+ 0.0,
271
+ 1.0,
272
+ 1.0,
273
+ 0.0,
274
+ 1.0,
275
+ 0.0,
276
+ 0.0
277
+ ],
278
+ "ends": {
279
+ "submitted": 4,
280
+ "schema_invalid": 3,
281
+ "empty": 1
282
+ },
283
+ "turns": 12.2,
284
+ "rescued_replies": 50
285
+ },
286
+ "bugfix-software-l1": {
287
+ "n": 8,
288
+ "mean": 0.75,
289
+ "solved": 6,
290
+ "rewards": [
291
+ 1.0,
292
+ 1.0,
293
+ 1.0,
294
+ 1.0,
295
+ 1.0,
296
+ 0.0,
297
+ 1.0,
298
+ 0.0
299
+ ],
300
+ "ends": {
301
+ "submitted": 6,
302
+ "out_of_steps": 1,
303
+ "schema_invalid": 1
304
+ },
305
+ "turns": 17.8,
306
+ "rescued_replies": 68
307
+ },
308
+ "bugfix-software-l2": {
309
+ "n": 8,
310
+ "mean": 0.75,
311
+ "solved": 6,
312
+ "rewards": [
313
+ 1.0,
314
+ 1.0,
315
+ 1.0,
316
+ 1.0,
317
+ 0.0,
318
+ 0.0,
319
+ 1.0,
320
+ 1.0
321
+ ],
322
+ "ends": {
323
+ "submitted": 6,
324
+ "empty": 1,
325
+ "schema_invalid": 1
326
+ },
327
+ "turns": 12.2,
328
+ "rescued_replies": 46
329
+ },
330
+ "bugfix-math-l1": {
331
+ "n": 8,
332
+ "mean": 0.5,
333
+ "solved": 4,
334
+ "rewards": [
335
+ 1.0,
336
+ 1.0,
337
+ 1.0,
338
+ 0.0,
339
+ 0.0,
340
+ 1.0,
341
+ 0.0,
342
+ 0.0
343
+ ],
344
+ "ends": {
345
+ "submitted": 5,
346
+ "no_json": 1,
347
+ "schema_invalid": 2
348
+ },
349
+ "turns": 13.9,
350
+ "rescued_replies": 56
351
+ },
352
+ "bugfix-math-l2": {
353
+ "n": 8,
354
+ "mean": 0.375,
355
+ "solved": 3,
356
+ "rewards": [
357
+ 1.0,
358
+ 1.0,
359
+ 0.0,
360
+ 0.0,
361
+ 0.0,
362
+ 0.0,
363
+ 0.0,
364
+ 1.0
365
+ ],
366
+ "ends": {
367
+ "submitted": 4,
368
+ "out_of_steps": 2,
369
+ "schema_invalid": 1,
370
+ "no_json": 1
371
+ },
372
+ "turns": 21.4,
373
+ "rescued_replies": 49
374
+ },
375
+ "media-production-l1": {
376
+ "n": 8,
377
+ "mean": 0.375,
378
+ "solved": 3,
379
+ "rewards": [
380
+ 1.0,
381
+ 0.0,
382
+ 0.0,
383
+ 1.0,
384
+ 0.0,
385
+ 1.0,
386
+ 0.0,
387
+ 0.0
388
+ ],
389
+ "ends": {
390
+ "submitted": 7,
391
+ "no_json": 1
392
+ },
393
+ "turns": 8.5,
394
+ "rescued_replies": 3
395
+ },
396
+ "media-production-l2": {
397
+ "n": 8,
398
+ "mean": 0.5,
399
+ "solved": 4,
400
+ "rewards": [
401
+ 1.0,
402
+ 0.0,
403
+ 0.0,
404
+ 1.0,
405
+ 0.0,
406
+ 1.0,
407
+ 0.0,
408
+ 1.0
409
+ ],
410
+ "ends": {
411
+ "submitted": 5,
412
+ "no_json": 1,
413
+ "schema_invalid": 2
414
+ },
415
+ "turns": 7.6,
416
+ "rescued_replies": 8
417
+ }
418
+ }
419
+ }
calibration/r2_episodes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
calibration/r2_summary.json ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3.8-27B:deepinfra",
3
+ "lenient": true,
4
+ "episodes": 72,
5
+ "seconds": 522,
6
+ "usage": {
7
+ "prompt_tokens": 7635035,
8
+ "completion_tokens": 98268,
9
+ "calls": 1042,
10
+ "empty_content": 61
11
+ },
12
+ "tasks": {
13
+ "bugfix-office-l1": {
14
+ "n": 8,
15
+ "mean": 0.625,
16
+ "solved": 5,
17
+ "rewards": [
18
+ 1.0,
19
+ 1.0,
20
+ 0.0,
21
+ 0.0,
22
+ 1.0,
23
+ 1.0,
24
+ 1.0,
25
+ 0.0
26
+ ],
27
+ "ends": {
28
+ "submitted": 4,
29
+ "no_json": 1,
30
+ "schema_invalid": 2,
31
+ "truncated": 1
32
+ },
33
+ "turns": 12.9,
34
+ "rescued_replies": 35
35
+ },
36
+ "bugfix-finance-l1": {
37
+ "n": 8,
38
+ "mean": 0.625,
39
+ "solved": 5,
40
+ "rewards": [
41
+ 1.0,
42
+ 1.0,
43
+ 0.0,
44
+ 1.0,
45
+ 1.0,
46
+ 0.0,
47
+ 1.0,
48
+ 0.0
49
+ ],
50
+ "ends": {
51
+ "submitted": 5,
52
+ "no_json": 1,
53
+ "schema_invalid": 2
54
+ },
55
+ "turns": 10.4,
56
+ "rescued_replies": 33
57
+ },
58
+ "bugfix-science-l1": {
59
+ "n": 8,
60
+ "mean": 0.375,
61
+ "solved": 3,
62
+ "rewards": [
63
+ 0.0,
64
+ 0.0,
65
+ 1.0,
66
+ 0.0,
67
+ 0.0,
68
+ 1.0,
69
+ 0.0,
70
+ 1.0
71
+ ],
72
+ "ends": {
73
+ "truncated": 1,
74
+ "schema_invalid": 2,
75
+ "submitted": 3,
76
+ "no_json": 2
77
+ },
78
+ "turns": 12,
79
+ "rescued_replies": 20
80
+ },
81
+ "bugfix-industrial-l2": {
82
+ "n": 8,
83
+ "mean": 0.375,
84
+ "solved": 3,
85
+ "rewards": [
86
+ 0.0,
87
+ 0.0,
88
+ 1.0,
89
+ 1.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 1.0
94
+ ],
95
+ "ends": {
96
+ "truncated": 1,
97
+ "schema_invalid": 1,
98
+ "submitted": 4,
99
+ "out_of_steps": 2
100
+ },
101
+ "turns": 23.5,
102
+ "rescued_replies": 58
103
+ },
104
+ "bugfix-media-l2": {
105
+ "n": 8,
106
+ "mean": 0.75,
107
+ "solved": 6,
108
+ "rewards": [
109
+ 1.0,
110
+ 1.0,
111
+ 1.0,
112
+ 1.0,
113
+ 0.0,
114
+ 1.0,
115
+ 0.0,
116
+ 1.0
117
+ ],
118
+ "ends": {
119
+ "submitted": 6,
120
+ "schema_invalid": 2
121
+ },
122
+ "turns": 13.9,
123
+ "rescued_replies": 54
124
+ },
125
+ "bugfix-security-l2": {
126
+ "n": 8,
127
+ "mean": 0.5,
128
+ "solved": 4,
129
+ "rewards": [
130
+ 0.0,
131
+ 1.0,
132
+ 1.0,
133
+ 0.0,
134
+ 0.0,
135
+ 0.0,
136
+ 1.0,
137
+ 1.0
138
+ ],
139
+ "ends": {
140
+ "schema_invalid": 2,
141
+ "submitted": 4,
142
+ "out_of_steps": 2
143
+ },
144
+ "turns": 13.9,
145
+ "rescued_replies": 60
146
+ },
147
+ "bugfix-software-l2": {
148
+ "n": 8,
149
+ "mean": 0.625,
150
+ "solved": 5,
151
+ "rewards": [
152
+ 0.0,
153
+ 1.0,
154
+ 1.0,
155
+ 0.0,
156
+ 0.0,
157
+ 1.0,
158
+ 1.0,
159
+ 1.0
160
+ ],
161
+ "ends": {
162
+ "out_of_steps": 2,
163
+ "submitted": 4,
164
+ "schema_invalid": 2
165
+ },
166
+ "turns": 16.1,
167
+ "rescued_replies": 30
168
+ },
169
+ "bugfix-math-l1": {
170
+ "n": 8,
171
+ "mean": 0.5,
172
+ "solved": 4,
173
+ "rewards": [
174
+ 1.0,
175
+ 1.0,
176
+ 1.0,
177
+ 0.0,
178
+ 1.0,
179
+ 0.0,
180
+ 0.0,
181
+ 0.0
182
+ ],
183
+ "ends": {
184
+ "submitted": 4,
185
+ "no_json": 1,
186
+ "out_of_steps": 1,
187
+ "schema_invalid": 2
188
+ },
189
+ "turns": 13.4,
190
+ "rescued_replies": 40
191
+ },
192
+ "media-production-l2": {
193
+ "n": 8,
194
+ "mean": 0.375,
195
+ "solved": 3,
196
+ "rewards": [
197
+ 1.0,
198
+ 1.0,
199
+ 0.0,
200
+ 0.0,
201
+ 0.0,
202
+ 0.0,
203
+ 0.0,
204
+ 1.0
205
+ ],
206
+ "ends": {
207
+ "submitted": 5,
208
+ "schema_invalid": 2,
209
+ "no_json": 1
210
+ },
211
+ "turns": 6.9,
212
+ "rescued_replies": 9
213
+ }
214
+ }
215
+ }
libraries.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mutants_per_library": {
3
+ "croniter": 40,
4
+ "isodate": 37,
5
+ "humanize": 40,
6
+ "numpy_financial": 40,
7
+ "uncertainties": 39,
8
+ "webvtt": 40,
9
+ "slugify": 40,
10
+ "jwt": 35,
11
+ "toolz": 40,
12
+ "tabulate": 40,
13
+ "inflection": 38,
14
+ "more_itertools": 40,
15
+ "srt": 13,
16
+ "itsdangerous": 3,
17
+ "fluids": 40
18
+ },
19
+ "libraries_per_domain": {
20
+ "office-white-collar": [
21
+ "croniter",
22
+ "humanize",
23
+ "isodate"
24
+ ],
25
+ "finance-economics": [
26
+ "numpy_financial"
27
+ ],
28
+ "natural-science": [
29
+ "uncertainties"
30
+ ],
31
+ "media-content-production": [
32
+ "slugify",
33
+ "srt",
34
+ "webvtt"
35
+ ],
36
+ "cybersecurity": [
37
+ "itsdangerous",
38
+ "jwt"
39
+ ],
40
+ "software-engineering": [
41
+ "inflection",
42
+ "tabulate",
43
+ "toolz"
44
+ ],
45
+ "mathematics-or-formal-reasoning": [
46
+ "more_itertools"
47
+ ],
48
+ "industrial-physical-systems": [
49
+ "fluids"
50
+ ]
51
+ }
52
+ }
source/codedesk/Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ LABEL org.opencontainers.image.title="Five Desks Code"
3
+ LABEL org.opencontainers.image.description="OpenEnv environment: agentic coding on real open-source libraries from every arena domain"
4
+ LABEL org.opencontainers.image.source="https://huggingface.co/datasets/rca-umb/five-desks"
5
+ LABEL org.opencontainers.image.licenses="Apache-2.0"
6
+ WORKDIR /app
7
+ COPY requirements.lock /app/requirements.lock
8
+ COPY codedesk/requirements-tools.txt /app/requirements-tools.txt
9
+ RUN apt-get update && apt-get install -y --no-install-recommends git ffmpeg imagemagick \
10
+ && pip install --no-cache-dir -r requirements.lock -r requirements-tools.txt \
11
+ && apt-get purge -y git && apt-get autoremove -y && rm -rf /var/lib/apt/lists/* \
12
+ && pip uninstall -y pip
13
+ COPY codedesk /app/codedesk
14
+ # The server runs as root so it can run the policy's commands as `nobody`, which cannot read /app (the bug catalog
15
+ # and the original library sources live there).
16
+ RUN rm -rf /app/codedesk/build && chmod -R go-rwx /app
17
+ ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
18
+ EXPOSE 8000
19
+ CMD ["uvicorn", "codedesk.server.app:app", "--host", "0.0.0.0", "--port", "8000"]
source/codedesk/__init__.py ADDED
File without changes
source/codedesk/base.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools with declared arguments, and the base class for coding tasks."""
2
+
3
+ import random
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Callable
7
+
8
+ from . import runner
9
+
10
+ TYPE_NAMES = {str: "string", int: "integer", float: "number", dict: "object", list: "array"}
11
+ READ_LINES = 200
12
+
13
+
14
+ @dataclass
15
+ class Tool:
16
+ name: str
17
+ help: str
18
+ fn: Callable[[dict], str]
19
+ args: dict[str, type] = field(default_factory=dict)
20
+ optional: tuple[str, ...] = ()
21
+ final: bool = False
22
+
23
+ def signature(self) -> str:
24
+ parts = [f'"{k}": {TYPE_NAMES[t]}' + (" (optional)" if k in self.optional else "") for k, t in self.args.items()]
25
+ return "{" + ", ".join(parts) + "}"
26
+
27
+ def check(self, args: dict) -> str | None:
28
+ unknown = sorted(set(args) - set(self.args))
29
+ if unknown:
30
+ return f"Unknown argument(s) {unknown} for {self.name}. It takes {self.signature()}."
31
+ missing = [k for k in self.args if k not in args and k not in self.optional]
32
+ if missing:
33
+ return f"Missing argument(s) {missing} for {self.name}. It takes {self.signature()}."
34
+ for k, t in self.args.items():
35
+ if k in args and not (isinstance(args[k], t) and not (t is int and isinstance(args[k], bool))):
36
+ return f"Argument {k!r} of {self.name} must be a {TYPE_NAMES[t]}."
37
+ return None
38
+
39
+
40
+ class CodingTask:
41
+ """One generated instance with its own workspace directory. Subclasses implement setup(), brief(), grade()."""
42
+
43
+ family = ""
44
+ domain = ""
45
+ levels = (1, 2)
46
+ max_steps = 30
47
+
48
+ def __init__(self, rng: random.Random, level: int, group: str = "", **opts):
49
+ self.rng, self.level, self.group, self.opts = rng, level, group, opts
50
+ self.ws = runner.new_workspace()
51
+ try:
52
+ self.setup()
53
+ runner.give_to_nobody(self.ws)
54
+ except BaseException:
55
+ self.close()
56
+ raise
57
+
58
+ def close(self):
59
+ runner.remove(self.ws)
60
+
61
+ # -- to implement --------------------------------------------------------------------------------
62
+ def setup(self):
63
+ raise NotImplementedError
64
+
65
+ def brief(self) -> str:
66
+ raise NotImplementedError
67
+
68
+ def grade(self, args: dict) -> float:
69
+ raise NotImplementedError
70
+
71
+ def oracle(self):
72
+ """Change the workspace into a correct solution (used by tests)."""
73
+ raise NotImplementedError
74
+
75
+ # -- shared tools --------------------------------------------------------------------------------
76
+ def _path(self, rel: str) -> Path | None:
77
+ rel = str(rel).strip()
78
+ p = (self.ws / rel.lstrip("/")).resolve() if not rel.startswith(str(self.ws)) else Path(rel).resolve()
79
+ ws = self.ws.resolve()
80
+ return p if p == ws or ws in p.parents else None
81
+
82
+ def coding_tools(self, tests: bool = True) -> list[Tool]:
83
+ tools = [
84
+ Tool("list_files", "list files under a directory of the repository (the root if omitted)", self._ls,
85
+ {"path": str}, optional=("path",)),
86
+ Tool("read_file", f"show a file with line numbers (lines start-end, at most {READ_LINES} at a time)",
87
+ self._read, {"path": str, "start": int, "end": int}, optional=("start", "end")),
88
+ Tool("search", "search the repository for a regular expression (grep -rn)", self._search,
89
+ {"pattern": str, "path": str}, optional=("path",)),
90
+ Tool("edit_file", "replace an exact snippet of a file with new text (the snippet must occur once)",
91
+ self._edit, {"path": str, "old": str, "new": str}),
92
+ Tool("write_file", "create or overwrite a whole file", self._write, {"path": str, "content": str}),
93
+ Tool("run", "run a shell command in the repository root (60 s limit), e.g. python -c '...'", self._run,
94
+ {"command": str}),
95
+ ]
96
+ if tests:
97
+ tools.append(Tool("run_tests", "run pytest on a test file or directory (the whole suite if omitted; "
98
+ "100 s limit)",
99
+ self._tests, {"target": str}, optional=("target",)))
100
+ return tools
101
+
102
+ def _ls(self, a):
103
+ p = self._path(a.get("path", "."))
104
+ if p is None or not p.is_dir():
105
+ return f"No directory {a.get('path')!r}."
106
+ rows = []
107
+ for q in sorted(p.rglob("*")):
108
+ rel = q.relative_to(self.ws).as_posix()
109
+ if any(part.startswith(".") or part == "__pycache__" for part in rel.split("/")):
110
+ continue
111
+ if q.is_file():
112
+ rows.append(rel)
113
+ return "\n".join(rows[:300]) + (f"\n... {len(rows) - 300} more" if len(rows) > 300 else "") or "(empty)"
114
+
115
+ def _read(self, a):
116
+ p = self._path(a["path"])
117
+ if p is None or not p.is_file():
118
+ return f"No file {a['path']!r}."
119
+ lines = p.read_text(errors="replace").split("\n")
120
+ start = max(1, a.get("start", 1))
121
+ end = min(len(lines), a.get("end", start + READ_LINES - 1), start + READ_LINES - 1)
122
+ body = "\n".join(f"{i:5d} {lines[i - 1]}" for i in range(start, end + 1))
123
+ more = f"\n[lines {start}-{end} of {len(lines)}]" if end < len(lines) or start > 1 else ""
124
+ return body + more
125
+
126
+ def _search(self, a):
127
+ if not a["pattern"]:
128
+ return "pattern is empty"
129
+ p = self._path(a.get("path", "."))
130
+ if p is None:
131
+ return "path is outside the repository"
132
+ import shlex
133
+ code, out = runner.run(f"grep -rnE --exclude-dir=__pycache__ -- {shlex.quote(a['pattern'])} "
134
+ f"{shlex.quote(str(p))} | head -60", self.ws, timeout=20)
135
+ return out.replace(str(self.ws) + "/", "") or "no matches"
136
+
137
+ def _edit(self, a):
138
+ p = self._path(a["path"])
139
+ if p is None or not p.is_file():
140
+ return f"No file {a['path']!r}."
141
+ text = p.read_text(errors="replace")
142
+ n = text.count(a["old"]) if a["old"] else 0
143
+ if n != 1:
144
+ return f"The snippet occurs {n} times in {a['path']}; it must occur exactly once (include more context)."
145
+ p.write_text(text.replace(a["old"], a["new"]))
146
+ return f"Edited {a['path']}."
147
+
148
+ def _write(self, a):
149
+ p = self._path(a["path"])
150
+ if p is None or p == self.ws.resolve():
151
+ return "path must be a file inside the repository"
152
+ p.parent.mkdir(parents=True, exist_ok=True)
153
+ p.write_text(a["content"])
154
+ runner.give_to_nobody(p.parent)
155
+ return f"Wrote {len(a['content'])} characters to {a['path']}."
156
+
157
+ def _run(self, a):
158
+ if not a["command"].strip():
159
+ return "command is empty"
160
+ code, out = runner.run(a["command"], self.ws, timeout=60)
161
+ return f"exit code {code}\n" + runner.trim(out.replace(str(self.ws) + "/", ""))
162
+
163
+ def _tests(self, a):
164
+ import shlex
165
+ target = a.get("target", "").strip()
166
+ code, out = runner.run("python -m pytest -q -p no:cacheprovider --tb=short -x --hypothesis-seed=0 "
167
+ + (shlex.quote(target) if target else ""), self.ws, timeout=100)
168
+ return f"exit code {code}\n" + runner.trim(out.replace(str(self.ws) + "/", ""))
source/codedesk/build/Dockerfile.builder ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Build-time only: runs pinned libraries' tests to build the mutation catalog (no network at run time).
2
+ FROM python:3.12-slim
3
+ RUN pip install --no-cache-dir pytest==8.3.3 hypothesis==6.112.1 numpy==2.1.2 python-dateutil==2.9.0.post0 \
4
+ pytz==2024.2 text-unidecode==1.3 freezegun==1.5.1
5
+ WORKDIR /work
source/codedesk/build/catalog.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the bug catalog for Five Desks Code: single-token mutants of real libraries that their own tests detect.
2
+
3
+ Runs inside the builder container (no network), never on the host:
4
+
5
+ docker run --rm --network none -v $PWD/sdists:/sdists:ro -v $PWD/out:/out -v $PWD:/build:ro \
6
+ codedesk-builder python /build/catalog.py [--per-lib 80]
7
+
8
+ For each library: run its test suite once (baseline), enumerate mutation sites inside function bodies (comparison,
9
+ arithmetic, boolean and constant changes), apply each one alone, run the tests again and keep mutants that 1 to 8
10
+ previously passing tests catch. Writes /out/<lib>/ (the pristine source tree) and /out/catalog.json.
11
+ """
12
+
13
+ import argparse
14
+ import ast
15
+ import io
16
+ import json
17
+ import os
18
+ import random
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import tarfile
24
+ import tempfile
25
+ import tokenize
26
+ import xml.etree.ElementTree as ET
27
+ from concurrent.futures import ThreadPoolExecutor
28
+ from pathlib import Path
29
+
30
+ # name: (sdist stem, package path inside the sdist, tests path, domain, test runner timeout s)
31
+ LIBS = {
32
+ "croniter": ("croniter-6.2.4", "src/croniter", "src/croniter/tests", "office-white-collar", 120),
33
+ "isodate": ("isodate-0.7.2", "src/isodate", "tests", "office-white-collar", 60),
34
+ "humanize": ("humanize-4.16.0", "src/humanize", "tests", "office-white-collar", 60),
35
+ "numpy_financial": ("numpy-financial-1.0.0", "numpy_financial", "numpy_financial/tests", "finance-economics", 60),
36
+ "uncertainties": ("uncertainties-3.2.3", "uncertainties", "tests", "natural-science", 120),
37
+ "simple_pid": ("simple_pid-2.0.1", "simple_pid", "tests", "industrial-physical-systems", 60),
38
+ "srt": ("srt-3.5.3", "srt.py", "tests", "media-content-production", 180),
39
+ "webvtt": ("webvtt-py-0.5.1", "webvtt", "tests", "media-content-production", 60),
40
+ "slugify": ("python_slugify-9.1.3", "slugify", "tests", "media-content-production", 60),
41
+ "itsdangerous": ("itsdangerous-2.2.0", "src/itsdangerous", "tests", "cybersecurity", 60),
42
+ "jwt": ("pyjwt-2.15.1", "jwt", "tests", "cybersecurity", 60),
43
+ "toolz": ("toolz-1.2.0", "toolz", "toolz/tests", "software-engineering", 60),
44
+ "tabulate": ("tabulate-0.10.0", "tabulate", "test", "software-engineering", 60),
45
+ "inflection": ("inflection-0.5.1", "inflection", "test_inflection.py", "software-engineering", 60),
46
+ "more_itertools": ("more_itertools-11.1.0", "more_itertools", "tests", "mathematics-or-formal-reasoning", 240),
47
+ "semver": ("semver-3.1.0", "src/semver", "tests", "software-engineering", 60),
48
+ "fluids": ("fluids-1.3.1", "fluids", "tests", "industrial-physical-systems", 120),
49
+ }
50
+ # libraries whose catalog uses only some modules and the test files that cover them
51
+ SUBSET = {
52
+ "fluids": {m: f"tests/test_{m}.py" for m in ["pump", "control_valve", "friction", "fittings", "core", "compressible",
53
+ "safety_valve", "piping", "flow_meter", "separator", "two_phase",
54
+ "open_flow", "jet_pump", "packed_bed", "drag", "mixing"]},
55
+ }
56
+
57
+ # tests that never finish on their own (real-time simulation); they are also removed from the shipped copies
58
+ DESELECT = ["--deselect", "tests/test_pid.py::test_converge_system"]
59
+
60
+ SWAPS = {ast.Lt: "<=", ast.LtE: "<", ast.Gt: ">=", ast.GtE: ">", ast.Eq: "!=", ast.NotEq: "==",
61
+ ast.Add: "-", ast.Sub: "+", ast.Mult: "/", ast.Div: "*", ast.FloorDiv: "/", ast.Mod: "//",
62
+ ast.And: "or", ast.Or: "and"}
63
+ OP_TEXT = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "==", ast.NotEq: "!=", ast.Add: "+",
64
+ ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.FloorDiv: "//", ast.Mod: "%", ast.And: "and", ast.Or: "or"}
65
+
66
+
67
+ def sites(src: str):
68
+ """Yield (line, col, old, new, kind, function) for single-token mutations inside function bodies."""
69
+ tree = ast.parse(src)
70
+ toks = [t for t in tokenize.generate_tokens(io.StringIO(src).readline) if t.type in (tokenize.OP, tokenize.NAME)]
71
+
72
+ def token_between(a, b, text):
73
+ for t in toks:
74
+ if a <= t.start and t.end <= b and t.string == text:
75
+ return t
76
+ return None
77
+
78
+ def walk(node, func):
79
+ for child in ast.iter_child_nodes(node):
80
+ name = child.name if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) else func
81
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
82
+ # skip decorators and defaults: mutate the body only
83
+ for stmt in child.body:
84
+ if not (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)): # docstrings
85
+ yield from walk_stmt(stmt, name)
86
+ continue
87
+ if isinstance(child, ast.ClassDef):
88
+ yield from walk(child, func)
89
+
90
+ def walk_stmt(stmt, func):
91
+ for n in ast.walk(stmt):
92
+ if isinstance(n, ast.Compare):
93
+ left = n.left
94
+ for op, right in zip(n.ops, n.comparators):
95
+ if type(op) in SWAPS:
96
+ t = token_between((left.end_lineno, left.end_col_offset), (right.lineno, right.col_offset),
97
+ OP_TEXT[type(op)])
98
+ if t:
99
+ yield t.start[0], t.start[1], t.string, SWAPS[type(op)], "compare", func
100
+ left = right
101
+ elif isinstance(n, ast.BinOp) and type(n.op) in SWAPS:
102
+ if isinstance(n.left, ast.Constant) and isinstance(n.left.value, str):
103
+ continue # string formatting with %, concatenation
104
+ t = token_between((n.left.end_lineno, n.left.end_col_offset), (n.right.lineno, n.right.col_offset),
105
+ OP_TEXT[type(n.op)])
106
+ if t:
107
+ yield t.start[0], t.start[1], t.string, SWAPS[type(n.op)], "arith", func
108
+ elif isinstance(n, ast.BoolOp) and type(n.op) in SWAPS:
109
+ for a, b in zip(n.values, n.values[1:]):
110
+ t = token_between((a.end_lineno, a.end_col_offset), (b.lineno, b.col_offset), OP_TEXT[type(n.op)])
111
+ if t:
112
+ yield t.start[0], t.start[1], t.string, SWAPS[type(n.op)], "bool", func
113
+ elif isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.Not):
114
+ yield n.lineno, n.col_offset, "not ", "", "not", func
115
+ elif (isinstance(n, ast.Constant) and type(n.value) is int and 0 <= n.value <= 64
116
+ and n.end_lineno == n.lineno and n.end_col_offset - n.col_offset == len(str(n.value))):
117
+ yield n.lineno, n.col_offset, str(n.value), str(n.value + 1 if n.value != 1 else 0), "const", func
118
+
119
+ yield from walk(tree, None)
120
+
121
+
122
+ def apply(src: str, line: int, col: int, old: str, new: str) -> str:
123
+ lines = src.splitlines(keepends=True)
124
+ text = lines[line - 1]
125
+ assert text[col:col + len(old)] == old, (text, col, old)
126
+ lines[line - 1] = text[:col] + new + text[col + len(old):]
127
+ return "".join(lines)
128
+
129
+
130
+ def run_tests(root: Path, tests: str, timeout: int, select=None):
131
+ """Run pytest; return ({nodeid: outcome}, output) or (None, output) on a crash or timeout."""
132
+ with tempfile.TemporaryDirectory() as tmp:
133
+ xml = Path(tmp) / "r.xml"
134
+ cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-p", "no:randomly", "--tb=no",
135
+ "--hypothesis-seed=0", f"--junitxml={xml}", "-o", "junit_family=xunit1", *DESELECT,
136
+ *(select or [tests])]
137
+ env = {**os.environ, "PYTHONPATH": f"{root}:{root}/src", "PYTHONDONTWRITEBYTECODE": "1"}
138
+ try:
139
+ proc = subprocess.run(cmd, cwd=root, env=env, capture_output=True, text=True, timeout=timeout)
140
+ except subprocess.TimeoutExpired:
141
+ return None, "timeout"
142
+ if not xml.exists():
143
+ return None, proc.stdout[-2000:] + proc.stderr[-2000:]
144
+ results = {}
145
+ for case in ET.parse(xml).getroot().iter("testcase"):
146
+ nodeid = f"{case.get('file') or case.get('classname')}::{case.get('name')}"
147
+ kids = {c.tag for c in case}
148
+ results[nodeid] = ("failed" if kids & {"failure", "error"} else "skipped" if "skipped" in kids else "passed")
149
+ return results, proc.stdout[-4000:]
150
+
151
+
152
+ def failure_text(root: Path, nodeid: str, timeout: int) -> str:
153
+ file_part, _, name = nodeid.partition("::")
154
+ env = {**os.environ, "PYTHONPATH": f"{root}:{root}/src", "PYTHONDONTWRITEBYTECODE": "1"}
155
+ cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "--tb=short", "-x", "--hypothesis-seed=0",
156
+ *DESELECT, "-k", name.split("[")[0]]
157
+ path = file_part.replace(".", "/") + ".py" if not file_part.endswith(".py") else file_part
158
+ if (root / path).exists():
159
+ cmd.append(path)
160
+ try:
161
+ out = subprocess.run(cmd, cwd=root, env=env, capture_output=True, text=True, timeout=timeout).stdout
162
+ except subprocess.TimeoutExpired:
163
+ return ""
164
+ return out[-3000:]
165
+
166
+
167
+ def build_lib(name, spec, per_lib, out_dir, workers):
168
+ stem, pkg, tests, domain, timeout = spec
169
+ pristine = out_dir / name
170
+ if pristine.exists():
171
+ shutil.rmtree(pristine)
172
+ with tarfile.open(f"/sdists/{stem}.tar.gz") as tf:
173
+ tf.extractall(out_dir / "_extract", filter="data")
174
+ shutil.move(str(out_dir / "_extract" / stem), str(pristine))
175
+ import time
176
+ subset = SUBSET.get(name)
177
+ select = sorted(set(subset.values())) if subset else None
178
+ t0 = time.monotonic()
179
+ base, out = run_tests(pristine, tests, timeout * 2, select)
180
+ timeout = max(15, int(5 * (time.monotonic() - t0))) # mutants that loop forever are cut off early
181
+ if base is None:
182
+ print(f"{name}: baseline failed: {out[-300:]}", flush=True)
183
+ return []
184
+ passing = {k for k, v in base.items() if v == "passed"}
185
+ (out_dir / f"{name}.baseline.json").write_text(json.dumps(base, indent=0))
186
+ files = [pristine / pkg] if pkg.endswith(".py") else sorted((pristine / pkg).rglob("*.py"))
187
+ files = [f for f in files if "test" not in f.relative_to(pristine).as_posix().split("/")[-1]
188
+ and "/tests/" not in f.relative_to(pristine).as_posix()]
189
+ if subset:
190
+ files = [f for f in files if f.stem in subset and f.parent == pristine / pkg]
191
+ cands = []
192
+ for f in files:
193
+ src = f.read_text()
194
+ try:
195
+ for s in sites(src):
196
+ cands.append((f.relative_to(pristine).as_posix(), *s))
197
+ except (SyntaxError, tokenize.TokenError):
198
+ continue
199
+ rng = random.Random(f"catalog:{name}")
200
+ rng.shuffle(cands)
201
+ cands = cands[:per_lib * 3]
202
+ print(f"{name}: {len(passing)} passing tests, {len(cands)} candidate sites", flush=True)
203
+
204
+ def try_one(c):
205
+ rel, line, col, old, new, kind, func = c
206
+ work = Path(tempfile.mkdtemp())
207
+ try:
208
+ shutil.copytree(pristine, work / "lib")
209
+ path = work / "lib" / rel
210
+ mutated = apply(path.read_text(), line, col, old, new)
211
+ try:
212
+ ast.parse(mutated)
213
+ except SyntaxError:
214
+ return None
215
+ path.write_text(mutated)
216
+ res, _ = run_tests(work / "lib", tests, timeout, [subset[Path(rel).stem]] if subset else None)
217
+ if res is None:
218
+ return None
219
+ killed = sorted(k for k in passing if res.get(k) == "failed")
220
+ if not 1 <= len(killed) <= 8:
221
+ return None
222
+ fail = failure_text(work / "lib", killed[0], timeout)
223
+ return {"lib": name, "domain": domain, "file": rel, "line": line, "col": col, "old": old, "new": new,
224
+ "kind": kind, "function": func, "killed": killed, "failure": fail,
225
+ "tests_root": tests}
226
+ finally:
227
+ shutil.rmtree(work, ignore_errors=True)
228
+
229
+ kept = []
230
+ with ThreadPoolExecutor(workers) as pool:
231
+ for m in pool.map(try_one, cands):
232
+ if m and len(kept) < per_lib:
233
+ kept.append(m)
234
+ print(f"{name}: kept {len(kept)} mutants", flush=True)
235
+ return kept
236
+
237
+
238
+ def main():
239
+ ap = argparse.ArgumentParser()
240
+ ap.add_argument("--per-lib", type=int, default=40)
241
+ ap.add_argument("--libs", default="")
242
+ ap.add_argument("--workers", type=int, default=4)
243
+ args = ap.parse_args()
244
+ out_dir = Path("/out")
245
+ out_dir.mkdir(exist_ok=True)
246
+ catalog_path = out_dir / "catalog.json"
247
+ catalog = json.loads(catalog_path.read_text()) if catalog_path.exists() else []
248
+ names = [n for n in LIBS if not args.libs or n in args.libs.split(",")]
249
+ catalog = [m for m in catalog if m["lib"] not in names]
250
+ for name in names:
251
+ catalog += build_lib(name, LIBS[name], args.per_lib, out_dir, args.workers)
252
+ catalog_path.write_text(json.dumps(catalog, indent=1))
253
+ shutil.rmtree(out_dir / "_extract", ignore_errors=True)
254
+ print("total mutants:", len(catalog))
255
+
256
+
257
+ if __name__ == "__main__":
258
+ main()
source/codedesk/build/package.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Copy the built catalog and pristine library trees into codedesk/data for the image (file copies only).
2
+
3
+ Usage (on the host, after catalog.py): python3 codedesk/build/package.py
4
+ """
5
+
6
+ import ast
7
+ import json
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ HERE = Path(__file__).resolve().parent
12
+ OUT, DATA = HERE / "out", HERE.parent / "data"
13
+ # tests that never finish on their own; removed from the shipped copies
14
+ STRIP = {"simple_pid": {"tests/test_pid.py": {"test_converge_system"}}}
15
+ # simple-pid's tests depend on wall-clock timing and gave different results under load: not used
16
+ DROP = {"simple_pid", "semver"}
17
+
18
+
19
+ def strip_tests(path: Path, names: set[str]):
20
+ src = path.read_text()
21
+ spans = [(min([n.lineno] + [d.lineno for d in n.decorator_list]), n.end_lineno) for n in ast.walk(ast.parse(src))
22
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in names]
23
+ lines = src.splitlines(keepends=True)
24
+ for first, last in sorted(spans, reverse=True):
25
+ del lines[first - 1:last]
26
+ path.write_text("".join(lines))
27
+
28
+
29
+ def main():
30
+ catalog = [m for m in json.loads((OUT / "catalog.json").read_text()) if m["lib"] not in DROP]
31
+ valid = OUT / "valid.json"
32
+ if valid.exists() and "--validated" in __import__("sys").argv: # keep only mutants that passed validate.py
33
+ keys = {tuple(k) for k in json.loads(valid.read_text())["ok"]}
34
+ catalog = [m for m in catalog if (m["lib"], m["file"], m["line"], m["col"], m["new"]) in keys]
35
+ libs = sorted({m["lib"] for m in catalog})
36
+ shutil.rmtree(DATA, ignore_errors=True)
37
+ (DATA / "libs").mkdir(parents=True)
38
+ for lib in libs:
39
+ shutil.copytree(OUT / lib, DATA / "libs" / lib, ignore=shutil.ignore_patterns(
40
+ "__pycache__", "*.pyc", ".pytest_cache", ".hypothesis", "docs", ".github", "*.egg-info"))
41
+ for rel, names in STRIP.get(lib, {}).items():
42
+ strip_tests(DATA / "libs" / lib / rel, names)
43
+ shutil.copy(OUT / f"{lib}.baseline.json", DATA / f"{lib}.baseline.json")
44
+ stripped = {(lib, f"{rel}::{n}") for lib, files in STRIP.items() for rel, names in files.items() for n in names}
45
+ catalog = [m for m in catalog if not any((m["lib"], k.split("[")[0]) in stripped for k in m["killed"])]
46
+ (DATA / "catalog.json").write_text(json.dumps(catalog, indent=1))
47
+ by = {}
48
+ for m in catalog:
49
+ by[m["lib"]] = by.get(m["lib"], 0) + 1
50
+ print(len(catalog), "mutants", by)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
source/codedesk/build/survey.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -u
2
+ pip install -q python-dateutil pytz text-unidecode freezegun 2>/dev/null
3
+ mkdir -p /tmp/src && cd /tmp/src
4
+ for f in /out/*.tar.gz; do tar xzf "$f"; done
5
+ for d in /tmp/src/*/; do
6
+ n=$(basename "$d")
7
+ t=$(find "$d" -path '*test*' -name '*.py' | wc -l)
8
+ src=$(find "$d" -name '*.py' -not -path '*test*' -not -path '*docs*' -not -name 'setup.py' -not -name 'conf.py' | xargs cat 2>/dev/null | wc -l)
9
+ start=$(date +%s.%N)
10
+ out=$(cd "$d" && PYTHONPATH="$d:$d/src" timeout 300 python -m pytest -q -x -p no:cacheprovider 2>&1 | tail -1)
11
+ end=$(date +%s.%N)
12
+ printf '%-28s testfiles=%-3s srclines=%-6s %6.1fs %s\n' "$n" "$t" "$src" "$(echo "$end - $start" | bc 2>/dev/null || echo 0)" "$out"
13
+ done
source/codedesk/build/validate.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check every catalog mutant inside the image: the untouched workspace must fail and the original code must pass,
2
+ at both levels. Writes the indices that pass to /out/valid.json.
3
+
4
+ docker run --rm -e PYTHONPATH=/app -v $PWD/codedesk/build/out:/out -v $PWD/codedesk/build/validate.py:/v.py:ro \
5
+ five-desks-code:native python /v.py
6
+ """
7
+
8
+ import json
9
+ import random
10
+ import sys
11
+ from concurrent.futures import ThreadPoolExecutor
12
+
13
+ from codedesk.families.bugfix import LIBS, LibBugfix, catalog
14
+
15
+
16
+ def check(i_m):
17
+ i, m = i_m
18
+ try:
19
+ for level in (1, 2):
20
+ t = LibBugfix(random.Random(i), level, LIBS[m["lib"]][1], mutant=m)
21
+ try:
22
+ if t.grade({}) != 0.0:
23
+ return i, "untouched passes"
24
+ t.oracle()
25
+ if t.grade({}) != 1.0:
26
+ return i, f"oracle fails (level {level})"
27
+ finally:
28
+ t.close()
29
+ return i, "ok"
30
+ except Exception as exc: # generation problems count as failures
31
+ return i, f"error {type(exc).__name__}: {exc}"[:200]
32
+
33
+
34
+ def main():
35
+ cat = catalog()
36
+ results = {}
37
+ with ThreadPoolExecutor(int(sys.argv[1]) if len(sys.argv) > 1 else 4) as pool:
38
+ for i, verdict in pool.map(check, list(enumerate(cat))):
39
+ results[i] = verdict
40
+ ok = [i for i, v in sorted(results.items()) if v == "ok"]
41
+ keys = [[cat[i]["lib"], cat[i]["file"], cat[i]["line"], cat[i]["col"], cat[i]["new"]] for i in ok]
42
+ bad = {}
43
+ for i, v in results.items():
44
+ if v != "ok":
45
+ bad.setdefault(cat[i]["lib"], []).append(v)
46
+ json.dump({"ok": keys, "failures": {k: v[:5] for k, v in bad.items()}}, open("/out/valid.json", "w"), indent=1)
47
+ by = {}
48
+ for i in ok:
49
+ by[cat[i]["lib"]] = by.get(cat[i]["lib"], 0) + 1
50
+ print(len(ok), "of", len(cat), "valid", by)
51
+ print({k: len(v) for k, v in bad.items()})
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
source/codedesk/environment.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Five Desks Code OpenEnv environment: agentic coding on real libraries from every arena domain."""
2
+
3
+ import random
4
+ import secrets
5
+ from typing import Any, Optional
6
+ from uuid import uuid4
7
+
8
+ from openenv.core.env_server.interfaces import Environment
9
+ from openenv.core.env_server.types import State
10
+
11
+ from .families import FAMILIES
12
+ from .interface import Interface
13
+ from .models import ToolAction, ToolObservation
14
+
15
+ MAX_OUTPUT_CHARS = 6000
16
+
17
+
18
+ def task_ids() -> list[str]:
19
+ return [f"{fam}-{group}-l{level}" for fam, cls in FAMILIES.items() for group in cls.groups() for level in cls.levels]
20
+
21
+
22
+ def build(task_id: str, seed: int):
23
+ fam, _, rest = task_id.partition("-")
24
+ group, _, level = rest.rpartition("-l")
25
+ cls = FAMILIES.get(fam)
26
+ if cls is None or group not in cls.groups() or level not in {str(lv) for lv in cls.levels}:
27
+ raise ValueError(f"unknown task_id {task_id!r}; known ids: {', '.join(task_ids())}")
28
+ return cls(random.Random(f"{task_id}:{seed}"), int(level), group)
29
+
30
+
31
+ class CodeEnvironment(Environment):
32
+ SUPPORTS_CONCURRENT_SESSIONS = True
33
+
34
+ def __init__(self):
35
+ self._state = State(episode_id=str(uuid4()), step_count=0)
36
+ self._task = None
37
+ self._tools = {}
38
+ self._interface = None
39
+ self._steps_left = 0
40
+ self._done = True
41
+
42
+ def _close_task(self):
43
+ if self._task is not None:
44
+ self._task.close()
45
+
46
+ def reset(self, seed: Optional[int] = None, episode_id: Optional[str] = None, task_id: Optional[str] = None,
47
+ canonical_names: bool = False, **kwargs: Any) -> ToolObservation:
48
+ task_id = task_id or task_ids()[0]
49
+ seed = seed if seed is not None else secrets.randbits(48)
50
+ self._close_task()
51
+ self._task = build(task_id, seed)
52
+ tools = self._task.tools()
53
+ self._interface = None if canonical_names else Interface(tools, random.Random(f"names:{task_id}:{seed}"))
54
+ listed = self._interface.tools if self._interface else tools
55
+ self._tools = {t.name: t for t in listed}
56
+ self._state = State(episode_id=episode_id or str(uuid4()), step_count=0)
57
+ self._steps_left = self._task.max_steps
58
+ self._done = False
59
+ brief = self._interface.text(self._task.brief()) if self._interface else self._task.brief()
60
+ lines = [f"- {t.name} {t.signature()}: {t.help}" for t in listed]
61
+ text = (f"{brief}\n\nReply with exactly one JSON object per turn: {{\"tool\": \"<name>\", \"args\": {{...}}}}. "
62
+ "Tools:\n" + "\n".join(lines) + f"\nYou have {self._task.max_steps} tool calls.")
63
+ return ToolObservation(output=text, steps_left=self._steps_left, done=False, reward=0.0)
64
+
65
+ def _end(self, output: str, reward: float) -> ToolObservation:
66
+ self._done = True
67
+ self._close_task()
68
+ return ToolObservation(output=output, steps_left=self._steps_left, done=True,
69
+ reward=round(min(1.0, max(0.0, reward)), 4))
70
+
71
+ def step(self, action: ToolAction, timeout_s: Optional[float] = None, **kwargs: Any) -> ToolObservation: # type: ignore[override]
72
+ if self._task is None or self._done:
73
+ return ToolObservation(output="Episode is over. Call reset.", steps_left=0, done=True, reward=0.0)
74
+ self._state.step_count += 1
75
+ self._steps_left -= 1
76
+ name = action.tool.strip()
77
+ tool = self._tools.get(name)
78
+ if tool is not None and tool.final: # submit (also the arena's finish action) grades the work so far
79
+ return self._end("Submitted.", float(tool.fn(dict(action.args))))
80
+ if tool is None and name == "submit":
81
+ return self._end("Submitted.", float(self._task.grade({})))
82
+ if tool is None:
83
+ output = f"Unknown tool {name!r}. Tools: {', '.join(self._tools)}."
84
+ elif (error := tool.check(action.args)) is not None:
85
+ output = error
86
+ else:
87
+ try:
88
+ output = tool.fn(action.args)
89
+ except Exception as exc: # a tool bug must not kill the episode
90
+ output = f"Tool error: {type(exc).__name__}: {exc}"
91
+ if self._interface:
92
+ output = self._interface.text(output)
93
+ if len(output) > MAX_OUTPUT_CHARS:
94
+ output = output[:MAX_OUTPUT_CHARS] + "\n... [output truncated]"
95
+ if self._steps_left <= 0:
96
+ return self._end(output + "\nNo tool calls left; the work so far was submitted.", float(self._task.grade({})))
97
+ return ToolObservation(output=output, steps_left=self._steps_left, done=False, reward=0.0)
98
+
99
+ @property
100
+ def state(self) -> State:
101
+ return self._state
source/codedesk/families/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .bugfix import LibBugfix, groups
2
+ from .mediatools import MediaTools
3
+
4
+ LibBugfix.groups = staticmethod(groups)
5
+
6
+ FAMILIES = {cls.family: cls for cls in [LibBugfix, MediaTools]}
source/codedesk/families/bugfix.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix a real bug in a real library.
2
+
3
+ Each instance takes one pinned open-source Python library and one mutant from the build-time catalog: a single
4
+ token changed inside a function (a comparison, an operator, a constant, and/or, a `not`) that 1 to 8 of the
5
+ library's own tests catch. Level 1 is a failing CI run: the test suite is in the repository and the issue shows
6
+ the failing test's output. Level 2 is a user report: the issue shows only the failing check, and the tests that
7
+ cover it are removed from the repository, so the policy has to find the code and verify its fix itself.
8
+
9
+ Grading copies only the library's own source files from the workspace into a clean copy of the original project
10
+ and runs the original test files that cover the bug: every catching test must pass and no other test in those
11
+ files may fail that passes on the original. Edits to tests, configuration or anything else are ignored.
12
+ """
13
+
14
+ import ast
15
+ import json
16
+ import re
17
+ import shutil
18
+ import tempfile
19
+ import xml.etree.ElementTree as ET
20
+ from functools import lru_cache
21
+ from pathlib import Path
22
+
23
+ from .. import runner
24
+ from ..base import CodingTask, Tool
25
+
26
+ DATA = Path(__file__).resolve().parents[1] / "data"
27
+ # library -> (package path in the source tree, task group)
28
+ LIBS = {
29
+ "croniter": ("src/croniter", "office"), "isodate": ("src/isodate", "office"), "humanize": ("src/humanize", "office"),
30
+ "numpy_financial": ("numpy_financial", "finance"), "uncertainties": ("uncertainties", "science"),
31
+ "fluids": ("fluids", "industrial"), "srt": ("srt.py", "media"), "webvtt": ("webvtt", "media"),
32
+ "slugify": ("slugify", "media"), "itsdangerous": ("src/itsdangerous", "security"), "jwt": ("jwt", "security"),
33
+ "toolz": ("toolz", "software"), "tabulate": ("tabulate", "software"), "inflection": ("inflection", "software"),
34
+ "semver": ("src/semver", "software"), "more_itertools": ("more_itertools", "math"),
35
+ }
36
+ DOMAINS = {"office": "office-white-collar", "finance": "finance-economics", "science": "natural-science",
37
+ "industrial": "industrial-physical-systems", "media": "media-content-production",
38
+ "security": "cybersecurity", "software": "software-engineering", "math": "mathematics-or-formal-reasoning"}
39
+ SKIP = {".egg-info", "docs", ".github", "PKG-INFO", "__pycache__", "benchmarks", "examples"}
40
+
41
+
42
+ @lru_cache(maxsize=1)
43
+ def catalog() -> list[dict]:
44
+ path = DATA / "catalog.json"
45
+ return json.loads(path.read_text()) if path.exists() else []
46
+
47
+
48
+ def pytest_outcomes(root: Path, files: list[str]) -> dict | None:
49
+ """Run the given test files under root as nobody; {test key: passed/failed/skipped}, or None if pytest crashed."""
50
+ xml = root / ".grade.xml"
51
+ runner.run("python -m pytest -q -p no:cacheprovider -p no:randomly --tb=no --hypothesis-seed=0 "
52
+ f"--junitxml={xml} -o junit_family=xunit1 " + " ".join(files), root, timeout=240)
53
+ if not xml.exists():
54
+ return None
55
+ outcomes = {}
56
+ for case in ET.parse(xml).getroot().iter("testcase"):
57
+ key = f"{case.get('file') or case.get('classname')}::{case.get('name')}"
58
+ kids = {c.tag for c in case}
59
+ outcomes[key] = "failed" if kids & {"failure", "error"} else "skipped" if "skipped" in kids else "passed"
60
+ return outcomes
61
+
62
+
63
+ def owned_tmp(prefix: str) -> tempfile.TemporaryDirectory:
64
+ tmp = tempfile.TemporaryDirectory(prefix=prefix)
65
+ if runner.AS_ROOT:
66
+ import os
67
+ os.chown(tmp.name, runner.NOBODY, runner.NOBODY)
68
+ return tmp
69
+
70
+
71
+ @lru_cache(maxsize=None)
72
+ def pristine_outcomes(lib: str, files: tuple[str, ...]) -> dict:
73
+ """Outcomes of the same test files on the original library, in this image (tests can depend on run order)."""
74
+ with owned_tmp("pristine-") as tmp:
75
+ root = Path(tmp) / "repo"
76
+ copy_tree(DATA / "libs" / lib, root)
77
+ runner.give_to_nobody(Path(tmp))
78
+ return pytest_outcomes(root, list(files)) or {}
79
+
80
+
81
+ def groups() -> list[str]:
82
+ present = {LIBS[m["lib"]][1] for m in catalog() if m["lib"] in LIBS}
83
+ return [g for g in DOMAINS if g in present]
84
+
85
+
86
+ def copy_tree(src: Path, dst: Path):
87
+ def ignore(_, names):
88
+ return [n for n in names if n in SKIP or n.endswith(".egg-info") or n.startswith(".")]
89
+ shutil.copytree(src, dst, ignore=ignore, dirs_exist_ok=True)
90
+
91
+
92
+ def mutate(text: str, m: dict) -> str:
93
+ lines = text.splitlines(keepends=True)
94
+ line = lines[m["line"] - 1]
95
+ assert line[m["col"]:m["col"] + len(m["old"])] == m["old"], m
96
+ lines[m["line"] - 1] = line[:m["col"]] + m["new"] + line[m["col"] + len(m["old"]):]
97
+ return "".join(lines)
98
+
99
+
100
+ def test_file(key: str) -> str:
101
+ return key.split("::")[0]
102
+
103
+
104
+ def test_name(key: str) -> str:
105
+ return key.split("::")[-1].split("[")[0]
106
+
107
+
108
+ def remove_tests(path: Path, names: set[str]):
109
+ """Delete the named test functions (with their decorators) from a test file, keeping everything else."""
110
+ src = path.read_text()
111
+ tree = ast.parse(src)
112
+ spans = []
113
+ for node in ast.walk(tree):
114
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:
115
+ first = min([node.lineno] + [d.lineno for d in node.decorator_list])
116
+ spans.append((first, node.end_lineno))
117
+ lines = src.splitlines(keepends=True)
118
+ for first, last in sorted(spans, reverse=True):
119
+ del lines[first - 1:last]
120
+ path.write_text("".join(lines))
121
+
122
+
123
+ def symptom(failure: str) -> str:
124
+ """The failing check from pytest's short traceback, without the test's name or location."""
125
+ keep, grab = [], False
126
+ for line in failure.splitlines():
127
+ if re.match(r"^\S+\.py:\d+: in ", line):
128
+ grab = True
129
+ continue
130
+ if grab and line.startswith(" ") and not line.startswith(" E"):
131
+ keep.append(line.strip())
132
+ elif line.startswith("E "):
133
+ keep.append(line[1:].strip())
134
+ if sum(1 for k in keep if k.startswith(("AssertionError", "assert", "+", "-", "Error", "Value", "Type", "Key",
135
+ "Index", "Attribute"))) > 4:
136
+ break
137
+ elif line.startswith(("=", "_")) and keep:
138
+ break
139
+ return "\n".join(keep[-8:])
140
+
141
+
142
+ class LibBugfix(CodingTask):
143
+ family = "bugfix"
144
+ levels = (1, 2)
145
+ max_steps = 30
146
+
147
+ def setup(self):
148
+ pool = [m for m in catalog() if LIBS.get(m["lib"], (None, None))[1] == self.group]
149
+ if self.level == 2: # needs a readable check for the report
150
+ pool = [m for m in pool if symptom(m["failure"]).count("\n") >= 1] or pool
151
+ assert pool, f"no mutants for {self.group}"
152
+ self.m = m = self.opts.get("mutant") or self.rng.choice(pool) # tests and validation can pick one
153
+ self.domain = DOMAINS[self.group]
154
+ self.lib_root = DATA / "libs" / m["lib"]
155
+ self.pkg = LIBS[m["lib"]][0]
156
+ copy_tree(self.lib_root, self.ws)
157
+ target = self.ws / m["file"]
158
+ self.original = target.read_text()
159
+ target.write_text(mutate(self.original, m))
160
+ self.killed = m["killed"]
161
+ if self.level == 2:
162
+ by_file = {}
163
+ for key in self.killed:
164
+ by_file.setdefault(test_file(key), set()).add(test_name(key))
165
+ for rel, names in by_file.items():
166
+ if (self.ws / rel).exists():
167
+ remove_tests(self.ws / rel, names)
168
+ failing = self.killed[0]
169
+ if self.level == 1:
170
+ report = (f"# CI failure\n\nThe test suite fails on main. One failing test:\n\n pytest '{failing}'\n\n"
171
+ f"```\n{m['failure'].strip()[-2500:]}\n```\n\nFix the library (not the tests).\n")
172
+ else:
173
+ report = ("# Bug report\n\nA user reports that this check fails on the current version:\n\n"
174
+ f"```\n{symptom(m['failure'])}\n```\n\nThe expected behaviour is the one the check asserts. Fix "
175
+ "the library; the test suite has no test for this yet.\n")
176
+ (self.ws / "ISSUE.md").write_text(report)
177
+
178
+ def brief(self):
179
+ name = self.m["lib"].replace("_", "-")
180
+ how = ("Run the failing test, find the cause in the library code, fix it" if self.level == 1 else
181
+ "Reproduce the problem, find the cause in the library code, fix it")
182
+ return (f"SOFTWARE ({self.group}). This repository is the open-source Python library {name}. Read ISSUE.md. "
183
+ f"{how}, check that nothing else breaks, then submit. Only changes to the library's own source "
184
+ f"({self.pkg}) count.")
185
+
186
+ def tools(self):
187
+ return self.coding_tools(tests=True) + [Tool("submit", "submit your fix (ends the episode)", self.grade,
188
+ final=True)]
189
+
190
+ def grade(self, a=None) -> float:
191
+ with owned_tmp("grade-") as tmp:
192
+ root = Path(tmp) / "repo"
193
+ copy_tree(self.lib_root, root)
194
+ src, dst = self.ws / self.pkg, root / self.pkg
195
+ # never follow links out of the workspace (the grader runs as root)
196
+ if src.is_symlink() or (src.is_dir() and any(p.is_symlink() for p in src.rglob("*"))):
197
+ return 0.0
198
+ if src.is_file():
199
+ shutil.copyfile(src, dst)
200
+ elif src.is_dir():
201
+ shutil.rmtree(dst)
202
+ shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "conftest.py"))
203
+ else:
204
+ return 0.0
205
+ # some libraries keep their tests inside the package: always grade with the original tests
206
+ tests = self.lib_root / self.m["tests_root"]
207
+ if tests.is_dir():
208
+ shutil.rmtree(root / self.m["tests_root"], ignore_errors=True)
209
+ copy_tree(tests, root / self.m["tests_root"])
210
+ elif tests.is_file():
211
+ shutil.copyfile(tests, root / self.m["tests_root"])
212
+ runner.give_to_nobody(Path(tmp))
213
+ files = sorted({test_file(k) for k in self.killed})
214
+ outcomes = pytest_outcomes(root, files)
215
+ if outcomes is None or any(outcomes.get(k) != "passed" for k in self.killed):
216
+ return 0.0
217
+ base = pristine_outcomes(self.m["lib"], tuple(files))
218
+ return float(not [k for k, v in outcomes.items() if v == "failed" and base.get(k) == "passed"])
219
+
220
+ def oracle(self):
221
+ (self.ws / self.m["file"]).write_text(self.original)
source/codedesk/families/mediatools.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Media production with real tools: ffmpeg, ImageMagick and Pillow.
2
+
3
+ Each instance generates its own input media and a client spec (spec.md) plus production notes (notes.md) that add
4
+ one requirement the spec does not mention. The policy uses the shell to produce the deliverable. Grading measures
5
+ the output files (stream properties with ffprobe; picture content against references computed from a private copy
6
+ of the inputs) and never trusts anything the policy wrote except the deliverables themselves.
7
+
8
+ Variants: a trimmed and scaled video clip, square thumbnails from photos (some rotated by EXIF), a contact sheet
9
+ ordered by capture time, and a loudness-normalised audio delivery.
10
+ """
11
+
12
+ import json
13
+ import math
14
+ import shutil
15
+ import tempfile
16
+ from pathlib import Path
17
+
18
+ from .. import runner
19
+ from ..base import CodingTask, Tool
20
+
21
+ ANALYZE = r'''
22
+ import json, subprocess, sys
23
+ from PIL import Image, ImageOps
24
+ kind, path = sys.argv[1], sys.argv[2]
25
+ def tiny(img, size):
26
+ return list(ImageOps.fit(img.convert("L"), size).getdata())
27
+ if kind == "image":
28
+ try:
29
+ img = Image.open(path); img.load()
30
+ print(json.dumps({"size": img.size, "format": img.format, "tiny": tiny(img, (8, 8))}))
31
+ except Exception as e:
32
+ print(json.dumps({"error": str(e)[:200]}))
33
+ elif kind == "tiles":
34
+ cols, rows, tw, th = map(int, sys.argv[3:7])
35
+ img = Image.open(path).convert("L")
36
+ out = []
37
+ for r in range(rows):
38
+ for c in range(cols):
39
+ box = img.crop((c * tw + tw // 4, r * th + th // 4, c * tw + 3 * tw // 4, r * th + 3 * th // 4))
40
+ px = list(box.getdata()); out.append(sum(px) / len(px))
41
+ print(json.dumps({"size": img.size, "tiles": out}))
42
+ '''
43
+
44
+
45
+ def ffprobe(path: Path, cwd: Path) -> dict:
46
+ code, out = runner.run(f"ffprobe -v error -show_streams -show_format -of json '{path}'", cwd, timeout=30)
47
+ try:
48
+ return json.loads(out)
49
+ except json.JSONDecodeError:
50
+ return {}
51
+
52
+
53
+ def frame_tiny(path: Path, t: float, cwd: Path) -> list[int] | None:
54
+ """A 16x9 grayscale thumbnail of the frame at time t (seconds)."""
55
+ code, out = runner.run(f"ffmpeg -v error -ss {t:.3f} -i '{path}' -frames:v 1 -vf scale=16:9,format=gray "
56
+ "-f rawvideo - | od -An -v -tu1", cwd, timeout=30)
57
+ vals = [int(v) for v in out.split() if v.isdigit()]
58
+ return vals if len(vals) == 144 else None
59
+
60
+
61
+ def mad(a, b) -> float:
62
+ return sum(abs(x - y) for x, y in zip(a, b)) / max(1, len(a))
63
+
64
+
65
+ class MediaTools(CodingTask):
66
+ family = "media"
67
+ levels = (1, 2)
68
+ max_steps = 24
69
+
70
+ @staticmethod
71
+ def groups():
72
+ return ["production"]
73
+
74
+ def setup(self):
75
+ self.domain = "media-content-production"
76
+ self.private = Path(tempfile.mkdtemp(prefix="media-ref-")) # root-only copy of the inputs
77
+ self.variant = self.rng.randrange(4)
78
+ for attempt in range(20): # generators assert their own invariants; redraw until they hold
79
+ try:
80
+ getattr(self, f"_v{self.variant}")()
81
+ break
82
+ except AssertionError:
83
+ for d in (self.ws, self.private):
84
+ for p in d.iterdir():
85
+ shutil.rmtree(p) if p.is_dir() else p.unlink()
86
+ else:
87
+ raise RuntimeError("could not generate a media task")
88
+ (self.ws / "spec.md").write_text(self.spec)
89
+ (self.ws / "notes.md").write_text("# Production notes\n\n" + "\n".join(f"- {n}" for n in self.notes) + "\n")
90
+
91
+ def close(self):
92
+ super().close()
93
+ if getattr(self, "private", None):
94
+ shutil.rmtree(self.private, ignore_errors=True)
95
+
96
+ def _sh(self, cmd: str, cwd: Path, timeout: int = 60):
97
+ code, out = runner.run(cmd, cwd, timeout=timeout)
98
+ assert code == 0, out[-500:]
99
+
100
+ # -- variant 0: trimmed, scaled clip ---------------------------------------------------------------
101
+ def _v0(self):
102
+ r = self.rng
103
+ dur = r.choice([12, 14, 16])
104
+ self.a = r.randint(2, dur - 7)
105
+ self.b = self.a + r.randint(3, 5)
106
+ self.w = r.choice([320, 426, 480])
107
+ self.fps = r.choice([12, 15, 24])
108
+ self.mono = r.random() < 0.5
109
+ self._sh(f"ffmpeg -v error -f lavfi -i testsrc2=size=640x360:rate=30:duration={dur} -f lavfi "
110
+ f"-i sine=frequency={r.choice([330, 440, 550])}:duration={dur} -ac 2 -c:v libx264 -preset ultrafast "
111
+ "-pix_fmt yuv420p -c:a aac -shortest input.mp4", self.ws, 120)
112
+ shutil.copy(self.ws / "input.mp4", self.private / "input.mp4")
113
+ self.ref = [frame_tiny(self.ws / "input.mp4", t + 0.05, self.ws) for t in (self.a, self.a - 1, self.a + 1)]
114
+ assert all(self.ref)
115
+ self.out = "deliver/clip.mp4"
116
+ self.spec = (f"# Clip delivery\n\nFrom input.mp4, deliver the segment from {self.a} s to {self.b} s as "
117
+ f"{self.out}: H.264 video, {self.w} pixels wide with the aspect ratio kept (even height), "
118
+ f"{self.fps} frames per second.\n")
119
+ self.notes = ["The client's player needs the audio track kept, downmixed to mono (one channel)."
120
+ if self.mono else "The client will add their own music: deliver the clip with no audio track."]
121
+
122
+ def _g0(self, path: Path) -> bool:
123
+ info = ffprobe(path, self.ws)
124
+ streams = info.get("streams", [])
125
+ video = [s for s in streams if s.get("codec_type") == "video"]
126
+ audio = [s for s in streams if s.get("codec_type") == "audio"]
127
+ if len(video) != 1 or video[0].get("codec_name") != "h264":
128
+ return False
129
+ v = video[0]
130
+ h = round(self.w * 360 / 640 / 2) * 2
131
+ if v.get("width") != self.w or abs(int(v.get("height", 0)) - h) > 2:
132
+ return False
133
+ num, _, den = str(v.get("avg_frame_rate", "0/1")).partition("/")
134
+ try:
135
+ fps = float(num) / float(den or 1)
136
+ except (ValueError, ZeroDivisionError):
137
+ return False
138
+ if abs(fps - self.fps) > 0.5:
139
+ return False
140
+ try:
141
+ duration = float(info.get("format", {}).get("duration", 0))
142
+ except ValueError:
143
+ return False
144
+ if abs(duration - (self.b - self.a)) > 0.25:
145
+ return False
146
+ if self.mono != (len(audio) == 1 and audio[0].get("channels") == 1) or (not self.mono and audio):
147
+ return False
148
+ first = frame_tiny(path, 0.05, self.ws)
149
+ if first is None:
150
+ return False
151
+ right, before, after = (mad(first, ref) for ref in self.ref)
152
+ return right < 12 and right < before and right < after
153
+
154
+ # -- variant 1: thumbnails -------------------------------------------------------------------------
155
+ def _photos(self, n):
156
+ from PIL import Image, ImageDraw
157
+ r = self.rng
158
+ self.photos = []
159
+ (self.ws / "photos").mkdir()
160
+ for i in range(n):
161
+ w, h = r.choice([(640, 480), (800, 600), (480, 640), (1024, 768), (240, 180), (200, 260)])
162
+ img = Image.new("RGB", (w, h), tuple(r.randint(30, 220) for _ in range(3)))
163
+ d = ImageDraw.Draw(img)
164
+ d.rectangle([0, 0, w // 3, h // 3], fill=(250, 250, 250)) # a bright corner shows orientation
165
+ d.ellipse([w // 3, h // 3, 2 * w // 3, 2 * h // 3], fill=tuple(r.randint(0, 255) for _ in range(3)))
166
+ orient = r.choice([1, 1, 3, 6, 8])
167
+ exif = Image.Exif()
168
+ exif[0x0112] = orient
169
+ exif[0x9003] = f"2026:0{r.randint(1, 9)}:{r.randint(10, 28)} {r.randint(10, 19)}:{r.randint(10, 59)}:00"
170
+ stem = f"IMG_{r.randint(1000, 9999)}"
171
+ while any(p[0] == stem for p in self.photos):
172
+ stem = f"IMG_{r.randint(1000, 9999)}"
173
+ img.save(self.private / f"{stem}.jpg", quality=92, exif=exif)
174
+ shutil.copy(self.private / f"{stem}.jpg", self.ws / "photos" / f"{stem}.jpg")
175
+ self.photos.append((stem, img.size, orient, exif[0x9003]))
176
+
177
+ def _v1(self):
178
+ from PIL import Image, ImageOps
179
+ r = self.rng
180
+ self._photos(r.randint(5, 8))
181
+ self.size = r.choice([128, 160, 200])
182
+ self.min_side = 300
183
+ self.expected = {}
184
+ for stem, (w, h), _, _ in self.photos:
185
+ if min(w, h) < self.min_side:
186
+ continue
187
+ img = ImageOps.exif_transpose(Image.open(self.private / f"{stem}.jpg"))
188
+ thumb = ImageOps.fit(img, (self.size, self.size))
189
+ self.expected[stem] = list(ImageOps.fit(thumb.convert("L"), (8, 8)).getdata())
190
+ assert 2 <= len(self.expected) < len(self.photos)
191
+ self.spec = (f"# Thumbnails\n\nFor every photo in photos/, make a square {self.size}x{self.size} thumbnail: "
192
+ "the photo shown upright (as a phone would display it), scaled to cover the square and "
193
+ "centre-cropped. Save each as PNG in thumbs/ with the photo's name, e.g. thumbs/IMG_1234.png.\n")
194
+ self.notes = [f"Skip photos smaller than {self.min_side} pixels on their short side; no thumbnails for "
195
+ "those (they are placeholders)."]
196
+
197
+ def _g1(self) -> bool:
198
+ thumbs = self.ws / "thumbs"
199
+ if not thumbs.is_dir():
200
+ return False
201
+ got = {p.stem: p for p in thumbs.iterdir() if p.suffix.lower() == ".png"}
202
+ if set(got) != set(self.expected):
203
+ return False
204
+ for stem, ref in self.expected.items():
205
+ stats = self._analyze("image", got[stem])
206
+ if stats.get("format") != "PNG" or tuple(stats.get("size", ())) != (self.size, self.size):
207
+ return False
208
+ if mad(stats["tiny"], ref) > 14:
209
+ return False
210
+ return True
211
+
212
+ # -- variant 2: contact sheet ----------------------------------------------------------------------
213
+ def _v2(self):
214
+ from PIL import Image, ImageOps
215
+ r = self.rng
216
+ self._photos(6)
217
+ assert len({p[3] for p in self.photos}) == 6 and sorted(self.photos, key=lambda p: p[3]) != sorted(self.photos)
218
+ self.cols, self.rows = (3, 2) if r.random() < 0.5 else (2, 3)
219
+ self.tw, self.th = r.choice([(160, 120), (200, 150)])
220
+ order = sorted(self.photos, key=lambda p: p[3])
221
+ self.expected = []
222
+ for stem, *_ in order:
223
+ img = ImageOps.exif_transpose(Image.open(self.private / f"{stem}.jpg"))
224
+ tile = ImageOps.fit(img, (self.tw, self.th)).convert("L")
225
+ box = tile.crop((self.tw // 4, self.th // 4, 3 * self.tw // 4, 3 * self.th // 4))
226
+ px = list(box.getdata())
227
+ self.expected.append(sum(px) / len(px))
228
+ self.out = "sheet.png"
229
+ self.spec = (f"# Contact sheet\n\nMake a contact sheet of the six photos in photos/ as {self.out}: a grid "
230
+ f"{self.cols} tiles wide and {self.rows} tall, each tile exactly {self.tw}x{self.th} pixels "
231
+ "(photo upright, scaled to cover and centre-cropped), no borders or gaps, filled left to right "
232
+ "then top to bottom.\n")
233
+ self.notes = ["Order the photos by when they were taken (EXIF DateTimeOriginal), earliest first, not by "
234
+ "file name."]
235
+
236
+ def _g2(self) -> bool:
237
+ path = self.ws / self.out
238
+ if not path.is_file():
239
+ return False
240
+ stats = self._analyze("tiles", path, self.cols, self.rows, self.tw, self.th)
241
+ if tuple(stats.get("size", ())) != (self.cols * self.tw, self.rows * self.th):
242
+ return False
243
+ return all(abs(a - b) <= 12 for a, b in zip(stats["tiles"], self.expected))
244
+
245
+ # -- variant 3: audio delivery ---------------------------------------------------------------------
246
+ def _v3(self):
247
+ r = self.rng
248
+ self.lead = r.choice([1.0, 1.5, 2.0])
249
+ self.rate = r.choice([16000, 22050, 24000])
250
+ self.peak = r.choice([-1.0, -2.0, -3.0])
251
+ self.trim = r.random() < 0.5
252
+ self._sh(f"ffmpeg -v error -f lavfi -i anullsrc=r=44100:cl=stereo:d={self.lead} -f lavfi "
253
+ f"-i sine=frequency={r.choice([300, 500, 700])}:duration=4:sample_rate=44100 "
254
+ "-filter_complex '[1]volume=-14dB,aformat=channel_layouts=stereo[t];[0][t]concat=n=2:v=0:a=1' "
255
+ "-c:a pcm_s16le take.wav", self.ws, 60)
256
+ shutil.copy(self.ws / "take.wav", self.private / "take.wav")
257
+ self.out = "deliver/voice.flac"
258
+ self.spec = (f"# Audio delivery\n\nDeliver take.wav as {self.out}: FLAC, mono, {self.rate} Hz, normalised so "
259
+ f"the peak sample is at {self.peak:g} dBFS (within 0.5 dB).\n")
260
+ self.notes = ["Cut the silence at the start: the delivery must begin within 0.1 s of the first sound."
261
+ if self.trim else "Keep the timing exactly as recorded, including the silence at the start."]
262
+
263
+ def _g3(self) -> bool:
264
+ path = self.ws / self.out
265
+ info = ffprobe(path, self.ws)
266
+ audio = [s for s in info.get("streams", []) if s.get("codec_type") == "audio"]
267
+ if len(audio) != 1 or audio[0].get("codec_name") != "flac" or audio[0].get("channels") != 1:
268
+ return False
269
+ if int(audio[0].get("sample_rate", 0)) != self.rate:
270
+ return False
271
+ code, out = runner.run(f"ffmpeg -v error -i '{path}' -f s16le -ac 1 - | od -An -v -td2", self.ws, timeout=30)
272
+ samples = [int(v) for v in out.split() if v.lstrip("-").isdigit()]
273
+ if not samples:
274
+ return False
275
+ peak = max(abs(s) for s in samples)
276
+ if peak == 0 or abs(20 * math.log10(peak / 32768) - self.peak) > 0.5:
277
+ return False
278
+ first = next(i for i, s in enumerate(samples) if abs(s) > peak * 0.05) / self.rate
279
+ return first <= 0.1 if self.trim else abs(first - self.lead) <= 0.1
280
+
281
+ # -- shared ----------------------------------------------------------------------------------------
282
+ def _analyze(self, *args) -> dict:
283
+ script = self.private / "analyze.py"
284
+ script.write_text(ANALYZE)
285
+ # copy the script where nobody can read it but the policy cannot have changed it
286
+ tmp = runner.new_workspace("an-")
287
+ try:
288
+ shutil.copy(script, tmp / "analyze.py")
289
+ target = Path(args[1])
290
+ shutil.copy(target, tmp / ("in" + target.suffix))
291
+ runner.give_to_nobody(tmp)
292
+ extra = " ".join(str(a) for a in args[2:])
293
+ code, out = runner.run(f"python -I analyze.py {args[0]} in{target.suffix} {extra}", tmp, timeout=30)
294
+ finally:
295
+ runner.remove(tmp)
296
+ try:
297
+ return json.loads(out.strip().splitlines()[-1])
298
+ except (json.JSONDecodeError, IndexError):
299
+ return {}
300
+
301
+ def brief(self):
302
+ pointer = " Read spec.md and notes.md first." if self.level == 1 else " The brief is in spec.md."
303
+ return ("MEDIA. Production desk. Produce the deliverable described in this workspace with the tools on this "
304
+ f"machine (ffmpeg, ffprobe, ImageMagick's magick/convert, Python with Pillow).{pointer} Submit when "
305
+ "the files are in place.")
306
+
307
+ def tools(self):
308
+ return self.coding_tools(tests=False) + [Tool("submit", "submit the deliverable (ends the episode)",
309
+ self.grade, final=True)]
310
+
311
+ def grade(self, a=None) -> float:
312
+ try:
313
+ if self.variant == 0:
314
+ return float(self._g0(self.ws / self.out))
315
+ return float(getattr(self, f"_g{self.variant}")())
316
+ except Exception:
317
+ return 0.0
318
+
319
+ def oracle(self):
320
+ """Produce a correct deliverable with the tools (used by tests)."""
321
+ if self.variant == 0:
322
+ audio = "-ac 1 -c:a aac" if self.mono else "-an"
323
+ cmd = (f"mkdir -p deliver && ffmpeg -v error -y -ss {self.a} -i input.mp4 -t {self.b - self.a} "
324
+ f"-vf scale={self.w}:-2,fps={self.fps} -c:v libx264 -preset ultrafast {audio} {self.out}")
325
+ elif self.variant == 1:
326
+ keep = " ".join(f"'{s}'" for s in self.expected)
327
+ cmd = ("mkdir -p thumbs && python -c \"import sys\nfrom PIL import Image, ImageOps\nfor s in sys.argv[1:]:\n"
328
+ f" ImageOps.fit(ImageOps.exif_transpose(Image.open(f'photos/{{s}}.jpg')), ({self.size},{self.size}))"
329
+ f".save(f'thumbs/{{s}}.png')\" {keep}")
330
+ elif self.variant == 2:
331
+ order = " ".join(p[0] for p in sorted(self.photos, key=lambda p: p[3]))
332
+ cmd = ("python -c \"import sys\nfrom PIL import Image, ImageOps\n"
333
+ f"sheet = Image.new('RGB', ({self.cols * self.tw}, {self.rows * self.th}))\n"
334
+ "for i, s in enumerate(sys.argv[1:]):\n"
335
+ f" t = ImageOps.fit(ImageOps.exif_transpose(Image.open(f'photos/{{s}}.jpg')), ({self.tw},{self.th}))\n"
336
+ f" sheet.paste(t, ((i % {self.cols}) * {self.tw}, (i // {self.cols}) * {self.th}))\n"
337
+ f"sheet.save('{self.out}')\" {order}")
338
+ else:
339
+ trim = "silenceremove=start_periods=1:start_threshold=-50dB," if self.trim else ""
340
+ cmd = (f"mkdir -p deliver && ffmpeg -v error -y -i take.wav -af {trim}aresample={self.rate} -ac 1 tmp.wav "
341
+ f"&& G=$(ffmpeg -i tmp.wav -af volumedetect -f null - 2>&1 | sed -n 's/.*max_volume: \\(.*\\) dB/\\1/p') "
342
+ f"&& ffmpeg -v error -y -i tmp.wav -af volume=$(python -c \"print({self.peak} - ($G))\")dB "
343
+ f"-ar {self.rate} -ac 1 {self.out} && rm tmp.wav")
344
+ code, out = runner.run(cmd, self.ws, timeout=120)
345
+ assert code == 0, out[-800:]
source/codedesk/interface.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-episode tool and argument names.
2
+
3
+ Every private arena task brings its own interface. If one task always calls its tools read_file and run_tests, a
4
+ policy can memorise the names instead of reading the tool list. Each reset therefore draws names from these pools
5
+ (the canonical name is one of the options). `submit` keeps its name and arguments: it is also the arena's finish
6
+ action.
7
+ """
8
+
9
+ import random
10
+ import re
11
+
12
+ from .base import Tool
13
+
14
+ TOOL_NAMES = {
15
+ "list_files": ["list_files", "ls", "tree", "list_dir"],
16
+ "read_file": ["read_file", "open_file", "cat", "view_file", "show_file"],
17
+ "search": ["search", "grep", "find_text", "search_code"],
18
+ "edit_file": ["edit_file", "str_replace", "replace_in_file", "patch_file"],
19
+ "write_file": ["write_file", "save_file", "create_file", "put_file"],
20
+ "run": ["run", "bash", "shell", "exec", "run_command"],
21
+ "run_tests": ["run_tests", "pytest", "test", "check_tests"],
22
+ }
23
+ ARG_NAMES = {
24
+ "path": ["path", "file", "filename"],
25
+ "start": ["start", "from_line", "first"],
26
+ "end": ["end", "to_line", "last"],
27
+ "pattern": ["pattern", "regex", "query"],
28
+ "old": ["old", "old_str", "find", "before"],
29
+ "new": ["new", "new_str", "replace", "after"],
30
+ "content": ["content", "text", "body"],
31
+ "command": ["command", "cmd", "script"],
32
+ "target": ["target", "path", "tests"],
33
+ }
34
+ # Names that are also ordinary words ("the style guide", "check how...") are renamed in the tool list but not in
35
+ # running text; the others are replaced wherever they appear as a word.
36
+ TEXT_SAFE = {name for name in TOOL_NAMES if "_" in name}
37
+
38
+
39
+ class Interface:
40
+ def __init__(self, tools: list[Tool], rng: random.Random):
41
+ self.tool_names, used = {}, {"submit"}
42
+ for tool in tools:
43
+ options = [n for n in TOOL_NAMES.get(tool.name, [tool.name]) if n not in used] or [tool.name]
44
+ name = tool.name if tool.name == "submit" else rng.choice(options)
45
+ used.add(name)
46
+ self.tool_names[tool.name] = name
47
+ pairs = [(old, new) for old, new in self.tool_names.items() if old in TEXT_SAFE and old != new]
48
+ self._pattern = re.compile(r"\b(" + "|".join(re.escape(old) for old, _ in pairs) + r")\b") if pairs else None
49
+ self._lookup = dict(pairs)
50
+ self.tools = [self._rename(tool, rng) for tool in tools]
51
+
52
+ def _rename(self, tool: Tool, rng: random.Random) -> Tool:
53
+ if tool.name == "submit":
54
+ return tool
55
+ args, used = {}, set()
56
+ for arg in tool.args:
57
+ options = [n for n in ARG_NAMES.get(arg, [arg]) if n not in used] or [arg]
58
+ args[arg] = rng.choice(options)
59
+ used.add(args[arg])
60
+ back = {new: old for old, new in args.items()}
61
+
62
+ def fn(a, _fn=tool.fn):
63
+ return _fn({back.get(k, k): v for k, v in a.items()})
64
+
65
+ return Tool(self.tool_names[tool.name], self.text(tool.help), fn,
66
+ {args[k]: t for k, t in tool.args.items()}, tuple(args[k] for k in tool.optional), tool.final)
67
+
68
+ def text(self, s: str) -> str:
69
+ """Rewrite canonical tool names in briefs and tool output to this episode's names."""
70
+ if not self._pattern or not isinstance(s, str):
71
+ return s
72
+ return self._pattern.sub(lambda m: self._lookup[m.group(1)], s)
source/codedesk/models.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Action and observation models. One generic action serves every task: each task lists its own tools."""
2
+
3
+ from typing import Any
4
+
5
+ from openenv.core.env_server.types import Action, Observation
6
+ from pydantic import Field
7
+
8
+
9
+ class ToolAction(Action):
10
+ tool: str = Field(min_length=1, max_length=40, description="Name of one of the tools listed in the task.")
11
+ args: dict[str, Any] = Field(
12
+ default_factory=dict,
13
+ description="Arguments for that tool, exactly as the task lists them (an empty object if it takes none).",
14
+ )
15
+
16
+
17
+ class ToolObservation(Observation):
18
+ output: str = Field(default="", description="Result of the last tool call.")
19
+ steps_left: int = Field(default=0, description="Tool calls left before the episode ends.")
source/codedesk/requirements-tools.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # on top of requirements.lock (which already pins numpy, pillow, python-dateutil and pytz)
2
+ pytest==8.3.3
3
+ hypothesis==6.112.1
4
+ text-unidecode==1.3
5
+ freezegun==1.5.1
source/codedesk/runner.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-episode workspaces and command execution for the coding tasks.
2
+
3
+ The server runs as root inside its container; every command the policy runs, and every test run, executes as the
4
+ unprivileged `nobody` user in the episode's workspace, with CPU, memory, file-size and process limits applied by a
5
+ shell prelude (no preexec_fn, which can deadlock in threaded servers). The server's code and the bug catalog are
6
+ root-only, so the policy cannot read hidden tests or the original sources. Outside a root container (local
7
+ development) commands run as the current user.
8
+ """
9
+
10
+ import os
11
+ import shutil
12
+ import signal
13
+ import subprocess
14
+ import tempfile
15
+ import threading
16
+ from pathlib import Path
17
+
18
+ NOBODY = 65534
19
+ LIMITS = "ulimit -t 120 -v 4000000 -f 100000 -u 512 2>/dev/null; "
20
+ MAX_OUTPUT = 4000
21
+ _SLOTS = threading.BoundedSemaphore(4)
22
+ AS_ROOT = hasattr(os, "geteuid") and os.geteuid() == 0
23
+
24
+
25
+ def new_workspace(prefix: str = "ws-") -> Path:
26
+ path = Path(tempfile.mkdtemp(prefix=prefix))
27
+ if AS_ROOT:
28
+ os.chown(path, NOBODY, NOBODY)
29
+ path.chmod(0o755 if not AS_ROOT else 0o700)
30
+ return path
31
+
32
+
33
+ def give_to_nobody(root: Path):
34
+ if not AS_ROOT:
35
+ return
36
+ for dirpath, dirnames, filenames in os.walk(root):
37
+ os.chown(dirpath, NOBODY, NOBODY)
38
+ for name in filenames:
39
+ p = os.path.join(dirpath, name)
40
+ if not os.path.islink(p):
41
+ os.chown(p, NOBODY, NOBODY)
42
+
43
+
44
+ def remove(path: Path):
45
+ shutil.rmtree(path, ignore_errors=True)
46
+
47
+
48
+ def _drain(stream, chunks, keep=200_000):
49
+ kept = 0
50
+ while block := stream.read(8192):
51
+ if kept < keep:
52
+ chunks.append(block[:keep - kept])
53
+ kept += len(chunks[-1])
54
+
55
+
56
+ def run(command: str, cwd: Path, timeout: int = 60, env_extra: dict | None = None) -> tuple[int, str]:
57
+ """Run a shell command as nobody in cwd. Returns (exit code, combined output, tail-trimmed)."""
58
+ env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": str(cwd), "LANG": "C.UTF-8", "PYTHONDONTWRITEBYTECODE": "1",
59
+ "PYTHONPATH": f"{cwd}:{cwd}/src", "TMPDIR": str(cwd), "MPLBACKEND": "Agg", **(env_extra or {})}
60
+ kwargs = dict(user=NOBODY, group=NOBODY, extra_groups=[]) if AS_ROOT else {}
61
+ with _SLOTS:
62
+ proc = subprocess.Popen(["/bin/sh", "-c", LIMITS + command], cwd=cwd, env=env, stdin=subprocess.DEVNULL,
63
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace",
64
+ start_new_session=True, **kwargs)
65
+ chunks = []
66
+ reader = threading.Thread(target=_drain, args=(proc.stdout, chunks), daemon=True)
67
+ reader.start()
68
+ try:
69
+ proc.wait(timeout=timeout)
70
+ timed_out = False
71
+ except subprocess.TimeoutExpired:
72
+ timed_out = True
73
+ try: # stop everything the command started
74
+ os.killpg(proc.pid, signal.SIGKILL)
75
+ except (ProcessLookupError, PermissionError):
76
+ pass
77
+ proc.wait()
78
+ reader.join(2)
79
+ out = "".join(chunks)
80
+ if timed_out:
81
+ out += f"\n[timed out after {timeout} s]"
82
+ return (124 if timed_out else proc.returncode), out
83
+
84
+
85
+ def trim(out: str, limit: int = MAX_OUTPUT) -> str:
86
+ if len(out) <= limit:
87
+ return out
88
+ return f"[... {len(out) - limit} characters cut ...]\n" + out[-limit:]
source/codedesk/server/__init__.py ADDED
File without changes
source/codedesk/server/app.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openenv.core.env_server.http_server import create_app
2
+
3
+ from codedesk.environment import CodeEnvironment
4
+ from codedesk.models import ToolAction, ToolObservation
5
+
6
+ app = create_app(
7
+ CodeEnvironment,
8
+ ToolAction,
9
+ ToolObservation,
10
+ env_name="five_desks_code",
11
+ max_concurrent_envs=8,
12
+ )
source/codedesk/tests/__init__.py ADDED
File without changes
source/codedesk/tests/test_codedesk.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks for Five Desks Code. Run inside the image (the libraries' tests run here):
2
+
3
+ docker run --rm five-desks-code:test python -m pytest -q /app/codedesk/tests
4
+ """
5
+
6
+ import os
7
+
8
+ import pytest
9
+
10
+ from codedesk import runner
11
+ from codedesk.environment import CodeEnvironment, build, task_ids
12
+ from codedesk.models import ToolAction
13
+
14
+ SEEDS = range(3)
15
+
16
+
17
+ @pytest.mark.parametrize("task_id", task_ids())
18
+ def test_oracle_scores_one_and_untouched_scores_zero(task_id):
19
+ for seed in SEEDS:
20
+ task = build(task_id, seed)
21
+ try:
22
+ assert task.grade({}) == 0.0, (task_id, seed, "untouched workspace must fail")
23
+ task.oracle()
24
+ assert task.grade({}) == 1.0, (task_id, seed, "oracle must pass")
25
+ finally:
26
+ task.close()
27
+
28
+
29
+ def test_bugfix_ignores_test_edits_and_config():
30
+ ids = [t for t in task_ids() if t.startswith("bugfix-") and t.endswith("-l1")]
31
+ for task_id in ids[:4]:
32
+ task = build(task_id, 1)
33
+ try:
34
+ for key in task.killed: # gut the test files and add a conftest that skips everything
35
+ path = task.ws / key.split("::")[0]
36
+ if path.exists():
37
+ path.write_text("def test_nothing():\n pass\n")
38
+ (task.ws / "conftest.py").write_text("import pytest\ncollect_ignore_glob = ['*']\n")
39
+ assert task.grade({}) == 0.0, task_id
40
+ finally:
41
+ task.close()
42
+
43
+
44
+ def test_bugfix_package_symlink_out_scores_zero():
45
+ task_id = next(t for t in task_ids() if t.startswith("bugfix-") and t.endswith("-l1"))
46
+ task = build(task_id, 2)
47
+ try:
48
+ pkg = task.ws / task.pkg
49
+ target = pkg / "evil_link" if pkg.is_dir() else task.ws / "evil_link"
50
+ os.symlink("/etc/passwd", target)
51
+ task.oracle()
52
+ if pkg.is_dir():
53
+ assert task.grade({}) == 0.0
54
+ finally:
55
+ task.close()
56
+
57
+
58
+ def test_level2_removes_the_catching_tests():
59
+ for task_id in [t for t in task_ids() if t.startswith("bugfix-") and t.endswith("-l2")]:
60
+ task = build(task_id, 0)
61
+ try:
62
+ for key in task.killed:
63
+ path = task.ws / key.split("::")[0]
64
+ name = key.split("::")[-1].split("[")[0]
65
+ if path.exists():
66
+ assert f"def {name}(" not in path.read_text(), (task_id, key)
67
+ assert "pytest '" not in (task.ws / "ISSUE.md").read_text()
68
+ finally:
69
+ task.close()
70
+
71
+
72
+ def test_policy_commands_cannot_read_the_server():
73
+ if not runner.AS_ROOT:
74
+ pytest.skip("only meaningful in the root container")
75
+ task = build(next(t for t in task_ids() if t.startswith("bugfix-")), 0)
76
+ try:
77
+ code, out = runner.run("id -u; cat /app/codedesk/data/catalog.json | head -c 50", task.ws)
78
+ assert out.splitlines()[0] == "65534"
79
+ assert "Permission denied" in out
80
+ finally:
81
+ task.close()
82
+
83
+
84
+ def test_episode_flow_with_random_names_and_finish():
85
+ env = CodeEnvironment()
86
+ for task_id in task_ids()[:6]:
87
+ obs = env.reset(task_id=task_id, seed=4)
88
+ assert "Tools:" in obs.output and not obs.done
89
+ obs = env.step(ToolAction(tool="submit", args={}))
90
+ assert obs.done and obs.reward == 0.0, task_id
91
+ obs = env.reset(task_id=task_ids()[0], seed=5)
92
+ names = [line.split()[1] for line in obs.output.split("Tools:")[1].splitlines() if line.startswith("- ")]
93
+ listing = next(n for n in names if n in ("list_files", "ls", "tree", "list_dir"))
94
+ out = env.step(ToolAction(tool=listing, args={})).output
95
+ assert "ISSUE.md" in out
96
+ unknown = env.step(ToolAction(tool="no_such_tool", args={}))
97
+ assert "Unknown tool" in unknown.output and not unknown.done
98
+
99
+
100
+ def test_hostile_tool_calls_do_not_escape_or_crash():
101
+ env = CodeEnvironment()
102
+ env.reset(task_id=next(t for t in task_ids() if t.startswith("bugfix-")), seed=7, canonical_names=True)
103
+ calls = [
104
+ ("read_file", {"path": "../../etc/passwd"}), ("read_file", {"path": "/app/codedesk/data/catalog.json"}),
105
+ ("write_file", {"path": "../escape.txt", "content": "x"}), ("write_file", {"path": "/tmp/x", "content": "x"}),
106
+ ("edit_file", {"path": "/etc/hostname", "old": "a", "new": "b"}), ("list_files", {"path": "/"}),
107
+ ("search", {"pattern": "(((", "path": "."}), ("search", {"pattern": "x", "path": "/app"}),
108
+ ("run", {"command": "yes | head -c 10000000"}), ("run", {"command": "sleep 100"}),
109
+ ("run", {"command": ":(){ :|:& };:"}), ("run", {"command": "cat /app/codedesk/data/catalog.json"}),
110
+ ("run", {"command": "python -c 'import os; os.kill(1, 9)'"}), ("read_file", {"path": "ISSUE.md", "start": -5, "end": 10**9}),
111
+ ("run_tests", {"target": "/etc"}), ("run_tests", {"target": "; rm -rf /"}),
112
+ ]
113
+ for tool, args in calls:
114
+ obs = env.step(ToolAction(tool=tool, args=args))
115
+ assert not obs.done, (tool, args)
116
+ assert len(obs.output) <= 7000
117
+ assert '"cases"' not in obs.output and '"killed"' not in obs.output, (tool, args, obs.output[:200])
118
+ assert not (env._task.ws.parent / "escape.txt").exists()
119
+ obs = env.step(ToolAction(tool="submit", args={}))
120
+ assert obs.done and obs.reward == 0.0
source/proxy_eval/run.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Play Qwen3.8-27B (thinking off) on the proxy tasks with arena-style prompts.
2
+
3
+ Each episode is scored twice from one conversation:
4
+ - strict: the arena's rule. A reply that is not exactly one JSON object, or an action that fails the task's
5
+ schema, ends the episode and the task scores its finish_action.
6
+ - lenient: the conversation continues (first JSON object in the reply is used; schema errors are reported back
7
+ to the model), to show what the model would reach without format failures.
8
+
9
+ Usage: HF_TOKEN_PATH=... .venv/bin/python -m proxy_eval.run --samples 2 --out reports/proxy/run1
10
+ """
11
+
12
+ import argparse
13
+ import copy
14
+ import json
15
+ import sys
16
+ import time
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from pathlib import Path
19
+ from statistics import mean
20
+
21
+ from pydantic import ValidationError
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
24
+
25
+ from calibrate import Model, first_json_object, system_prompt # noqa: E402
26
+
27
+ from .tasks import FAMILIES # noqa: E402
28
+
29
+
30
+ def classify(reply: str):
31
+ s = reply.strip()
32
+ if not s:
33
+ return None, "empty"
34
+ try:
35
+ obj = json.loads(s)
36
+ return (obj, None) if isinstance(obj, dict) else (None, "not_object")
37
+ except json.JSONDecodeError:
38
+ pass
39
+ if s.startswith("```"):
40
+ return None, "code_fence"
41
+ if first_json_object(s) is not None:
42
+ return None, "json_plus_text"
43
+ return None, "no_json"
44
+
45
+
46
+ def unwrap(action):
47
+ if isinstance(action, dict) and set(action) == {"action"} and isinstance(action["action"], dict):
48
+ return action["action"]
49
+ return action
50
+
51
+
52
+ def finish_score(task):
53
+ """Reward the arena would record if the episode were ended now through finish_action."""
54
+ if task.done:
55
+ return None
56
+ try:
57
+ clone = copy.deepcopy(task)
58
+ except TypeError: # tasks holding a database connection score 0 on an empty finish
59
+ return 0.0
60
+ return clone.step(clone.Action.model_validate(task.finish_action)).reward
61
+
62
+
63
+ def play(task, model, completion_budget, context_budget, system_extra=""):
64
+ schema = task.Action.model_json_schema()
65
+ messages = [{"role": "system", "content": system_prompt(schema) + system_extra}]
66
+ obs = task.reset()
67
+ ep = {"task_id": task.task_id, "family": task.family, "domain": task.domain, "turns": [],
68
+ "strict": None, "lenient": None, "strict_end": None, "lenient_end": None, "schema_errors": 0}
69
+ completion_used = 0
70
+ first = True
71
+
72
+ def strict_fail(kind):
73
+ if ep["strict"] is None:
74
+ ep["strict"], ep["strict_end"] = finish_score(task) or 0.0, kind
75
+
76
+ while True:
77
+ obs_text = json.dumps(obs)
78
+ messages.append({"role": "user", "content": obs_text})
79
+ if not first:
80
+ completion_used += len(obs_text) // 3
81
+ first = False
82
+ if completion_used >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget:
83
+ strict_fail("budget")
84
+ ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, "budget"
85
+ break
86
+ reply, used, finish_reason = model.chat(messages)
87
+ completion_used += used
88
+ messages.append({"role": "assistant", "content": reply})
89
+ ep["turns"].append({"obs": obs_text[:1500], "reply": reply[:1500], "tokens": used})
90
+ if finish_reason == "length":
91
+ strict_fail("truncated")
92
+ ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, "truncated"
93
+ break
94
+ strict_obj, kind = classify(reply)
95
+ if kind:
96
+ strict_fail(kind)
97
+ action = unwrap(strict_obj if strict_obj is not None else first_json_object(reply))
98
+ if action is None:
99
+ ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, kind
100
+ break
101
+ if action.get("finish") is True:
102
+ score = finish_score(task) or 0.0
103
+ strict_fail("finish")
104
+ ep["lenient"], ep["lenient_end"] = score, "finish"
105
+ break
106
+ try:
107
+ parsed = task.Action.model_validate(action)
108
+ except ValidationError as exc:
109
+ ep["schema_errors"] += 1
110
+ strict_fail("schema_invalid")
111
+ errors = "; ".join(f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in exc.errors()[:3])
112
+ obs = {"error": f"Invalid action: {errors}"}
113
+ if task.steps + ep["schema_errors"] > task.max_steps + 3:
114
+ ep["lenient"], ep["lenient_end"] = finish_score(task) or 0.0, "schema_invalid"
115
+ break
116
+ continue
117
+ step = task.step(parsed)
118
+ obs = step.observation
119
+ if step.done:
120
+ if ep["strict"] is None:
121
+ ep["strict"], ep["strict_end"] = step.reward, "done"
122
+ ep["lenient"], ep["lenient_end"] = step.reward, "done"
123
+ break
124
+ ep["n_turns"] = len(ep["turns"])
125
+ return ep
126
+
127
+
128
+ def main():
129
+ parser = argparse.ArgumentParser()
130
+ parser.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra")
131
+ parser.add_argument("--families", default="", help="comma-separated family prefixes (default: all)")
132
+ parser.add_argument("--seeds", default="0-4")
133
+ parser.add_argument("--samples", type=int, default=2)
134
+ parser.add_argument("--workers", type=int, default=8)
135
+ parser.add_argument("--temperature", type=float, default=1.0)
136
+ parser.add_argument("--max-tokens", type=int, default=2048)
137
+ parser.add_argument("--completion-budget", type=int, default=8192)
138
+ parser.add_argument("--context-budget", type=int, default=16384)
139
+ parser.add_argument("--thinking", action="store_true", help="enable the model's thinking mode")
140
+ parser.add_argument("--system-extra", default="", help="file whose text is appended to the system prompt "
141
+ "(to imitate a model that has learned a habit)")
142
+ parser.add_argument("--out", required=True)
143
+ args = parser.parse_args()
144
+ extra = "\n\n" + Path(args.system_extra).read_text().strip() if args.system_extra else ""
145
+
146
+ lo, hi = map(int, args.seeds.split("-"))
147
+ fams = [f for f in FAMILIES if not args.families or any(f.startswith(p) for p in args.families.split(","))]
148
+ jobs = [(f, s) for f in fams for s in range(lo, hi + 1) for _ in range(args.samples)]
149
+ model = Model(args.model, args.max_tokens, args.temperature, args.thinking)
150
+ out = Path(args.out)
151
+ out.mkdir(parents=True, exist_ok=True)
152
+ started, results = time.monotonic(), []
153
+
154
+ def run(job):
155
+ fam, seed = job
156
+ return play(FAMILIES[fam](seed), model, args.completion_budget, args.context_budget, extra)
157
+
158
+ with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log:
159
+ for fut in [pool.submit(run, j) for j in jobs]:
160
+ try:
161
+ ep = fut.result()
162
+ except Exception as exc: # infrastructure errors are excluded, not scored
163
+ print("episode error:", repr(exc)[:300], file=sys.stderr)
164
+ continue
165
+ results.append(ep)
166
+ log.write(json.dumps(ep) + "\n")
167
+ log.flush()
168
+
169
+ summary = {}
170
+ for fam in fams:
171
+ eps = [e for e in results if e["family"] == fam]
172
+ if not eps:
173
+ continue
174
+ ends = {}
175
+ for e in eps:
176
+ ends[e["strict_end"]] = ends.get(e["strict_end"], 0) + 1
177
+ summary[fam] = {"n": len(eps), "strict": round(mean(e["strict"] for e in eps), 3),
178
+ "lenient": round(mean(e["lenient"] for e in eps), 3), "strict_ends": ends,
179
+ "turns": round(mean(e["n_turns"] for e in eps), 1)}
180
+ report = {"model": args.model, "system_extra": args.system_extra, "temperature": args.temperature, "thinking": args.thinking, "episodes": len(results),
181
+ "seconds": round(time.monotonic() - started), "usage": model.usage, "families": summary,
182
+ "overall": {"strict": round(mean(e["strict"] for e in results), 3),
183
+ "lenient": round(mean(e["lenient"] for e in results), 3)}}
184
+ (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
185
+ print(f"{'family':24s} {'n':>3s} {'strict':>6s} {'lenient':>7s} strict ends")
186
+ for fam, s in summary.items():
187
+ print(f"{fam:24s} {s['n']:3d} {s['strict']:6.2f} {s['lenient']:7.2f} {s['strict_ends']}")
188
+ print("overall", report["overall"], "usage", model.usage, "seconds", report["seconds"])
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
source/requirements.lock ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file was autogenerated by uv via the following command:
2
+ # uv pip compile requirements.in --python-version 3.12 --python-platform x86_64-unknown-linux-gnu -o requirements.lock
3
+ aiofile==3.12.3
4
+ # via py-key-value-aio
5
+ annotated-doc==0.0.5
6
+ # via
7
+ # fastapi
8
+ # typer
9
+ annotated-types==0.8.0
10
+ # via pydantic
11
+ anyio==4.15.1
12
+ # via
13
+ # gradio
14
+ # httpx
15
+ # httpx2
16
+ # mcp
17
+ # openai
18
+ # py-key-value-aio
19
+ # sse-starlette
20
+ # starlette
21
+ # watchfiles
22
+ attrs==26.1.0
23
+ # via
24
+ # cyclopts
25
+ # jsonschema
26
+ # jsonschema-path
27
+ # referencing
28
+ authlib==1.8.0
29
+ # via fastmcp-slim
30
+ beartype==0.22.9
31
+ # via py-key-value-aio
32
+ brotli==1.2.0
33
+ # via gradio
34
+ cachetools==7.2.1
35
+ # via py-key-value-aio
36
+ caio==0.12.9
37
+ # via aiofile
38
+ certifi==2026.7.22
39
+ # via
40
+ # httpcore
41
+ # httpx
42
+ # requests
43
+ cffi==2.1.1
44
+ # via cryptography
45
+ charset-normalizer==3.5.2
46
+ # via requests
47
+ click==8.5.0
48
+ # via
49
+ # huggingface-hub
50
+ # uvicorn
51
+ cryptography==50.0.2
52
+ # via
53
+ # authlib
54
+ # joserfc
55
+ # pyjwt
56
+ # secretstorage
57
+ cyclopts==5.2.0
58
+ # via fastmcp-slim
59
+ dnspython==2.9.0
60
+ # via email-validator
61
+ docstring-parser==0.18.0
62
+ # via cyclopts
63
+ email-validator==2.3.0
64
+ # via pydantic
65
+ exceptiongroup==1.3.1
66
+ # via fastmcp-slim
67
+ fastapi==0.143.0
68
+ # via
69
+ # gradio
70
+ # openenv
71
+ fastmcp==3.4.8
72
+ # via openenv
73
+ fastmcp-slim==3.4.8
74
+ # via fastmcp
75
+ filelock==4.0.12
76
+ # via huggingface-hub
77
+ fsspec==2026.9.0
78
+ # via
79
+ # gradio-client
80
+ # huggingface-hub
81
+ gradio==6.30.0
82
+ # via openenv
83
+ gradio-client==2.7.2
84
+ # via
85
+ # gradio
86
+ # hf-gradio
87
+ griffelib==2.3.2
88
+ # via fastmcp-slim
89
+ groovy==0.1.2
90
+ # via gradio
91
+ h11==0.16.0
92
+ # via
93
+ # httpcore
94
+ # httpcore2
95
+ # uvicorn
96
+ hf-gradio==0.4.1
97
+ # via gradio
98
+ hf-xet==1.7.0
99
+ # via huggingface-hub
100
+ httpcore==1.0.9
101
+ # via httpx
102
+ httpcore2==2.13.1
103
+ # via httpx2
104
+ httpx==0.28.1
105
+ # via
106
+ # fastmcp-slim
107
+ # gradio
108
+ # gradio-client
109
+ # mcp
110
+ # openenv
111
+ # safehttpx
112
+ httpx-sse==0.4.3
113
+ # via mcp
114
+ httpx2==2.13.1
115
+ # via
116
+ # huggingface-hub
117
+ # openai
118
+ huggingface-hub==2.2.0
119
+ # via
120
+ # gradio
121
+ # gradio-client
122
+ # openenv
123
+ idna==3.20
124
+ # via
125
+ # anyio
126
+ # email-validator
127
+ # httpx
128
+ # httpx2
129
+ # requests
130
+ jaraco-classes==3.4.0
131
+ # via keyring
132
+ jaraco-context==6.1.2
133
+ # via keyring
134
+ jaraco-functools==4.6.0
135
+ # via keyring
136
+ jeepney==0.9.0
137
+ # via
138
+ # keyring
139
+ # secretstorage
140
+ jinja2==3.1.6
141
+ # via gradio
142
+ jiter==0.17.0
143
+ # via openai
144
+ joserfc==1.7.5
145
+ # via
146
+ # authlib
147
+ # fastmcp-slim
148
+ jsonref==1.1.0
149
+ # via fastmcp-slim
150
+ jsonschema==4.26.0
151
+ # via mcp
152
+ jsonschema-path==0.5.0
153
+ # via fastmcp-slim
154
+ jsonschema-specifications==2025.9.1
155
+ # via jsonschema
156
+ keyring==25.7.0
157
+ # via py-key-value-aio
158
+ markdown-it-py==4.2.0
159
+ # via rich
160
+ markupsafe==3.0.4
161
+ # via
162
+ # gradio
163
+ # jinja2
164
+ mcp==1.30.0
165
+ # via fastmcp-slim
166
+ mdurl==0.1.2
167
+ # via markdown-it-py
168
+ more-itertools==11.1.0
169
+ # via
170
+ # jaraco-classes
171
+ # jaraco-functools
172
+ numpy==2.5.3
173
+ # via
174
+ # gradio
175
+ # pandas
176
+ openai==3.27.0
177
+ # via openenv
178
+ openapi-pydantic==0.6.0
179
+ # via fastmcp-slim
180
+ openenv @ git+https://github.com/meta-pytorch/OpenEnv.git@86a180ede21e044f7929b9a7783ad83aa67d83a3
181
+ # via -r requirements.in
182
+ opentelemetry-api==1.45.1
183
+ # via
184
+ # fastapi
185
+ # fastmcp-slim
186
+ orjson==3.13.0
187
+ # via gradio
188
+ packaging==26.3
189
+ # via
190
+ # fastmcp-slim
191
+ # gradio
192
+ # gradio-client
193
+ # huggingface-hub
194
+ # openenv
195
+ pandas==3.0.6
196
+ # via gradio
197
+ pathable==0.6.0
198
+ # via jsonschema-path
199
+ pillow==12.3.0
200
+ # via gradio
201
+ platformdirs==4.12.4
202
+ # via fastmcp-slim
203
+ py-key-value-aio==0.4.6
204
+ # via fastmcp-slim
205
+ pycparser==3.11
206
+ # via cffi
207
+ pydantic==2.14.0
208
+ # via
209
+ # fastapi
210
+ # fastmcp-slim
211
+ # gradio
212
+ # mcp
213
+ # openai
214
+ # openapi-pydantic
215
+ # openenv
216
+ # pydantic-settings
217
+ pydantic-core==2.50.0
218
+ # via pydantic
219
+ pydantic-settings==2.15.0
220
+ # via
221
+ # fastmcp-slim
222
+ # mcp
223
+ pydub==0.25.1
224
+ # via gradio
225
+ pygments==2.21.0
226
+ # via
227
+ # rich
228
+ # rich-rst
229
+ pyjwt==2.15.1
230
+ # via mcp
231
+ pyperclip==1.11.0
232
+ # via fastmcp-slim
233
+ python-dateutil==2.9.0.post0
234
+ # via pandas
235
+ python-dotenv==1.2.4
236
+ # via
237
+ # fastmcp-slim
238
+ # pydantic-settings
239
+ python-multipart==0.0.32
240
+ # via
241
+ # fastmcp-slim
242
+ # gradio
243
+ # mcp
244
+ pytz==2026.5
245
+ # via gradio
246
+ pyyaml==6.0.3
247
+ # via
248
+ # fastmcp-slim
249
+ # gradio
250
+ # huggingface-hub
251
+ # jsonschema-path
252
+ # openenv
253
+ referencing==0.37.0
254
+ # via
255
+ # jsonschema
256
+ # jsonschema-path
257
+ # jsonschema-specifications
258
+ requests==2.34.2
259
+ # via openenv
260
+ rich==15.0.0
261
+ # via
262
+ # cyclopts
263
+ # fastmcp-slim
264
+ # openenv
265
+ # rich-rst
266
+ # typer
267
+ rich-rst==2.2.0
268
+ # via cyclopts
269
+ rpds-py==2026.9.1
270
+ # via
271
+ # jsonschema
272
+ # referencing
273
+ safehttpx==0.1.7
274
+ # via gradio
275
+ secretstorage==3.5.0
276
+ # via keyring
277
+ semantic-version==2.10.0
278
+ # via gradio
279
+ shellingham==1.5.4
280
+ # via typer
281
+ six==1.17.0
282
+ # via python-dateutil
283
+ sniffio==1.3.1
284
+ # via openai
285
+ sse-starlette==3.5.0
286
+ # via mcp
287
+ starlette==1.7.0
288
+ # via
289
+ # fastapi
290
+ # fastmcp-slim
291
+ # gradio
292
+ # mcp
293
+ # sse-starlette
294
+ tomli==2.5.0
295
+ # via openenv
296
+ tomli-w==1.2.0
297
+ # via openenv
298
+ tomlkit==0.14.0
299
+ # via gradio
300
+ tqdm==4.70.1
301
+ # via huggingface-hub
302
+ truststore==0.10.4
303
+ # via
304
+ # httpcore2
305
+ # httpx2
306
+ typer==0.27.3
307
+ # via
308
+ # gradio
309
+ # hf-gradio
310
+ # openenv
311
+ typing-extensions==4.16.0
312
+ # via
313
+ # anyio
314
+ # exceptiongroup
315
+ # fastapi
316
+ # fastmcp-slim
317
+ # gradio
318
+ # gradio-client
319
+ # httpx2
320
+ # huggingface-hub
321
+ # mcp
322
+ # openai
323
+ # openenv
324
+ # opentelemetry-api
325
+ # py-key-value-aio
326
+ # pydantic
327
+ # pydantic-core
328
+ # referencing
329
+ # starlette
330
+ # typing-inspection
331
+ typing-inspection==0.4.4
332
+ # via
333
+ # fastapi
334
+ # mcp
335
+ # pydantic
336
+ # pydantic-settings
337
+ uncalled-for==0.4.1
338
+ # via fastmcp-slim
339
+ urllib3==2.8.0
340
+ # via requests
341
+ uvicorn==0.54.0
342
+ # via
343
+ # -r requirements.in
344
+ # fastmcp-slim
345
+ # gradio
346
+ # mcp
347
+ # openenv
348
+ watchfiles==1.3.0
349
+ # via fastmcp-slim
350
+ websockets==17.2
351
+ # via
352
+ # fastmcp-slim
353
+ # openenv
source/scripts/calibrate.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Play Qwen3.8-27B (thinking off) against a running server to measure per-task solve rates.
2
+
3
+ The HF token is read inside this process via huggingface_hub (HF_TOKEN_PATH selects the file);
4
+ it is never printed or written anywhere.
5
+
6
+ Usage: HF_TOKEN_PATH=... python scripts/calibrate.py --url http://localhost:8000 --episodes 4 --out reports/calibration/run1
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import random
12
+ import re
13
+ import sys
14
+ import threading
15
+ import time
16
+ import urllib.error
17
+ import urllib.request
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from pathlib import Path
20
+ from statistics import mean
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
+
25
+ from huggingface_hub import get_token # noqa: E402
26
+ from pydantic import ValidationError # noqa: E402
27
+
28
+ from five_desks.models import DeskAction # noqa: E402
29
+ from five_desks.tasks import TASK_IDS # noqa: E402
30
+ from wsclient import Session # noqa: E402
31
+
32
+ ROUTER = "https://router.huggingface.co/v1/chat/completions"
33
+ FINISH_ACTION = {"tool": "submit", "answer": {}}
34
+ _decoder = json.JSONDecoder(strict=False)
35
+
36
+
37
+ def system_prompt(action_schema: dict) -> str:
38
+ return (
39
+ "You are an agent acting in an environment. Reply to every message with exactly one JSON object and "
40
+ "nothing else: an action that matches the action schema below, or {\"finish\": true} to end the episode.\n"
41
+ f"Action schema: {json.dumps(action_schema)}"
42
+ )
43
+
44
+
45
+ def first_json_object(text: str):
46
+ text = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S)
47
+ for match in re.finditer(r"\{", text):
48
+ try:
49
+ obj, _ = _decoder.raw_decode(text[match.start():])
50
+ if isinstance(obj, dict):
51
+ return obj
52
+ except json.JSONDecodeError:
53
+ continue
54
+ return None
55
+
56
+
57
+ class Model:
58
+ def __init__(self, model: str, max_tokens: int, temperature: float, thinking: bool = False):
59
+ self.model, self.max_tokens, self.temperature, self.thinking = model, max_tokens, temperature, thinking
60
+ self._token = get_token()
61
+ if not self._token:
62
+ raise SystemExit("No Hugging Face token found (set HF_TOKEN_PATH).")
63
+ self.usage = {"prompt_tokens": 0, "completion_tokens": 0, "calls": 0}
64
+ self._lock = threading.Lock()
65
+ self.empty_examples = []
66
+
67
+ def chat(self, messages):
68
+ # Some provider responses come back with no content at all; retry those rather than score them.
69
+ for _ in range(3):
70
+ content, used, finish = self._chat_once(messages)
71
+ if content.strip() or finish == "length":
72
+ break
73
+ return content, used, finish
74
+
75
+ def _chat_once(self, messages):
76
+ body = {"model": self.model, "messages": messages, "max_tokens": self.max_tokens,
77
+ "temperature": self.temperature, "chat_template_kwargs": {"enable_thinking": self.thinking}}
78
+ for attempt in range(5):
79
+ req = urllib.request.Request(ROUTER, data=json.dumps(body).encode(), headers={
80
+ "Authorization": f"Bearer {self._token}", "Content-Type": "application/json"})
81
+ try:
82
+ with urllib.request.urlopen(req, timeout=180) as response:
83
+ data = json.load(response)
84
+ break
85
+ except urllib.error.HTTPError as exc:
86
+ if exc.code in (429, 500, 502, 503, 504) and attempt < 4:
87
+ time.sleep(2 ** attempt * 3)
88
+ continue
89
+ raise RuntimeError(f"inference HTTP {exc.code}: {exc.read().decode()[:200]}") from None
90
+ except (urllib.error.URLError, TimeoutError): # DNS hiccups and slow responses are retried too
91
+ if attempt < 4:
92
+ time.sleep(2 ** attempt * 3)
93
+ continue
94
+ raise
95
+ usage = data.get("usage") or {}
96
+ with self._lock:
97
+ self.usage["prompt_tokens"] += usage.get("prompt_tokens", 0)
98
+ self.usage["completion_tokens"] += usage.get("completion_tokens", 0)
99
+ self.usage["calls"] += 1
100
+ choice = data["choices"][0]
101
+ message = choice["message"]
102
+ content = message.get("content") or ""
103
+ if not content.strip():
104
+ with self._lock:
105
+ self.usage["empty_content"] = self.usage.get("empty_content", 0) + 1
106
+ self.empty_examples.append({k: v for k, v in message.items() if v})
107
+ return content, usage.get("completion_tokens", 0), choice.get("finish_reason")
108
+
109
+
110
+ def play(url, model, schema, task_id, completion_budget, context_budget):
111
+ messages = [{"role": "system", "content": system_prompt(schema)}]
112
+ episode = {"task_id": task_id, "turns": [], "end": None, "reward": 0.0}
113
+ completion_used = 0
114
+ with Session(url) as session:
115
+ episode["seed"] = random.SystemRandom().randrange(2**48)
116
+ data = session.reset(task_id=task_id, seed=episode["seed"])
117
+ obs = data["observation"]
118
+ while True:
119
+ obs_text = json.dumps({k: v for k, v in obs.items() if k != "metadata" or v})
120
+ messages.append({"role": "user", "content": obs_text})
121
+ if len(messages) > 2:
122
+ completion_used += len(obs_text) // 3 # later observations count against the budget
123
+ if completion_used >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget:
124
+ episode["end"] = "budget"
125
+ data = session.step(FINISH_ACTION)
126
+ break
127
+ reply, used, finish_reason = model.chat(messages)
128
+ completion_used += used
129
+ messages.append({"role": "assistant", "content": reply})
130
+ episode["turns"].append({"obs": obs_text[:4000], "reply": reply[:2000], "finish_reason": finish_reason, "tokens": used})
131
+ if finish_reason == "length":
132
+ episode["end"] = "truncated"
133
+ data = session.step(FINISH_ACTION)
134
+ break
135
+ action = first_json_object(reply)
136
+ if isinstance(action, dict) and set(action) == {"action"} and isinstance(action["action"], dict):
137
+ action = action["action"]
138
+ if action is None:
139
+ episode["end"] = "empty_reply" if not reply.strip() else "invalid_json"
140
+ data = session.step(FINISH_ACTION)
141
+ break
142
+ if action.get("finish") is True:
143
+ episode["end"] = "finish"
144
+ data = session.step(FINISH_ACTION)
145
+ break
146
+ try:
147
+ DeskAction.model_validate(action)
148
+ except ValidationError:
149
+ episode["end"] = "schema_invalid"
150
+ data = session.step(FINISH_ACTION)
151
+ break
152
+ data = session.step(action)
153
+ obs = data["observation"]
154
+ if data["done"]:
155
+ episode["end"] = "submitted" if action.get("tool") == "submit" else "out_of_steps"
156
+ episode["final"] = obs.get("output")
157
+ break
158
+ episode["reward"] = data.get("reward") or 0.0
159
+ episode["n_turns"] = len(episode["turns"])
160
+ episode["completion_tokens_est"] = completion_used
161
+ return episode
162
+
163
+
164
+ def main():
165
+ parser = argparse.ArgumentParser()
166
+ parser.add_argument("--url", default="http://localhost:8000")
167
+ parser.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra")
168
+ parser.add_argument("--episodes", type=int, default=4)
169
+ parser.add_argument("--tasks", default="", help="comma-separated task ids or prefixes (default: all)")
170
+ parser.add_argument("--workers", type=int, default=8)
171
+ parser.add_argument("--max-tokens", type=int, default=1024)
172
+ parser.add_argument("--temperature", type=float, default=1.0)
173
+ parser.add_argument("--completion-budget", type=int, default=8192)
174
+ parser.add_argument("--context-budget", type=int, default=16384)
175
+ parser.add_argument("--out", required=True)
176
+ args = parser.parse_args()
177
+
178
+ tasks = TASK_IDS
179
+ if args.tasks:
180
+ wanted = args.tasks.split(",")
181
+ tasks = [t for t in TASK_IDS if any(t.startswith(w) for w in wanted)]
182
+ with urllib.request.urlopen(f"{args.url}/schema", timeout=15) as response:
183
+ schema = json.load(response)["action"]
184
+ model = Model(args.model, args.max_tokens, args.temperature)
185
+ out = Path(args.out)
186
+ out.mkdir(parents=True, exist_ok=True)
187
+ jobs = [t for t in tasks for _ in range(args.episodes)]
188
+ started = time.monotonic()
189
+ results = []
190
+ with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log:
191
+ futures = [pool.submit(play, args.url, model, schema, t, args.completion_budget, args.context_budget) for t in jobs]
192
+ for fut in futures:
193
+ try:
194
+ ep = fut.result()
195
+ except Exception as exc: # infrastructure errors are excluded, not scored as 0
196
+ print("episode error:", exc, file=sys.stderr)
197
+ continue
198
+ results.append(ep)
199
+ log.write(json.dumps(ep) + "\n")
200
+
201
+ summary = {}
202
+ for task_id in tasks:
203
+ eps = [e for e in results if e["task_id"] == task_id]
204
+ if not eps:
205
+ continue
206
+ rewards = [e["reward"] for e in eps]
207
+ ends = {}
208
+ for e in eps:
209
+ ends[e["end"]] = ends.get(e["end"], 0) + 1
210
+ summary[task_id] = {"n": len(eps), "mean": round(mean(rewards), 3), "rewards": rewards,
211
+ "mixed": len(set(rewards)) > 1, "ends": ends,
212
+ "turns": round(mean(e["n_turns"] for e in eps), 1)}
213
+ report = {"model": args.model, "episodes": len(results), "seconds": round(time.monotonic() - started),
214
+ "usage": model.usage, "tasks": summary}
215
+ (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
216
+ (out / "empty_examples.json").write_text(json.dumps(model.empty_examples[:20], indent=2) + "\n")
217
+ print(f"{'task':24s} {'mean':>5s} rewards ends")
218
+ for task_id, s in summary.items():
219
+ print(f"{task_id:24s} {s['mean']:5.2f} {str(s['rewards']):30s} {s['ends']}")
220
+ print("usage:", model.usage, "seconds:", report["seconds"])
221
+
222
+
223
+ if __name__ == "__main__":
224
+ main()
source/scripts/calibrate_v2.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calibrate Five Desks against Qwen3.8-27B (thinking off) under the arena's reply rules.
2
+
3
+ A reply that is not exactly one JSON object, or an action that fails the schema, ends the episode through the
4
+ finish action. With --lenient, a reply with text around one JSON object is played instead: the v2 run showed the
5
+ arena accepts those (industrial trained at 0.80 against 0.31 measured strictly), and v1's lenient calibration
6
+ matched its arena run. The token is read in-process via HF_TOKEN_PATH and never printed.
7
+
8
+ Usage: HF_TOKEN_PATH=... .venv/bin/python scripts/calibrate_v2.py --url http://localhost:8001 --episodes 8 --out reports/calibration-v2/run1
9
+ """
10
+
11
+ import argparse
12
+ import json
13
+ import random
14
+ import sys
15
+ import time
16
+ import urllib.request
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from pathlib import Path
19
+ from statistics import mean
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
22
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
23
+
24
+ from pydantic import ValidationError # noqa: E402
25
+
26
+ from calibrate import Model, first_json_object, system_prompt # noqa: E402
27
+ from diligence.environment import TASK_IDS # noqa: E402
28
+ from diligence.models import ToolAction # noqa: E402
29
+ from proxy_eval.run import classify, unwrap # noqa: E402
30
+ from wsclient import Session # noqa: E402
31
+
32
+ FINISH = {"tool": "submit", "args": {}}
33
+
34
+
35
+ def play(url, model, schema, task_id, completion_budget, context_budget, extra="", lenient=False):
36
+ messages = [{"role": "system", "content": system_prompt(schema) + extra}]
37
+ ep = {"task_id": task_id, "turns": [], "end": None, "reward": 0.0, "bad_args": 0, "rescued": 0}
38
+ used_total, first = 0, True
39
+ with Session(url, timeout=60) as s:
40
+ ep["seed"] = random.SystemRandom().randrange(2**48)
41
+ data = s.reset(task_id=task_id, seed=ep["seed"])
42
+ while True:
43
+ obs = json.dumps({k: v for k, v in data["observation"].items() if k != "metadata" or v})
44
+ messages.append({"role": "user", "content": obs})
45
+ if not first:
46
+ used_total += len(obs) // 3
47
+ first = False
48
+ if used_total >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget:
49
+ ep["end"], data = "budget", s.step(FINISH)
50
+ break
51
+ reply, used, finish_reason = model.chat(messages)
52
+ used_total += used
53
+ messages.append({"role": "assistant", "content": reply})
54
+ ep["turns"].append({"obs": obs[:2500], "reply": reply[:2500]})
55
+ if finish_reason == "length":
56
+ ep["end"], data = "truncated", s.step(FINISH)
57
+ break
58
+ obj, kind = classify(reply)
59
+ if kind and lenient and (rescued := first_json_object(reply)) is not None:
60
+ obj, kind = rescued, None
61
+ ep["rescued"] += 1
62
+ if kind:
63
+ ep["end"], data = kind, s.step(FINISH)
64
+ break
65
+ action = unwrap(obj)
66
+ if action.get("finish") is True:
67
+ ep["end"], data = "finish", s.step(FINISH)
68
+ break
69
+ try:
70
+ ToolAction.model_validate(action)
71
+ except ValidationError:
72
+ ep["end"], data = "schema_invalid", s.step(FINISH)
73
+ break
74
+ data = s.step(action)
75
+ out = data["observation"].get("output", "")
76
+ if out.startswith(("Unknown tool", "Unknown argument", "Missing argument")) or "must be a" in out[:80]:
77
+ ep["bad_args"] += 1
78
+ if data["done"]:
79
+ ep["end"] = "submitted" if out.startswith("Submitted") else "out_of_steps"
80
+ break
81
+ ep["reward"] = data.get("reward") or 0.0
82
+ ep["n_turns"] = len(ep["turns"])
83
+ return ep
84
+
85
+
86
+ def main():
87
+ ap = argparse.ArgumentParser()
88
+ ap.add_argument("--url", default="http://localhost:8001")
89
+ ap.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra")
90
+ ap.add_argument("--episodes", type=int, default=8)
91
+ ap.add_argument("--tasks", default="")
92
+ ap.add_argument("--task-ids", default="", help="explicit comma-separated task ids (for other servers)")
93
+ ap.add_argument("--workers", type=int, default=8)
94
+ ap.add_argument("--temperature", type=float, default=1.0)
95
+ ap.add_argument("--max-tokens", type=int, default=2048)
96
+ ap.add_argument("--completion-budget", type=int, default=8192)
97
+ ap.add_argument("--context-budget", type=int, default=16384)
98
+ ap.add_argument("--system-extra", default="", help="file appended to the system prompt")
99
+ ap.add_argument("--lenient", action="store_true", help="play the JSON object out of replies with extra text")
100
+ ap.add_argument("--out", required=True)
101
+ args = ap.parse_args()
102
+ tasks = args.task_ids.split(",") if args.task_ids else [
103
+ t for t in TASK_IDS if not args.tasks or any(t.startswith(p) for p in args.tasks.split(","))]
104
+ with urllib.request.urlopen(f"{args.url}/schema", timeout=15) as r:
105
+ schema = json.load(r)["action"]
106
+ model = Model(args.model, args.max_tokens, args.temperature)
107
+ extra = "\n\n" + Path(args.system_extra).read_text().strip() if args.system_extra else ""
108
+ out = Path(args.out)
109
+ out.mkdir(parents=True, exist_ok=True)
110
+ started, results = time.monotonic(), []
111
+ jobs = [t for t in tasks for _ in range(args.episodes)]
112
+ with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log:
113
+ for fut in [pool.submit(play, args.url, model, schema, t, args.completion_budget, args.context_budget, extra, args.lenient) for t in jobs]:
114
+ try:
115
+ ep = fut.result()
116
+ except Exception as exc: # infrastructure errors are excluded, not scored
117
+ print("episode error:", repr(exc)[:200], file=sys.stderr)
118
+ continue
119
+ results.append(ep)
120
+ log.write(json.dumps(ep) + "\n")
121
+ log.flush()
122
+ summary = {}
123
+ for t in tasks:
124
+ eps = [e for e in results if e["task_id"] == t]
125
+ if not eps:
126
+ continue
127
+ ends = {}
128
+ for e in eps:
129
+ ends[e["end"]] = ends.get(e["end"], 0) + 1
130
+ summary[t] = {"n": len(eps), "mean": round(mean(e["reward"] for e in eps), 3),
131
+ "solved": sum(e["reward"] == 1.0 for e in eps), "rewards": [e["reward"] for e in eps],
132
+ "ends": ends, "turns": round(mean(e["n_turns"] for e in eps), 1),
133
+ "rescued_replies": sum(e.get("rescued", 0) for e in eps)}
134
+ report = {"model": args.model, "lenient": args.lenient, "episodes": len(results), "seconds": round(time.monotonic() - started),
135
+ "usage": model.usage, "tasks": summary}
136
+ (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n")
137
+ print(f"{'task':24s} {'mean':>5s} solved ends")
138
+ for t, s in summary.items():
139
+ print(f"{t:24s} {s['mean']:5.2f} {s['solved']:2d}/{s['n']:<2d} {s['ends']}")
140
+ print("usage:", model.usage, "seconds:", report["seconds"])
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
source/scripts/wsclient.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal OpenEnv WebSocket client used by the replay and calibration scripts."""
2
+
3
+ import json
4
+ from urllib.parse import urlsplit, urlunsplit
5
+
6
+ from websockets.sync.client import connect
7
+
8
+
9
+ def ws_url(base_url: str) -> str:
10
+ parts = urlsplit(base_url.rstrip("/"))
11
+ scheme = "wss" if parts.scheme == "https" else "ws"
12
+ return urlunsplit((scheme, parts.netloc, parts.path + "/ws", "", ""))
13
+
14
+
15
+ class Session:
16
+ def __init__(self, base_url: str, timeout: float = 30):
17
+ self.timeout = timeout
18
+ self.sock = connect(ws_url(base_url), open_timeout=timeout, close_timeout=5, max_size=2**22)
19
+
20
+ def _send(self, message: dict) -> dict:
21
+ self.sock.send(json.dumps(message))
22
+ response = json.loads(self.sock.recv(timeout=self.timeout))
23
+ if response.get("type") != "observation":
24
+ raise RuntimeError(f"unexpected response: {response}")
25
+ data = response["data"]
26
+ reward = data.get("reward")
27
+ assert isinstance(data.get("done"), bool), data
28
+ assert reward is None or (isinstance(reward, (int, float)) and 0 <= reward <= 1), data
29
+ return data
30
+
31
+ def reset(self, **kwargs) -> dict:
32
+ return self._send({"type": "reset", "data": kwargs})
33
+
34
+ def step(self, action: dict) -> dict:
35
+ return self._send({"type": "step", "data": action})
36
+
37
+ def close(self):
38
+ self.sock.close()
39
+
40
+ def __enter__(self):
41
+ return self
42
+
43
+ def __exit__(self, *exc):
44
+ self.close()
tasks.jsonl ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"task_id": "bugfix-finance-l1", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.5, "qwen3_8_27b_rewards": [1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0]}
2
+ {"task_id": "bugfix-finance-l2", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.125, "qwen3_8_27b_rewards": [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]}
3
+ {"task_id": "bugfix-industrial-l1", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.875, "qwen3_8_27b_rewards": [1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0]}
4
+ {"task_id": "bugfix-industrial-l2", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.375, "qwen3_8_27b_rewards": [0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0]}
5
+ {"task_id": "bugfix-math-l1", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.5, "qwen3_8_27b_rewards": [1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]}
6
+ {"task_id": "bugfix-math-l2", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.375, "qwen3_8_27b_rewards": [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]}
7
+ {"task_id": "bugfix-media-l1", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.375, "qwen3_8_27b_rewards": [0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0]}
8
+ {"task_id": "bugfix-media-l2", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.562, "qwen3_8_27b_rewards": [0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0]}
9
+ {"task_id": "bugfix-office-l1", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.562, "qwen3_8_27b_rewards": [0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]}
10
+ {"task_id": "bugfix-office-l2", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.625, "qwen3_8_27b_rewards": [0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]}
11
+ {"task_id": "bugfix-science-l1", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.312, "qwen3_8_27b_rewards": [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0]}
12
+ {"task_id": "bugfix-science-l2", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.25, "qwen3_8_27b_rewards": [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}
13
+ {"task_id": "bugfix-security-l1", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.75, "qwen3_8_27b_rewards": [1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0]}
14
+ {"task_id": "bugfix-security-l2", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.5, "qwen3_8_27b_rewards": [1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0]}
15
+ {"task_id": "bugfix-software-l1", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.75, "qwen3_8_27b_rewards": [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0]}
16
+ {"task_id": "bugfix-software-l2", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.688, "qwen3_8_27b_rewards": [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
17
+ {"task_id": "media-production-l1", "submitted_for_training": false, "qwen3_8_27b_mean_reward": 0.375, "qwen3_8_27b_rewards": [1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]}
18
+ {"task_id": "media-production-l2", "submitted_for_training": true, "qwen3_8_27b_mean_reward": 0.438, "qwen3_8_27b_rewards": [1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]}